Merge branch 'MSP-8520' into 'dev'
Resolve MSP-8520 See merge request isp/isp-admin-service!1
This commit is contained in:
commit
e0a35868af
371 files changed
+18636
-5443
No files matched your search
@@ -1,3 +1,11 @@
|
||||
### v7.1.0
|
||||
* переименование авторизации через SUDIR в OAuth:
|
||||
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
|
||||
* Колонка `users.sudir_user_id` → `users.oauth_user_id`
|
||||
* Переименованы ошибки: `ErrOauthAuthorization`, `ErrOauthIsMissed`
|
||||
* Метод `LoginWithSudir` → `LoginWithOauth`, поле `OauthUser.SudirUserId` → `OauthUser.OauthUserId`
|
||||
* Обновлены сообщения ошибок, логи, аудит и swagger-документация
|
||||
* в конфиге ключ OAuth-раздела `sudirAuth` → `oauth`
|
||||
### v7.0.0
|
||||
* Изменена логика авторизации через СУДИР:
|
||||
* Изменена схема конфигурации для авторизации через СУДИР
|
||||
|
||||
+12
-12
@@ -4,18 +4,18 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/service/delete_old_audit_worker"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/service/delete_old_audit_worker"
|
||||
"isp-admin-service/service/inactive_worker"
|
||||
"isp-admin-service/service/session_worker"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/app"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/dbrx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/http/httpclix"
|
||||
@@ -27,7 +27,7 @@ type Assembly struct {
|
||||
boot *bootstrap.Bootstrap
|
||||
db *dbrx.Client
|
||||
server *grpc.Server
|
||||
sudirCli *httpcli.Client
|
||||
oauthCli *httpcli.Client
|
||||
logger *log.Adapter
|
||||
bgjobCli *bgjobx.Client
|
||||
}
|
||||
@@ -45,7 +45,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
|
||||
db: db,
|
||||
server: grpc.NewServer(),
|
||||
logger: logger,
|
||||
sudirCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
||||
oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))),
|
||||
bgjobCli: bgjobCli,
|
||||
}, nil
|
||||
}
|
||||
@@ -67,13 +67,13 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client"))
|
||||
}
|
||||
|
||||
sudirBaseUrl := ""
|
||||
if newCfg.SudirAuth != nil {
|
||||
sudirBaseUrl = newCfg.SudirAuth.Host
|
||||
oauthBaseUrl := ""
|
||||
if newCfg.Oauth != nil {
|
||||
oauthBaseUrl = newCfg.Oauth.Host
|
||||
}
|
||||
a.sudirCli.GlobalRequestConfig().BaseUrl = sudirBaseUrl
|
||||
a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl
|
||||
|
||||
locator := NewLocator(a.logger, a.sudirCli, a.db)
|
||||
locator := NewLocator(a.logger, a.oauthCli, a.db)
|
||||
config, err := locator.Config(ctx, newCfg, time.Minute)
|
||||
if err != nil {
|
||||
a.logger.Fatal(ctx, errors.WithMessage(err, "locator config"))
|
||||
|
||||
+23
-23
@@ -4,16 +4,16 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/controller"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/routes"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/delete_old_audit_worker"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"msp-admin-service/service/secure"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"msp-admin-service/transaction"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/controller"
|
||||
"isp-admin-service/repository"
|
||||
"isp-admin-service/routes"
|
||||
"isp-admin-service/service"
|
||||
"isp-admin-service/service/delete_old_audit_worker"
|
||||
"isp-admin-service/service/inactive_worker"
|
||||
"isp-admin-service/service/secure"
|
||||
"isp-admin-service/service/session_worker"
|
||||
"isp-admin-service/transaction"
|
||||
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
@@ -31,14 +31,14 @@ type DB interface {
|
||||
|
||||
type Locator struct {
|
||||
logger log.Logger
|
||||
sudirCli *httpcli.Client
|
||||
oauthCli *httpcli.Client
|
||||
db DB
|
||||
}
|
||||
|
||||
func NewLocator(logger log.Logger, sudirCli *httpcli.Client, db DB) Locator {
|
||||
func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator {
|
||||
return Locator{
|
||||
logger: logger,
|
||||
sudirCli: sudirCli,
|
||||
oauthCli: oauthCli,
|
||||
db: db,
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ func (l Locator) Config(
|
||||
cfg conf.Remote,
|
||||
jobPollInterval time.Duration,
|
||||
) (Config, error) {
|
||||
sudirRepo := repository.NewSudir(l.sudirCli)
|
||||
oauthRepo := repository.NewOauth(l.oauthCli)
|
||||
roleRepo := repository.NewRole(l.db)
|
||||
userRepo := repository.NewUser(l.db)
|
||||
tokenRepo := repository.NewToken(l.db)
|
||||
@@ -65,10 +65,10 @@ func (l Locator) Config(
|
||||
auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings)
|
||||
tokenService := service.NewToken(tokenRepo, cfg.ExpireSec)
|
||||
|
||||
sudirBaseUrl, sudirSettings := l.getSudirSettings(cfg.SudirAuth)
|
||||
sudirService, err := service.NewSudir(sudirSettings, sudirRepo)
|
||||
oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth)
|
||||
oauthService, err := service.NewOauth(oauthSettings, oauthRepo)
|
||||
if err != nil {
|
||||
return Config{}, errors.WithMessage(err, "new sudir")
|
||||
return Config{}, errors.WithMessage(err, "new oauth")
|
||||
}
|
||||
|
||||
secureService := secure.NewService(tokenRepo, userRoleRepo)
|
||||
@@ -87,7 +87,7 @@ func (l Locator) Config(
|
||||
l.logger,
|
||||
)
|
||||
authService := service.NewAuth(
|
||||
userRepo, txManager, tokenService, sudirService, auditService, l.logger,
|
||||
userRepo, txManager, tokenService, oauthService, auditService, l.logger,
|
||||
cfg.AntiBruteforce.DelayLoginRequestInSec,
|
||||
cfg.AntiBruteforce.MaxInFlightLoginRequests,
|
||||
)
|
||||
@@ -95,7 +95,7 @@ func (l Locator) Config(
|
||||
|
||||
permissionsService := service.NewPermission(cfg.Permissions)
|
||||
|
||||
uiSettingsService := service.NewUiSettings(sudirBaseUrl, sudirSettings)
|
||||
uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings)
|
||||
|
||||
userController := controller.NewUser(userService)
|
||||
customizationController := controller.NewCustomization(cfg.UiDesign)
|
||||
@@ -152,10 +152,10 @@ func (l Locator) Config(
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (l Locator) getSudirSettings(sudirAuth *conf.SudirAuth) (string, []conf.SudirClientConfig) {
|
||||
if sudirAuth == nil {
|
||||
return "", []conf.SudirClientConfig{}
|
||||
func (l Locator) getOauthSettings(oauthAuth *conf.Oauth) (string, []conf.OauthClientConfig) {
|
||||
if oauthAuth == nil {
|
||||
return "", []conf.OauthClientConfig{}
|
||||
}
|
||||
|
||||
return sudirAuth.Host, sudirAuth.Clients
|
||||
return oauthAuth.Host, oauthAuth.Clients
|
||||
}
|
||||
+2
-2
@@ -7,11 +7,11 @@ grpcOuterAddress:
|
||||
grpcInnerAddress:
|
||||
ip: 0.0.0.0
|
||||
port: 9007
|
||||
moduleName: msp-admin-service
|
||||
moduleName: isp-admin-service
|
||||
infraServerPort: 9557
|
||||
|
||||
logfile:
|
||||
path: /var/log/msp-admin-service/runtime.log
|
||||
path: /var/log/isp-admin-service/runtime.log
|
||||
maxSizeMb: 512
|
||||
maxBackups: 4
|
||||
compress: true
|
||||
+11
-12
@@ -24,7 +24,7 @@ type Remote struct {
|
||||
ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"`
|
||||
UiDesign UIDesign `schema:"Кастомизация интерфейса"`
|
||||
IdleTimeoutMs int `schema:"Время бездействия пользователя,в милисекундах, после указанного времени пользователь будет разлогирован из интерфейса в браузере, по умолчанию отключено"`
|
||||
SudirAuth *SudirAuth `schema:"СУДИР авторизация"`
|
||||
Oauth *Oauth `schema:"OAuth авторизация"`
|
||||
LogLevel log.Level `schemaGen:"logLevel" schema:"Уровень логирования"`
|
||||
AntiBruteforce AntiBruteforce `schema:"Настройки антибрут для admin login"`
|
||||
BlockInactiveWorker BlockInactiveWorker `validate:"required" schema:"Блокировка неактивных УЗ"`
|
||||
@@ -51,23 +51,22 @@ type UIDesign struct {
|
||||
PrimaryColor string `schema:"Цвет в HEX,примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"`
|
||||
}
|
||||
|
||||
type SudirAuth struct {
|
||||
Host string `validate:"required" schema:"Базовый путь до методов СУДИР, пример https://sudir.mos.ru"`
|
||||
Clients []SudirClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия с СУДИР для логина по authCode"`
|
||||
type Oauth struct {
|
||||
Host string `validate:"required" schema:"Базовый путь до методов, пример https://oauth.example.com"`
|
||||
Clients []OauthClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия для логина по authCode"`
|
||||
}
|
||||
|
||||
//nolint:lll
|
||||
type SudirClientConfig struct {
|
||||
type OauthClientConfig struct {
|
||||
ClientName string `validate:"required" schema:"Уникальное имя конфигурации клиента"`
|
||||
ClientId string `validate:"required" schema:"Идентификатор клиента,выданный СУДИР для basicAuth"`
|
||||
ClientSecret string `validate:"required" schema:"Пароль клиента,выданный СУДИР для basicAuth"`
|
||||
ClientId string `validate:"required" schema:"Идентификатор клиента,выданный для basicAuth"`
|
||||
ClientSecret string `validate:"required" schema:"Пароль клиента,выданный для basicAuth"`
|
||||
RedirectURI string `validate:"required" schema:"URI для редиректа,передаётся в запросе токена в query"`
|
||||
UiSetting *UiSudirSetting `schema:"Настройки СУДИР для админки"`
|
||||
UiSetting *UiOauthSetting `schema:"Настройки OAuth для админки"`
|
||||
}
|
||||
|
||||
type UiSudirSetting struct {
|
||||
LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через СУДИР в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"`
|
||||
LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через СУДИР в адмиинке"`
|
||||
type UiOauthSetting struct {
|
||||
LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через OAuth в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"`
|
||||
LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через OAuth в адмиинке"`
|
||||
}
|
||||
|
||||
type AntiBruteforce struct {
|
||||
|
||||
+2
-1
@@ -3,8 +3,9 @@ package conf_test
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"isp-admin-service/conf"
|
||||
|
||||
"github.com/txix-open/isp-kit/test/rct"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
func TestDefaultRemoteConfig(t *testing.T) {
|
||||
|
||||
+2
-2
@@ -3,9 +3,9 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
+14
-14
@@ -4,9 +4,9 @@ import (
|
||||
"context"
|
||||
"strconv"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
|
||||
type authService interface {
|
||||
Login(ctx context.Context, request domain.LoginRequest) (*domain.LoginResponse, error)
|
||||
LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error)
|
||||
LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error)
|
||||
Logout(ctx context.Context, adminId int64, request *domain.LogoutRequest) error
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
||||
auth, err := a.authService.Login(ctx, authRequest)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthorization):
|
||||
case errors.Is(err, domain.ErrOauthAuthorization):
|
||||
return nil, status.Error(codes.InvalidArgument, "plain auth is not available")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
a.logger.Error(ctx, err.Error())
|
||||
@@ -113,28 +113,28 @@ func (a Auth) Login(ctx context.Context, authRequest domain.LoginRequest) (*doma
|
||||
}
|
||||
}
|
||||
|
||||
// LoginWithSudir
|
||||
// LoginWithOauth
|
||||
// @Tags auth
|
||||
// @Summary Авторизация по авторизационному коду от СУДИР
|
||||
// @Summary Авторизация по авторизационному коду от OAuth
|
||||
// @Description Авторизация с получением токена администратора
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.LoginSudirRequest true "Тело запроса"
|
||||
// @Param body body domain.LoginOauthRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.LoginResponse
|
||||
// @Failure 401 {object} domain.GrpcError "Некорректный код для авторизации или неизвестное название клиента"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация СУДИР не настроена на сервере"
|
||||
// @Failure 412 {object} domain.GrpcError "Авторизация OAuth не настроена на сервере"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /auth/login_with_sudir [POST]
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithSudir(ctx, request)
|
||||
// @Router /auth/login_with_oauth [POST]
|
||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||
auth, err := a.authService.LoginWithOauth(ctx, request)
|
||||
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrSudirAuthIsMissed):
|
||||
return nil, status.Error(codes.FailedPrecondition, "sudir auth is not configured")
|
||||
case errors.Is(err, domain.ErrOauthIsMissed):
|
||||
return nil, status.Error(codes.FailedPrecondition, "oauth is not configured")
|
||||
case errors.Is(err, domain.ErrUnauthenticated):
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid code")
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "login with sudir")
|
||||
return nil, errors.WithMessage(err, "login with oauth")
|
||||
default:
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type Customization struct {
|
||||
|
||||
@@ -3,7 +3,7 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type permissionsService interface {
|
||||
|
||||
+3
-2
@@ -3,11 +3,12 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type roleService interface {
|
||||
|
||||
@@ -3,9 +3,10 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"msp-admin-service/domain"
|
||||
)
|
||||
|
||||
type SecureService interface {
|
||||
|
||||
@@ -3,7 +3,7 @@ package controller
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type SessionService interface {
|
||||
|
||||
+10
-10
@@ -2,15 +2,15 @@ package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type UiSettingsService interface {
|
||||
SudirSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiSudirSetting, error)
|
||||
OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error)
|
||||
}
|
||||
|
||||
type UiSettings struct {
|
||||
@@ -23,20 +23,20 @@ func NewUiSettings(service UiSettingsService) UiSettings {
|
||||
}
|
||||
}
|
||||
|
||||
// UiSudirSettings
|
||||
// UiOauthSettings
|
||||
// @Tags ui_settings
|
||||
// @Summary Получение настроек для ui для авторизации через СУДИР
|
||||
// @Description Получение настроек для ui для авторизации через СУДИР
|
||||
// @Summary Получение настроек для ui для авторизации через OAuth
|
||||
// @Description Получение настроек для ui для авторизации через OAuth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ClientNameRequest true "Тело запроса"
|
||||
// @Success 200 {object} domain.UiSudirSetting
|
||||
// @Success 200 {object} domain.UiOauthSetting
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента"
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /ui_settings/sudir [POST]
|
||||
func (c UiSettings) SudirSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiSudirSetting, error) {
|
||||
resp, err := c.service.SudirSettings(ctx, req)
|
||||
// @Router /ui_settings/oauth [POST]
|
||||
func (c UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||
resp, err := c.service.OauthSettings(ctx, req)
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrUnknownClient):
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid client name")
|
||||
|
||||
+2
-2
@@ -5,9 +5,9 @@ import (
|
||||
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/domain"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
+28
-28
@@ -2,7 +2,7 @@
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "сервис управления администраторами",
|
||||
"title": "msp-admin-service",
|
||||
"title": "isp-admin-service",
|
||||
"contact": {},
|
||||
"license": {
|
||||
"name": "GNU GPL v3.0"
|
||||
@@ -64,7 +64,7 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/auth/login_with_sudir": {
|
||||
"/auth/login_with_oauth": {
|
||||
"post": {
|
||||
"description": "Авторизация с получением токена администратора",
|
||||
"consumes": [
|
||||
@@ -76,7 +76,7 @@
|
||||
"tags": [
|
||||
"auth"
|
||||
],
|
||||
"summary": "Авторизация по авторизационному коду от СУДИР",
|
||||
"summary": "Авторизация по авторизационному коду от OAuth",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
@@ -84,7 +84,7 @@
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.LoginSudirRequest"
|
||||
"$ref": "#/definitions/domain.LoginOauthRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -102,7 +102,7 @@
|
||||
}
|
||||
},
|
||||
"412": {
|
||||
"description": "Авторизация СУДИР не настроена на сервере",
|
||||
"description": "Авторизация OAuth не настроена на сервере",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.GrpcError"
|
||||
}
|
||||
@@ -761,9 +761,9 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/ui_settings/sudir": {
|
||||
"/ui_settings/oauth": {
|
||||
"post": {
|
||||
"description": "Получение настроек для ui для авторизации через СУДИР",
|
||||
"description": "Получение настроек для ui для авторизации через OAuth",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
@@ -773,7 +773,7 @@
|
||||
"tags": [
|
||||
"ui_settings"
|
||||
],
|
||||
"summary": "Получение настроек для ui для авторизации через СУДИР",
|
||||
"summary": "Получение настроек для ui для авторизации через OAuth",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
@@ -789,7 +789,7 @@
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.UiSudirSetting"
|
||||
"$ref": "#/definitions/domain.UiOauthSetting"
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
@@ -1698,6 +1698,23 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LoginOauthRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authCode",
|
||||
"clientName"
|
||||
],
|
||||
"properties": {
|
||||
"authCode": {
|
||||
"description": "Код для авторизации у OAuth-провайдера",
|
||||
"type": "string"
|
||||
},
|
||||
"clientName": {
|
||||
"description": "Уникальное имя конфигурации клиента",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LoginRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
@@ -1732,23 +1749,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LoginSudirRequest": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"authCode",
|
||||
"clientName"
|
||||
],
|
||||
"properties": {
|
||||
"authCode": {
|
||||
"description": "Код для авторизации в СУДИР",
|
||||
"type": "string"
|
||||
},
|
||||
"clientName": {
|
||||
"description": "Уникальное имя конфигурации клиента",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.LogoutRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -2033,11 +2033,11 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.UiSudirSetting": {
|
||||
"domain.UiOauthSetting": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"loginUrl": {
|
||||
"description": "URL для получения authCode для авторизации через СУДИР",
|
||||
"description": "URL для получения authCode для авторизации через OAuth",
|
||||
"type": "string"
|
||||
},
|
||||
"logoutUrl": {
|
||||
|
||||
+3
-3
@@ -3,7 +3,7 @@ package domain
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -13,8 +13,8 @@ const (
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUnauthenticated = errors.New("authentication failure")
|
||||
ErrSudirAuthorization = errors.New("User is authorized only with SUDIR")
|
||||
ErrSudirAuthIsMissed = errors.New("SUDIR authorization is not configured on the server")
|
||||
ErrOauthAuthorization = errors.New("user is authorized only with oauth")
|
||||
ErrOauthIsMissed = errors.New("oauth is not configured on the server")
|
||||
ErrInvalid = errors.New("entity is invalid")
|
||||
ErrAlreadyExists = errors.New("already exists")
|
||||
ErrTokenExpired = errors.New("token expired")
|
||||
|
||||
+2
-2
@@ -14,8 +14,8 @@ type LoginRequest struct {
|
||||
Password string ` validate:"required"` // Пароль
|
||||
}
|
||||
|
||||
type LoginSudirRequest struct {
|
||||
AuthCode string `validate:"required"` // Код для авторизации в СУДИР
|
||||
type LoginOauthRequest struct {
|
||||
AuthCode string `validate:"required"` // Код для авторизации у OAuth-провайдера
|
||||
ClientName string `validate:"required"` // Уникальное имя конфигурации клиента
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ type ClientNameRequest struct {
|
||||
ClientName string `validate:"required"`
|
||||
}
|
||||
|
||||
type UiSudirSetting struct {
|
||||
LoginUrl string // URL для получения authCode для авторизации через СУДИР
|
||||
type UiOauthSetting struct {
|
||||
LoginUrl string // URL для получения authCode для авторизации через OAuth
|
||||
LogoutUrl string // URL для завершения сессии
|
||||
}
|
||||
@@ -12,18 +12,18 @@ type ClientSetting struct {
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,godoclint
|
||||
type SudirAuthError struct {
|
||||
type OauthAuthError struct {
|
||||
ErrorName string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
}
|
||||
|
||||
func (s *SudirAuthError) Error() string {
|
||||
func (s *OauthAuthError) Error() string {
|
||||
return fmt.Sprintf("error: %s; description: %s", s.ErrorName, s.ErrorDescription)
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,errname,godoclint
|
||||
type SudirUserResponse struct {
|
||||
*SudirAuthError
|
||||
type OauthUserResponse struct {
|
||||
*OauthAuthError
|
||||
|
||||
Email string `json:"email"`
|
||||
Groups []string `json:"groups"`
|
||||
@@ -34,8 +34,8 @@ type SudirUserResponse struct {
|
||||
}
|
||||
|
||||
// nolint:tagliatelle,errname,godoclint
|
||||
type SudirTokenResponse struct {
|
||||
*SudirAuthError
|
||||
type OauthTokenResponse struct {
|
||||
*OauthAuthError
|
||||
|
||||
IdToken string `json:"id_token"`
|
||||
AccessToken string `json:"access_token"`
|
||||
+3
-3
@@ -3,7 +3,7 @@ package entity
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
SudirUserId *string
|
||||
OauthUserId *string
|
||||
Id int64
|
||||
FirstName string
|
||||
LastName string
|
||||
@@ -18,9 +18,9 @@ type User struct {
|
||||
LastSessionCreatedAt *time.Time
|
||||
}
|
||||
|
||||
type SudirUser struct {
|
||||
type OauthUser struct {
|
||||
RoleIds []int
|
||||
SudirUserId string
|
||||
OauthUserId string
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
module msp-admin-service
|
||||
module isp-admin-service
|
||||
|
||||
go 1.26.0
|
||||
|
||||
@@ -6,39 +6,37 @@ require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/iancoleman/strcase v0.3.0
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/txix-open/bgjob v1.6.0
|
||||
github.com/txix-open/isp-kit v1.74.0
|
||||
github.com/txix-open/isp-kit v1.74.1
|
||||
github.com/txix-open/jsonschema v1.3.0
|
||||
golang.org/x/crypto v0.54.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
golang.org/x/sync v0.22.0
|
||||
google.golang.org/grpc v1.83.0
|
||||
google.golang.org/grpc v1.83.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/buger/jsonparser v1.6.0 // indirect
|
||||
github.com/buger/jsonparser v1.6.1 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/coder/websocket v1.8.15 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 // indirect
|
||||
github.com/getsentry/sentry-go v0.48.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.10.1 // indirect
|
||||
github.com/getsentry/sentry-go v0.49.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.11.0 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx/v5 v5.10.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.19.1 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
github.com/leodido/go-urn v1.5.0 // indirect
|
||||
@@ -48,7 +46,6 @@ require (
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/pressly/goose/v3 v3.27.3 // indirect
|
||||
github.com/prometheus/client_golang v1.24.1 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
@@ -64,22 +61,23 @@ require (
|
||||
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
|
||||
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 // indirect
|
||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 // indirect
|
||||
go.opentelemetry.io/otel v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.46.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
@@ -9,8 +9,8 @@ github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPn
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/buger/jsonparser v1.6.0 h1:IHTgLjkgckOjAp8p0aYfXkv+cqC+zrzALg/JywnPjxY=
|
||||
github.com/buger/jsonparser v1.6.0/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/buger/jsonparser v1.6.1 h1:I0phFv0PlbLHnM7TZAVjZ2MJ2/eWRTDyuO7GLR98IEs=
|
||||
github.com/buger/jsonparser v1.6.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
@@ -19,20 +19,18 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU
|
||||
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/getsentry/sentry-go v0.48.0 h1:FRZNr7Uk1C86ev1bSJmYlUkL9oyivQA6YOcdYfaaMmY=
|
||||
github.com/getsentry/sentry-go v0.48.0/go.mod h1:E5UkA5wp1qR2+MDydNYlVeUiNN2xEdjYMidkgf0Qoss=
|
||||
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
|
||||
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.10.1 h1:mGH3y0X8AfrXsfgPsPuTkWBYIebomvdkWEN1uDLoFFg=
|
||||
github.com/go-faker/faker/v4 v4.10.1/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120=
|
||||
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
@@ -56,8 +54,8 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
@@ -74,8 +72,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk=
|
||||
github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -114,8 +112,6 @@ github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTw
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
|
||||
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
@@ -126,8 +122,8 @@ github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0 h1:L8NA1WtF76C6KA3LAoufjfLgbist/If1UQYcsOjtxXA=
|
||||
github.com/rabbitmq/amqp091-go v1.13.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||
@@ -147,8 +143,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/txix-open/bellows v1.2.0 h1:CXv8nQaZtB/micraeRilYyj/gtfv+bqBgP5aPYQgjeY=
|
||||
github.com/txix-open/bellows v1.2.0/go.mod h1:qbKCy+RTgD30Qpw1fyb3y3jp5Y9mGhLLxgae1l0W92o=
|
||||
github.com/txix-open/bgjob v1.6.0 h1:Vwj9cAsIhMrHPKRZVxfg6mHqE9LI/atDCq1aeihH3+I=
|
||||
@@ -157,8 +153,8 @@ github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlf
|
||||
github.com/txix-open/etp/v4 v4.1.3/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM=
|
||||
github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y=
|
||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
||||
github.com/txix-open/isp-kit v1.74.0 h1:Gi1X8Jnf9ppV4TXq4kMCBgBjJjqSKh57X8038I+tQFw=
|
||||
github.com/txix-open/isp-kit v1.74.0/go.mod h1:Kob233jk1j/Js7UmopJ5b7JpVZrpWbagEAjasgfqTdk=
|
||||
github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
|
||||
github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
@@ -174,24 +170,24 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17
|
||||
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0 h1:MCcYL7J6Vt/X0kjqbMZkekCmwsurbQRbL69vkiye2lk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.69.0/go.mod h1:3jnStNwSufK+f5ktjL4EPcwtig4rtd81NS70lqHuXl8=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0 h1:4YsVu3B8+3qtWYYrsUYgn0OG78pN0rnNPRGX4SbokQI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.44.0/go.mod h1:+wnlSn0mD1ADVMe3v9Z/WIaiz6q6gL2J/ejaAmdmv80=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0 h1:lgh3PiVrRUWMLOVSkQicxzZll5NjF1r+AtsX1XRIHw0=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.44.0/go.mod h1:5Cnhth3m/AgOeTgE3ex12pPmiu/gGtZit03kSzx9X7s=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
|
||||
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
|
||||
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
|
||||
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
|
||||
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
@@ -202,28 +198,28 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0 h1:ybvH/ZpOcpCrjtkb7oW/fdlzbEmRVeumw19SRQmNFKU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:HJ9MpJLeDSstBkx1LILTpd5f41ADSMZcTPypw02qEGw=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0 h1:mJiOtnGp0k/BcSgdu03G2NwnscCfCH+h2QKUBZr18KI=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260729162451-8efbd57d26e0/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
|
||||
google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/routes"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/routes"
|
||||
|
||||
"github.com/txix-open/isp-kit/bootstrap"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
var version = "1.0.0"
|
||||
|
||||
// @title msp-admin-service
|
||||
// @title isp-admin-service
|
||||
// @version 1.0.0
|
||||
// @description сервис управления администраторами
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE users RENAME COLUMN sudir_user_id TO oauth_user_id;
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE users RENAME COLUMN oauth_user_id TO sudir_user_id;
|
||||
+3
-3
@@ -4,14 +4,14 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/iancoleman/strcase"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/metrics/http_metrics"
|
||||
)
|
||||
@@ -17,20 +17,20 @@ const (
|
||||
getUserEndpoint = "/oauth/me"
|
||||
)
|
||||
|
||||
type Sudir struct {
|
||||
type Oauth struct {
|
||||
cli *httpcli.Client
|
||||
}
|
||||
|
||||
func NewSudir(cli *httpcli.Client) Sudir {
|
||||
return Sudir{
|
||||
func NewOauth(cli *httpcli.Client) Oauth {
|
||||
return Oauth{
|
||||
cli: cli,
|
||||
}
|
||||
}
|
||||
|
||||
func (s Sudir) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.SudirTokenResponse, error) {
|
||||
func (s Oauth) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.OauthTokenResponse, error) {
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, getTokenEndpoint)
|
||||
|
||||
response := entity.SudirTokenResponse{}
|
||||
response := entity.OauthTokenResponse{}
|
||||
err := s.cli.Post(getTokenEndpoint).
|
||||
BasicAuth(httpcli.BasicAuth{
|
||||
Username: clientSetting.ClientId,
|
||||
@@ -52,10 +52,10 @@ func (s Sudir) GetToken(ctx context.Context, clientSetting entity.ClientSetting)
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (s Sudir) GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) {
|
||||
func (s Oauth) GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error) {
|
||||
ctx = http_metrics.ClientEndpointToContext(ctx, getUserEndpoint)
|
||||
|
||||
response := entity.SudirUserResponse{}
|
||||
response := entity.OauthUserResponse{}
|
||||
err := s.cli.Get(getUserEndpoint).
|
||||
Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)).
|
||||
JsonResponseBody(&response).
|
||||
+4
-3
@@ -4,13 +4,14 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
|
||||
+3
-3
@@ -9,12 +9,12 @@ import (
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/iancoleman/strcase"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
|
||||
+21
-21
@@ -6,14 +6,14 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/iancoleman/strcase"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ const (
|
||||
passwordUsersColumn = "password"
|
||||
createdAtUsersColumn = "created_at"
|
||||
updatedAtUsersColumn = "updated_at"
|
||||
sudirUserIdUsersColumn = "sudir_user_id"
|
||||
oauthUserIdUsersColumn = "oauth_user_id"
|
||||
blockedUsersColumn = "blocked"
|
||||
descriptionUsersColumn = "description"
|
||||
lastActiveAtUsersColumn = "last_active_at"
|
||||
@@ -45,7 +45,7 @@ func (u User) GetUserByEmail(ctx context.Context, email string) (*entity.User, e
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(squirrel.Eq{"email": email}).
|
||||
@@ -72,7 +72,7 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(squirrel.Eq{"id": identity}).
|
||||
@@ -94,17 +94,17 @@ func (u User) GetUserById(ctx context.Context, identity int64) (*entity.User, er
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmail")
|
||||
func (u User) GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.GetUserByEmailAndOauthId")
|
||||
|
||||
equalClause := squirrel.Eq{"email": email, "sudir_user_id": nil}
|
||||
if sudirUserId != "" {
|
||||
equalClause["sudir_user_id"] = sudirUserId
|
||||
equalClause := squirrel.Eq{"email": email, "oauth_user_id": nil}
|
||||
if oauthUserId != "" {
|
||||
equalClause["oauth_user_id"] = oauthUserId
|
||||
}
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(equalClause).
|
||||
@@ -126,13 +126,13 @@ func (u User) GetUserByEmailAndSudirId(ctx context.Context, email string, sudirU
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertBySudirUserId")
|
||||
func (u User) UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "User.UpsertByOauthUserId")
|
||||
|
||||
selectQ := `
|
||||
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, sudir_user_id)
|
||||
insert into users as u (first_name, last_name, full_name, email, created_at, updated_at, oauth_user_id)
|
||||
values ($1, $2, $3, $4, $5, $6, $7)
|
||||
on conflict (sudir_user_id) do update
|
||||
on conflict (oauth_user_id) do update
|
||||
set first_name = excluded.first_name,
|
||||
last_name = excluded.last_name,
|
||||
full_name = excluded.full_name,
|
||||
@@ -145,7 +145,7 @@ func (u User) UpsertBySudirUserId(ctx context.Context, user entity.User) (*entit
|
||||
err := u.db.SelectRow(ctx,
|
||||
&result,
|
||||
selectQ,
|
||||
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.SudirUserId,
|
||||
user.FirstName, user.LastName, user.FullName, user.Email, user.CreatedAt, user.UpdatedAt, user.OauthUserId,
|
||||
)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, domain.ErrUserIsBlocked
|
||||
@@ -162,7 +162,7 @@ func (u User) GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]enti
|
||||
|
||||
q := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
||||
From("users").
|
||||
Offset(req.Offset).
|
||||
@@ -193,7 +193,7 @@ func (u User) GetAllUsers(ctx context.Context) ([]entity.User, error) {
|
||||
|
||||
query, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn, "(SELECT max(created_at) FROM tokens WHERE tokens.user_id = users.id) as last_session_created_at").
|
||||
From("users").ToSql()
|
||||
if err != nil {
|
||||
@@ -214,7 +214,7 @@ func (u User) GetUsersByEmail(ctx context.Context, email string) ([]entity.User,
|
||||
|
||||
q, args, err := query.New().
|
||||
Select(idUsersColumn, firstNameUsersColumn, lastNameUsersColumn, emailUsersColumn, passwordUsersColumn, createdAtUsersColumn,
|
||||
updatedAtUsersColumn, sudirUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
updatedAtUsersColumn, oauthUserIdUsersColumn, blockedUsersColumn, descriptionUsersColumn, lastActiveAtUsersColumn,
|
||||
fullNameUsersColumn).
|
||||
From("users").
|
||||
Where(squirrel.Eq{"email": email}).
|
||||
@@ -274,7 +274,7 @@ func (u User) UpdateUser(ctx context.Context, id int64, user entity.UpdateUser)
|
||||
descriptionUsersColumn: user.Description,
|
||||
}).
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
Suffix("RETURNING id, first_name, last_name, full_name, email, sudir_user_id, description, created_at, updated_at").
|
||||
Suffix("RETURNING id, first_name, last_name, full_name, email, oauth_user_id, description, created_at, updated_at").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
|
||||
@@ -3,12 +3,13 @@ package repository
|
||||
import (
|
||||
"context"
|
||||
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/Masterminds/squirrel"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/metrics/sql_metrics"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
type UserRole struct {
|
||||
|
||||
+7
-7
@@ -1,8 +1,8 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"msp-admin-service/controller"
|
||||
"msp-admin-service/docs"
|
||||
"isp-admin-service/controller"
|
||||
"isp-admin-service/docs"
|
||||
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/common_endpoints"
|
||||
@@ -50,9 +50,9 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
Handler: c.Auth.Login,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/login_with_sudir",
|
||||
Path: "admin/auth/login_with_oauth",
|
||||
Inner: false,
|
||||
Handler: c.Auth.LoginWithSudir,
|
||||
Handler: c.Auth.LoginWithOauth,
|
||||
},
|
||||
{
|
||||
Path: "admin/auth/logout",
|
||||
@@ -189,16 +189,16 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor {
|
||||
Handler: c.Secure.Authorize,
|
||||
},
|
||||
{
|
||||
Path: "admin/ui_settings/sudir",
|
||||
Path: "admin/ui_settings/oauth",
|
||||
Inner: false,
|
||||
Handler: c.UiSettings.SudirSettings,
|
||||
Handler: c.UiSettings.OauthSettings,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func commonEndpoints() []cluster.EndpointDescriptor {
|
||||
return common_endpoints.CommonEndpoints(
|
||||
"msp-admin-service",
|
||||
"isp-admin-service",
|
||||
common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson),
|
||||
)
|
||||
}
|
||||
|
||||
+4
-4
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
+30
-30
@@ -5,10 +5,10 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -30,7 +30,7 @@ type auditService interface {
|
||||
|
||||
type userRepository interface {
|
||||
GetUserByEmail(ctx context.Context, email string) (*entity.User, error)
|
||||
UpsertBySudirUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||
UpsertByOauthUserId(ctx context.Context, user entity.User) (*entity.User, error)
|
||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||
UpdateLastActiveAt(ctx context.Context, userId int64, lastActiveAt time.Time) error
|
||||
}
|
||||
@@ -40,15 +40,15 @@ type tokenService interface {
|
||||
RevokeAllByUserId(ctx context.Context, userId int64) error
|
||||
}
|
||||
|
||||
type sudirService interface {
|
||||
Authenticate(ctx context.Context, request domain.LoginSudirRequest, repo roleRepo) (*entity.SudirUser, error)
|
||||
type oauthService interface {
|
||||
Authenticate(ctx context.Context, request domain.LoginOauthRequest, repo roleRepo) (*entity.OauthUser, error)
|
||||
}
|
||||
|
||||
type Auth struct {
|
||||
userRepository userRepository
|
||||
txRunner AuthTransactionRunner
|
||||
tokenService tokenService
|
||||
sudirService sudirService
|
||||
oauthService oauthService
|
||||
auditService auditService
|
||||
logger log.Logger
|
||||
maxInFlightLoginRequests int64
|
||||
@@ -60,7 +60,7 @@ func NewAuth(
|
||||
userRepository userRepository,
|
||||
txRunner AuthTransactionRunner,
|
||||
tokenService tokenService,
|
||||
sudirService sudirService,
|
||||
oauthService oauthService,
|
||||
auditService auditService,
|
||||
logger log.Logger,
|
||||
delayLoginRequestInSec int,
|
||||
@@ -70,7 +70,7 @@ func NewAuth(
|
||||
userRepository: userRepository,
|
||||
txRunner: txRunner,
|
||||
tokenService: tokenService,
|
||||
sudirService: sudirService,
|
||||
oauthService: oauthService,
|
||||
auditService: auditService,
|
||||
logger: logger,
|
||||
delayLoginRequest: time.Duration(delayLoginRequestInSec) * time.Second,
|
||||
@@ -100,8 +100,8 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
return errors.WithMessage(domain.ErrUnauthenticated, "wrong email")
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "get user by email")
|
||||
case user.SudirUserId != nil:
|
||||
return domain.ErrSudirAuthorization
|
||||
case user.OauthUserId != nil:
|
||||
return domain.ErrOauthAuthorization
|
||||
}
|
||||
|
||||
if user.Blocked {
|
||||
@@ -141,7 +141,7 @@ func (a Auth) Login(ctx context.Context, request domain.LoginRequest) (*domain.L
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirRequest) (*domain.LoginResponse, error) {
|
||||
func (a Auth) LoginWithOauth(ctx context.Context, request domain.LoginOauthRequest) (*domain.LoginResponse, error) {
|
||||
var (
|
||||
user *entity.User
|
||||
|
||||
@@ -150,41 +150,41 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
)
|
||||
|
||||
err := a.txRunner.AuthTransaction(ctx, func(ctx context.Context, tx AuthTransaction) error {
|
||||
sudirUser, err := a.sudirService.Authenticate(ctx, request, tx)
|
||||
oauthUser, err := a.oauthService.Authenticate(ctx, request, tx)
|
||||
|
||||
var authErr *entity.SudirAuthError
|
||||
var authErr *entity.OauthAuthError
|
||||
switch {
|
||||
case errors.As(err, &authErr):
|
||||
a.logger.Error(ctx, "sudir authenticate: error occurred", log.String("error", err.Error()))
|
||||
a.logger.Error(ctx, "oauth authenticate: error occurred", log.String("error", err.Error()))
|
||||
return domain.ErrUnauthenticated
|
||||
case err != nil:
|
||||
return errors.WithMessage(err, "sudir authenticate")
|
||||
case sudirUser.SudirUserId == "" || sudirUser.Email == "":
|
||||
a.logger.Error(ctx, "sudir authenticate: missing sudirUserId or email",
|
||||
log.String("userId", sudirUser.SudirUserId),
|
||||
log.String("email", sudirUser.Email))
|
||||
return errors.WithMessage(err, "oauth authenticate")
|
||||
case oauthUser.OauthUserId == "" || oauthUser.Email == "":
|
||||
a.logger.Error(ctx, "oauth authenticate: missing oauthUserId or email",
|
||||
log.String("userId", oauthUser.OauthUserId),
|
||||
log.String("email", oauthUser.Email))
|
||||
return domain.ErrUnauthenticated
|
||||
}
|
||||
|
||||
user, err = tx.UpsertBySudirUserId(ctx, entity.User{
|
||||
SudirUserId: &sudirUser.SudirUserId,
|
||||
FirstName: sudirUser.FirstName,
|
||||
LastName: sudirUser.LastName,
|
||||
FullName: sudirUser.FullName,
|
||||
Email: sudirUser.Email,
|
||||
user, err = tx.UpsertByOauthUserId(ctx, entity.User{
|
||||
OauthUserId: &oauthUser.OauthUserId,
|
||||
FirstName: oauthUser.FirstName,
|
||||
LastName: oauthUser.LastName,
|
||||
FullName: oauthUser.FullName,
|
||||
Email: oauthUser.Email,
|
||||
Password: "",
|
||||
Blocked: false,
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
})
|
||||
if errors.Is(err, domain.ErrUserIsBlocked) {
|
||||
return errors.Errorf("user with sudir user id = %s is blocked", sudirUser.SudirUserId)
|
||||
return errors.Errorf("user with oauth user id = %s is blocked", oauthUser.OauthUserId)
|
||||
}
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert by sudir user id")
|
||||
return errors.WithMessage(err, "upsert by oauth user id")
|
||||
}
|
||||
|
||||
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), sudirUser.RoleIds)
|
||||
err = tx.UpsertUserRoleLinks(ctx, int(user.Id), oauthUser.RoleIds)
|
||||
if err != nil {
|
||||
return errors.WithMessage(err, "upsert user role links")
|
||||
}
|
||||
@@ -206,7 +206,7 @@ func (a Auth) LoginWithSudir(ctx context.Context, request domain.LoginSudirReque
|
||||
return nil, errors.WithMessage(err, "auth transaction")
|
||||
}
|
||||
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через СУДИР", entity.EventSuccessLogin)
|
||||
a.auditService.SaveAuditAsync(ctx, user.Id, "Успешный вход через OAuth", entity.EventSuccessLogin)
|
||||
|
||||
return &domain.LoginResponse{
|
||||
Token: tokenString,
|
||||
|
||||
@@ -3,9 +3,9 @@ package delete_old_audit_worker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"isp-admin-service/conf"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ package inactive_worker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,12 +4,12 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -3,16 +3,16 @@ package service
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type sudirRepo interface {
|
||||
GetToken(ctx context.Context, creds entity.ClientSetting) (*entity.SudirTokenResponse, error)
|
||||
GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error)
|
||||
type oauthRepo interface {
|
||||
GetToken(ctx context.Context, creds entity.ClientSetting) (*entity.OauthTokenResponse, error)
|
||||
GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error)
|
||||
}
|
||||
|
||||
type roleRepo interface {
|
||||
@@ -20,30 +20,30 @@ type roleRepo interface {
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
}
|
||||
|
||||
type Sudir struct {
|
||||
sudirRepo sudirRepo
|
||||
clientSettings map[string]conf.SudirClientConfig
|
||||
type Oauth struct {
|
||||
oauthRepo oauthRepo
|
||||
clientSettings map[string]conf.OauthClientConfig
|
||||
}
|
||||
|
||||
func NewSudir(settings []conf.SudirClientConfig, sudirRepo sudirRepo) (Sudir, error) {
|
||||
clientSettings := make(map[string]conf.SudirClientConfig, len(settings))
|
||||
func NewOauth(settings []conf.OauthClientConfig, oauthRepo oauthRepo) (Oauth, error) {
|
||||
clientSettings := make(map[string]conf.OauthClientConfig, len(settings))
|
||||
for i, setting := range settings {
|
||||
_, ok := clientSettings[setting.ClientName]
|
||||
if ok {
|
||||
return Sudir{}, errors.Errorf("client setting [%d] has non-unique client name", i)
|
||||
return Oauth{}, errors.Errorf("client setting [%d] has non-unique client name", i)
|
||||
}
|
||||
clientSettings[setting.ClientName] = setting
|
||||
}
|
||||
|
||||
return Sudir{
|
||||
sudirRepo: sudirRepo,
|
||||
return Oauth{
|
||||
oauthRepo: oauthRepo,
|
||||
clientSettings: clientSettings,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s Sudir) Authenticate(ctx context.Context, req domain.LoginSudirRequest, roleRepo roleRepo) (*entity.SudirUser, error) {
|
||||
func (s Oauth) Authenticate(ctx context.Context, req domain.LoginOauthRequest, roleRepo roleRepo) (*entity.OauthUser, error) {
|
||||
if len(s.clientSettings) == 0 {
|
||||
return nil, domain.ErrSudirAuthIsMissed
|
||||
return nil, domain.ErrOauthIsMissed
|
||||
}
|
||||
|
||||
setting, ok := s.clientSettings[req.ClientName]
|
||||
@@ -57,20 +57,20 @@ func (s Sudir) Authenticate(ctx context.Context, req domain.LoginSudirRequest, r
|
||||
ClientSecret: setting.ClientSecret,
|
||||
RedirectURI: setting.RedirectURI,
|
||||
}
|
||||
tokenResponse, err := s.sudirRepo.GetToken(ctx, creds)
|
||||
tokenResponse, err := s.oauthRepo.GetToken(ctx, creds)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get token")
|
||||
case tokenResponse.SudirAuthError != nil:
|
||||
return nil, errors.WithMessage(tokenResponse.SudirAuthError, "get token")
|
||||
case tokenResponse.OauthAuthError != nil:
|
||||
return nil, errors.WithMessage(tokenResponse.OauthAuthError, "get token")
|
||||
}
|
||||
|
||||
user, err := s.sudirRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||
user, err := s.oauthRepo.GetUser(ctx, tokenResponse.AccessToken)
|
||||
switch {
|
||||
case err != nil:
|
||||
return nil, errors.WithMessage(err, "get user")
|
||||
case user.SudirAuthError != nil:
|
||||
return nil, errors.WithMessage(user.SudirAuthError, "get user")
|
||||
case user.OauthAuthError != nil:
|
||||
return nil, errors.WithMessage(user.OauthAuthError, "get user")
|
||||
}
|
||||
email := user.Email
|
||||
if email == "" {
|
||||
@@ -88,9 +88,9 @@ func (s Sudir) Authenticate(ctx context.Context, req domain.LoginSudirRequest, r
|
||||
}
|
||||
}
|
||||
|
||||
return &entity.SudirUser{
|
||||
return &entity.OauthUser{
|
||||
RoleIds: rolesIds,
|
||||
SudirUserId: user.Sub,
|
||||
OauthUserId: user.Sub,
|
||||
FirstName: user.GivenName,
|
||||
LastName: user.FamilyName,
|
||||
FullName: user.Name,
|
||||
@@ -3,8 +3,8 @@ package service
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
)
|
||||
|
||||
type Permission struct {
|
||||
|
||||
+4
-3
@@ -5,9 +5,10 @@ import (
|
||||
"fmt"
|
||||
"slices"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type roleRoleRepo interface {
|
||||
|
||||
@@ -5,9 +5,10 @@ import (
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type TokenRep interface {
|
||||
|
||||
@@ -3,9 +3,9 @@ package session_worker
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -4,11 +4,11 @@ import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/bgjob"
|
||||
"github.com/txix-open/isp-kit/bgjobx/handler"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
|
||||
+3
-3
@@ -6,10 +6,10 @@ import (
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
|
||||
+10
-10
@@ -2,20 +2,20 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"net/url"
|
||||
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
)
|
||||
|
||||
type UiSettings struct {
|
||||
sudirBaseUrl string
|
||||
settings map[string]conf.SudirClientConfig
|
||||
oauthBaseUrl string
|
||||
settings map[string]conf.OauthClientConfig
|
||||
}
|
||||
|
||||
func NewUiSettings(sudirBaseUrl string, settings []conf.SudirClientConfig) UiSettings {
|
||||
settingsMap := make(map[string]conf.SudirClientConfig, len(settings))
|
||||
func NewUiSettings(oauthBaseUrl string, settings []conf.OauthClientConfig) UiSettings {
|
||||
settingsMap := make(map[string]conf.OauthClientConfig, len(settings))
|
||||
for _, setting := range settings {
|
||||
if setting.UiSetting == nil {
|
||||
continue
|
||||
@@ -23,12 +23,12 @@ func NewUiSettings(sudirBaseUrl string, settings []conf.SudirClientConfig) UiSet
|
||||
settingsMap[setting.ClientName] = setting
|
||||
}
|
||||
return UiSettings{
|
||||
sudirBaseUrl: sudirBaseUrl,
|
||||
oauthBaseUrl: oauthBaseUrl,
|
||||
settings: settingsMap,
|
||||
}
|
||||
}
|
||||
|
||||
func (s UiSettings) SudirSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiSudirSetting, error) {
|
||||
func (s UiSettings) OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) {
|
||||
setting, ok := s.settings[req.ClientName]
|
||||
if !ok {
|
||||
return nil, domain.ErrUnknownClient
|
||||
@@ -48,7 +48,7 @@ func (s UiSettings) SudirSettings(ctx context.Context, req domain.ClientNameRequ
|
||||
if err != nil {
|
||||
return nil, errors.Errorf("build url for logout: %w", err)
|
||||
}
|
||||
return &domain.UiSudirSetting{
|
||||
return &domain.UiOauthSetting{
|
||||
LoginUrl: loginUrl,
|
||||
LogoutUrl: logoutUrl,
|
||||
}, nil
|
||||
@@ -60,7 +60,7 @@ func (s UiSettings) buildUrl(methodPath string, additionalQuery map[string]strin
|
||||
return "", errors.Errorf("parse method path")
|
||||
}
|
||||
|
||||
joined, err := url.JoinPath(s.sudirBaseUrl, method.Path)
|
||||
joined, err := url.JoinPath(s.oauthBaseUrl, method.Path)
|
||||
if err != nil {
|
||||
return "", errors.Errorf("join method path and baseUrl")
|
||||
}
|
||||
|
||||
+9
-9
@@ -8,10 +8,10 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -31,7 +31,7 @@ type UserRepo interface {
|
||||
GetUserById(ctx context.Context, identity int64) (*entity.User, error)
|
||||
GetUsers(ctx context.Context, req domain.UsersPageRequest) ([]entity.User, error)
|
||||
GetAllUsers(ctx context.Context) ([]entity.User, error)
|
||||
GetUserByEmailAndSudirId(ctx context.Context, email string, sudirUserId string) (*entity.User, error)
|
||||
GetUserByEmailAndOauthId(ctx context.Context, email string, oauthUserId string) (*entity.User, error)
|
||||
GetUsersByEmail(ctx context.Context, email string) ([]entity.User, error)
|
||||
UpdateUser(ctx context.Context, id int64, user entity.UpdateUser) (*entity.User, error)
|
||||
DeleteUser(ctx context.Context, ids []int64) (int, error)
|
||||
@@ -207,7 +207,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
var usr entity.User
|
||||
|
||||
err := u.txRunner.UserTransaction(ctx, func(ctx context.Context, tx UserTransaction) error {
|
||||
user, err := tx.GetUserByEmailAndSudirId(ctx, req.Email, "")
|
||||
user, err := tx.GetUserByEmailAndOauthId(ctx, req.Email, "")
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
break
|
||||
@@ -223,7 +223,7 @@ func (u User) CreateUser(ctx context.Context, req domain.CreateUserRequest, admi
|
||||
}
|
||||
|
||||
usr = entity.User{
|
||||
SudirUserId: nil,
|
||||
OauthUserId: nil,
|
||||
Id: 0,
|
||||
FirstName: req.FirstName,
|
||||
LastName: req.LastName,
|
||||
@@ -301,12 +301,12 @@ func (u User) UpdateUser(ctx context.Context, req domain.UpdateUserRequest, admi
|
||||
|
||||
for _, usr := range users {
|
||||
// check in internal user space
|
||||
if (user.SudirUserId == nil && usr.SudirUserId == nil) && (usr.Id != req.Id) {
|
||||
if (user.OauthUserId == nil && usr.OauthUserId == nil) && (usr.Id != req.Id) {
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
|
||||
// check in sudir user space
|
||||
if usr.SudirUserId != nil && user.SudirUserId != nil && (*user.SudirUserId != *usr.SudirUserId) {
|
||||
// check in oauth user space
|
||||
if usr.OauthUserId != nil && user.OauthUserId != nil && (*user.OauthUserId != *usr.OauthUserId) {
|
||||
return domain.ErrAlreadyExists
|
||||
}
|
||||
}
|
||||
|
||||
+5
-5
@@ -4,11 +4,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
|
||||
+35
-35
@@ -10,13 +10,13 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/test/fake"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
@@ -43,27 +43,27 @@ type AuthTestSuite struct {
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
sudirCli *httpcli.Client
|
||||
sudirClientName string
|
||||
oauthCli *httpcli.Client
|
||||
oauthClientName string
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
s.sudirCli = httpcli.New()
|
||||
s.sudirClientName = fake.It[string]()
|
||||
s.oauthCli = httpcli.New()
|
||||
s.oauthClientName = fake.It[string]()
|
||||
|
||||
mocksrv, host := s.initMockSudir()
|
||||
sudirHost, _ := url.JoinPath(host, "/blitz/")
|
||||
s.sudirCli.GlobalRequestConfig().BaseUrl = sudirHost
|
||||
mocksrv, host := s.initMockOauth()
|
||||
oauthHost, _ := url.JoinPath(host, "/blitz/")
|
||||
s.oauthCli.GlobalRequestConfig().BaseUrl = oauthHost
|
||||
|
||||
remote := conf.Remote{
|
||||
SudirAuth: &conf.SudirAuth{
|
||||
Host: sudirHost,
|
||||
Clients: []conf.SudirClientConfig{
|
||||
Oauth: &conf.Oauth{
|
||||
Host: host,
|
||||
Clients: []conf.OauthClientConfig{
|
||||
{
|
||||
ClientName: s.sudirClientName,
|
||||
ClientName: s.oauthClientName,
|
||||
ClientId: "admin",
|
||||
ClientSecret: "admin",
|
||||
RedirectURI: "http://localhost",
|
||||
@@ -77,7 +77,7 @@ func (s *AuthTestSuite) SetupTest() {
|
||||
},
|
||||
}
|
||||
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.sudirCli, s.db).
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
@@ -174,20 +174,20 @@ func (s *AuthTestSuite) TestLoginWrongPassword() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||
func (s *AuthTestSuite) TestOauthLoginHappyPath() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
||||
JsonRequestBody(domain.LoginSudirRequest{
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.sudirClientName,
|
||||
ClientName: s.oauthClientName,
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
s.Require().NoError(err)
|
||||
user := entity.User{}
|
||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where sudir_user_id = $1", "sudirUser1")
|
||||
s.Require().Equal("sudir@email.ru", user.Email)
|
||||
s.db.Must().SelectRow(&user, "select id, email, full_name from users where oauth_user_id = $1", "oauthUser1")
|
||||
s.Require().Equal("oauth@email.ru", user.Email)
|
||||
s.Require().Equal("surname name patronymic", user.FullName)
|
||||
|
||||
tokenInfo := SelectTokenEntityByToken(s.db, response.Token)
|
||||
@@ -196,13 +196,13 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestSudirLogin_UnknownClient() {
|
||||
func (s *AuthTestSuite) TestOauthLogin_UnknownClient() {
|
||||
response := domain.LoginResponse{}
|
||||
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_sudir").
|
||||
JsonRequestBody(domain.LoginSudirRequest{
|
||||
err := s.grpcCli.Invoke("admin/auth/login_with_oauth").
|
||||
JsonRequestBody(domain.LoginOauthRequest{
|
||||
AuthCode: "code",
|
||||
ClientName: s.sudirClientName + fake.It[string](),
|
||||
ClientName: s.oauthClientName + fake.It[string](),
|
||||
}).
|
||||
JsonResponseBody(&response).
|
||||
Do(s.T().Context())
|
||||
@@ -325,11 +325,11 @@ func (s *AuthTestSuite) TestBruteForceLogin() {
|
||||
time.Sleep(2 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
func (s *AuthTestSuite) initMockOauth() (*httptest.Server, string) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/blitz/oauth/te", func(writer http.ResponseWriter, request *http.Request) {
|
||||
res := entity.SudirTokenResponse{
|
||||
SudirAuthError: nil,
|
||||
res := entity.OauthTokenResponse{
|
||||
OauthAuthError: nil,
|
||||
IdToken: "1",
|
||||
AccessToken: "token",
|
||||
}
|
||||
@@ -339,11 +339,11 @@ func (s *AuthTestSuite) initMockSudir() (*httptest.Server, string) {
|
||||
s.NoError(err)
|
||||
})
|
||||
mux.HandleFunc("/blitz/oauth/me", func(writer http.ResponseWriter, request *http.Request) {
|
||||
res := entity.SudirUserResponse{
|
||||
SudirAuthError: nil,
|
||||
Email: "sudir@email.ru",
|
||||
res := entity.OauthUserResponse{
|
||||
OauthAuthError: nil,
|
||||
Email: "oauth@email.ru",
|
||||
Groups: []string{"DIT-KKD-Admins"},
|
||||
Sub: "sudirUser1",
|
||||
Sub: "oauthUser1",
|
||||
GivenName: "name",
|
||||
FamilyName: "surname",
|
||||
Name: "surname name patronymic",
|
||||
|
||||
@@ -4,14 +4,15 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
|
||||
"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/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
)
|
||||
|
||||
func TestCustomizationTestSuite(t *testing.T) {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"msp-admin-service/entity"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/txix-open/isp-kit/db/query"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
@@ -21,15 +21,15 @@ func InsertUser(db *dbt.TestDb, user entity.User) int64 {
|
||||
return id
|
||||
}
|
||||
|
||||
func InsertSudirUser(db *dbt.TestDb, user entity.SudirUser) int64 {
|
||||
func InsertOauthUser(db *dbt.TestDb, user entity.OauthUser) int64 {
|
||||
q, args, err := query.New().
|
||||
Insert("users").
|
||||
Columns("sudir_user_id", "first_name", "last_name", "full_name", "email").
|
||||
Values(user.SudirUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
||||
Columns("oauth_user_id", "first_name", "last_name", "full_name", "email").
|
||||
Values(user.OauthUserId, user.FirstName, user.LastName, user.FullName, user.Email).
|
||||
Suffix("RETURNING id").
|
||||
ToSql()
|
||||
if err != nil {
|
||||
panic(errors.WithMessagef(err, "insert sudir user"))
|
||||
panic(errors.WithMessagef(err, "insert oauth user"))
|
||||
}
|
||||
var id int64
|
||||
db.Must().SelectRow(&id, q, args...)
|
||||
|
||||
@@ -4,13 +4,13 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/service/inactive_worker"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/service/inactive_worker"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
|
||||
@@ -4,6 +4,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
@@ -12,10 +17,6 @@ import (
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
)
|
||||
|
||||
func TestSecureSuite(t *testing.T) {
|
||||
|
||||
@@ -5,11 +5,11 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/service/session_worker"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/bgjobx"
|
||||
|
||||
+20
-20
@@ -1,9 +1,9 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
@@ -21,20 +21,20 @@ type UiSettingsSuite struct {
|
||||
|
||||
test *test.Test
|
||||
apiCli *client.Client
|
||||
sudirClientSetting conf.SudirClientConfig
|
||||
baseSudirUrl string
|
||||
oauthClientSetting conf.OauthClientConfig
|
||||
baseOauthUrl string
|
||||
}
|
||||
|
||||
func TestUiSettingsSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &UiSettingsSuite{
|
||||
baseSudirUrl: "http://127.0.0.1/sudir",
|
||||
sudirClientSetting: conf.SudirClientConfig{
|
||||
baseOauthUrl: "http://127.0.0.1/oauth",
|
||||
oauthClientSetting: conf.OauthClientConfig{
|
||||
ClientName: fake.It[string](),
|
||||
ClientId: fake.It[string](),
|
||||
ClientSecret: fake.It[string](),
|
||||
RedirectURI: "https://127.0.0.1/test/redirected",
|
||||
UiSetting: &conf.UiSudirSetting{
|
||||
UiSetting: &conf.UiOauthSetting{
|
||||
LoginEndpoint: "/login?someQueryParam=1&test=true",
|
||||
LogoutEndpoint: "/logout?redirect=url",
|
||||
},
|
||||
@@ -45,9 +45,9 @@ func TestUiSettingsSuite(t *testing.T) {
|
||||
func (s *UiSettingsSuite) SetupTest() {
|
||||
s.test, _ = test.New(s.T())
|
||||
remote := conf.Remote{
|
||||
SudirAuth: &conf.SudirAuth{
|
||||
Host: s.baseSudirUrl,
|
||||
Clients: []conf.SudirClientConfig{s.sudirClientSetting},
|
||||
Oauth: &conf.Oauth{
|
||||
Host: s.baseOauthUrl,
|
||||
Clients: []conf.OauthClientConfig{s.oauthClientSetting},
|
||||
},
|
||||
}
|
||||
cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil).
|
||||
@@ -58,11 +58,11 @@ func (s *UiSettingsSuite) SetupTest() {
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
var resp domain.UiSudirSetting
|
||||
var resp domain.UiOauthSetting
|
||||
|
||||
err := s.apiCli.Invoke("admin/ui_settings/sudir").
|
||||
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.sudirClientSetting.ClientName,
|
||||
ClientName: s.oauthClientSetting.ClientName,
|
||||
}).
|
||||
JsonResponseBody(&resp).
|
||||
Do(s.T().Context())
|
||||
@@ -72,13 +72,13 @@ func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(
|
||||
"http://127.0.0.1/sudir/login",
|
||||
"http://127.0.0.1/oauth/login",
|
||||
loginURL.Scheme+"://"+loginURL.Host+loginURL.Path,
|
||||
)
|
||||
|
||||
query := loginURL.Query()
|
||||
s.Require().Equal(s.sudirClientSetting.ClientId, query.Get("client_id"))
|
||||
s.Require().Equal(s.sudirClientSetting.RedirectURI, query.Get("redirect_uri"))
|
||||
s.Require().Equal(s.oauthClientSetting.ClientId, query.Get("client_id"))
|
||||
s.Require().Equal(s.oauthClientSetting.RedirectURI, query.Get("redirect_uri"))
|
||||
s.Require().Equal("1", query.Get("someQueryParam"))
|
||||
s.Require().Equal("true", query.Get("test"))
|
||||
|
||||
@@ -86,16 +86,16 @@ func (s *UiSettingsSuite) Test_HappyPath() {
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().Equal(
|
||||
"http://127.0.0.1/sudir/logout",
|
||||
"http://127.0.0.1/oauth/logout",
|
||||
logoutURL.Scheme+"://"+logoutURL.Host+logoutURL.Path,
|
||||
)
|
||||
s.Require().Equal("url", logoutURL.Query().Get("redirect"))
|
||||
}
|
||||
|
||||
func (s *UiSettingsSuite) Test_UnknownClient() {
|
||||
err := s.apiCli.Invoke("admin/ui_settings/sudir").
|
||||
err := s.apiCli.Invoke("admin/ui_settings/oauth").
|
||||
JsonRequestBody(domain.ClientNameRequest{
|
||||
ClientName: s.sudirClientSetting.ClientName + fake.It[string](),
|
||||
ClientName: s.oauthClientSetting.ClientName + fake.It[string](),
|
||||
}).
|
||||
Do(s.T().Context())
|
||||
s.Require().Error(err)
|
||||
|
||||
+20
-20
@@ -9,12 +9,12 @@ import (
|
||||
"github.com/txix-open/isp-kit/grpc/apierrors"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"msp-admin-service/assembly"
|
||||
"msp-admin-service/conf"
|
||||
"msp-admin-service/domain"
|
||||
"msp-admin-service/entity"
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
"isp-admin-service/repository"
|
||||
"isp-admin-service/service"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
@@ -126,9 +126,9 @@ func (s *UserTestSuite) TestGetProfileNotFound() {
|
||||
s.Require().Equal(codes.NotFound, st.Code())
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestGetProfileSudir() {
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{
|
||||
SudirUserId: "sudirUser1",
|
||||
func (s *UserTestSuite) TestGetProfileOauth() {
|
||||
id := InsertOauthUser(s.db, entity.OauthUser{
|
||||
OauthUserId: "oauthUser1",
|
||||
FirstName: "name",
|
||||
LastName: "surname",
|
||||
FullName: "surname name",
|
||||
@@ -384,9 +384,9 @@ func (s *UserTestSuite) TestCreateUserHappyPath() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() {
|
||||
firstSudirId := "user_a"
|
||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a2@a.ru"})
|
||||
func (s *UserTestSuite) TestCreateUserWithSameEmailOauthHappyPath() {
|
||||
firstOauthId := "user_a"
|
||||
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a2@a.ru"})
|
||||
|
||||
preCount := 0
|
||||
s.db.Must().SelectRow(&preCount, "select count(*) from users")
|
||||
@@ -458,13 +458,13 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() {
|
||||
time.Sleep(1 * time.Second) // wait for go SaveAuditAsync()
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() {
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: "123", Email: "sudir@a.ru", FullName: "surname name patronymic"})
|
||||
func (s *AuthTestSuite) TestUpdateOauthUserHappyPath() {
|
||||
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: "123", Email: "oauth@a.ru", FullName: "surname name patronymic"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "nameUpd",
|
||||
LastName: "surnameUpd",
|
||||
Email: "sudir@a.ru",
|
||||
Email: "oauth@a.ru",
|
||||
}
|
||||
response := domain.User{}
|
||||
err := s.grpcCli.
|
||||
@@ -506,12 +506,12 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() {
|
||||
s.Require().Equal(codes.AlreadyExists, st.Code())
|
||||
}
|
||||
|
||||
func (s *AuthTestSuite) TestUpdateUserWithSudirAlreadyExist() {
|
||||
firstSudirId := "user_a"
|
||||
secondSudirId := "user_b"
|
||||
func (s *AuthTestSuite) TestUpdateUserWithOauthAlreadyExist() {
|
||||
firstOauthId := "user_a"
|
||||
secondOauthId := "user_b"
|
||||
|
||||
admin := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: firstSudirId, Email: "a_exists@a.ru"})
|
||||
id := InsertSudirUser(s.db, entity.SudirUser{SudirUserId: secondSudirId, Email: "b_exists@b.ru"})
|
||||
admin := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: firstOauthId, Email: "a_exists@a.ru"})
|
||||
id := InsertOauthUser(s.db, entity.OauthUser{OauthUserId: secondOauthId, Email: "b_exists@b.ru"})
|
||||
req := domain.UpdateUserRequest{
|
||||
Id: id,
|
||||
FirstName: "name",
|
||||
|
||||
@@ -3,9 +3,9 @@ package transaction
|
||||
import (
|
||||
"context"
|
||||
|
||||
"msp-admin-service/repository"
|
||||
"msp-admin-service/service"
|
||||
"msp-admin-service/service/session_worker"
|
||||
"isp-admin-service/repository"
|
||||
"isp-admin-service/service"
|
||||
"isp-admin-service/service/session_worker"
|
||||
|
||||
"github.com/txix-open/isp-kit/db"
|
||||
)
|
||||
|
||||
+40
@@ -1,5 +1,45 @@
|
||||
# Changelog
|
||||
|
||||
## [v1.6.1] — 2026-07-29
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
|
||||
|
||||
### Performance — gjson-style fast-skip in hot loops
|
||||
|
||||
Ported gjson's `>'\\'` fast-skip trick to three inner loops in parser.go:
|
||||
`stringEndConfig` tail, `blockEndConfig`, and `searchKeysConfig`. The trick
|
||||
uses a single unsigned comparison (`byte > 0x5C`) to skip all non-structural
|
||||
bytes in bulk, reducing per-byte branch overhead.
|
||||
|
||||
| Payload | Before | After | Improvement |
|
||||
|---|---|---|---|
|
||||
| Small (190B) | 382 ns | **339 ns** | -11.3% |
|
||||
| Medium (2.4kB) | 3,899 ns | **3,141 ns** | -19.4% |
|
||||
| Large (24kB) | 20,788 ns | **20,114 ns** | -3.2% |
|
||||
|
||||
Zero allocations maintained on all paths.
|
||||
|
||||
### Benchmarks — now includes gjson and sonic
|
||||
|
||||
Added [tidwall/gjson](https://github.com/tidwall/gjson) (15.5k⭐, path-based
|
||||
parser like jsonparser) and [bytedance/sonic](https://github.com/bytedance/sonic)
|
||||
(9.6k⭐, SIMD-accelerated deserializer) to the benchmark suite.
|
||||
|
||||
**Final leaderboard (large payload):**
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
|---|---|---|---|
|
||||
| **buger/jsonparser** | **20,114** | **0** | **0** |
|
||||
| tidwall/gjson | 22,756 | 28,672 | 2 |
|
||||
| mailru/easyjson | 33,771 | 4,016 | 134 |
|
||||
| bytedance/sonic | 41,053 | 31,368 | 71 |
|
||||
| pquerna/ffjson | 59,063 | 4,822 | 144 |
|
||||
| encoding/json | 130,565 | 4,432 | 147 |
|
||||
|
||||
jsonparser is **the fastest across all payload sizes** and the **only zero-allocation** parser.
|
||||
|
||||
---
|
||||
|
||||
## [v1.6.0] — 2026-07-29
|
||||
|
||||
### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings)
|
||||
|
||||
+28
-38
@@ -1,7 +1,7 @@
|
||||
[](https://goreportcard.com/report/github.com/buger/jsonparser) [](https://reqproof.com) 
|
||||
# Alternative JSON parser for Go (10x times faster standard library)
|
||||
|
||||
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **6x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
|
||||
It does not require you to know the structure of the payload (eg. create structs), and allows accessing fields by providing the path to them. It is up to **6.5x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below.
|
||||
|
||||
---
|
||||
|
||||
@@ -341,25 +341,20 @@ data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items")
|
||||
There are 3 benchmark types, trying to simulate real-life usage for small, medium and large JSON payloads.
|
||||
For each metric, the lower value is better. Time/op is in nanoseconds. Values better than standard encoding/json marked as bold text.
|
||||
|
||||
> **Methodology:** Benchmarks run with `go test -bench=. -benchmem -count=5` on Apple M4 Max (ARM64, darwin), Go 1.26.3. Median of 5 runs. All comparison libraries updated to their latest versions as of 2026-07-28. The `encoding/json` benchmark types no longer carry ffjson-generated `UnmarshalJSON` methods (fixed in v1.3.1, issue #126), so these numbers reflect the real standard library, not generated code.
|
||||
> **Methodology:** Benchmarks run with `go test -bench=. -benchmem -count=5` on Apple M4 Max (ARM64, darwin), Go 1.26.3. Median of 5 runs. All comparison libraries updated to their latest versions as of 2026-07-29.
|
||||
|
||||
Compared libraries:
|
||||
* https://golang.org/pkg/encoding/json
|
||||
* https://github.com/tidwall/gjson — path-based, like jsonparser
|
||||
* https://github.com/bytedance/sonic — SIMD-accelerated full deserializer
|
||||
* https://github.com/Jeffail/gabs/v2
|
||||
* https://github.com/a8m/djson
|
||||
* https://github.com/bitly/go-simplejson
|
||||
* https://github.com/antonholmquist/jason
|
||||
* https://github.com/mreiferson/go-ujson
|
||||
* https://github.com/ugorji/go/codec
|
||||
* https://github.com/pquerna/ffjson
|
||||
* https://github.com/mailru/easyjson
|
||||
* https://github.com/buger/jsonparser
|
||||
|
||||
#### TLDR
|
||||
|
||||
`jsonparser` is up to **6.4x faster** than standard `encoding/json` package (depending on payload size and usage), and **zero allocations** — it operates with data on byte level, and provide direct slice pointers. On large payloads, `jsonparser` is also faster than `easyjson` and `ffjson`.
|
||||
|
||||
If you searching for replacement of `encoding/json` while keeping structs, `easyjson` is an amazing choice. If you want to process dynamic JSON, have memory constrains, or more control over your data you should try `jsonparser`.
|
||||
`jsonparser` is the **fastest overall** across all payload sizes — faster than gjson, sonic, easyjson, and encoding/json — with **zero allocations** on every code path.
|
||||
|
||||
#### Small payload
|
||||
|
||||
@@ -369,21 +364,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payloa
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| ------ | ------- | -------- | ------- |
|
||||
| encoding/json struct | 1335 | 415 | 9 |
|
||||
| encoding/json interface{} | 1441 | 1336 | 30 |
|
||||
| Jeffail/gabs | 1558 | 1464 | 38 |
|
||||
| bitly/go-simplejson | 1594 | 2120 | 34 |
|
||||
| github.com/ugorji/go/codec | 1286 | 1288 | 13 |
|
||||
| antonholmquist/jason | 4354 | 6816 | 105 |
|
||||
| mreiferson/go-ujson | 1031 | 1392 | 36 |
|
||||
| a8m/djson | 880 | 1160 | 25 |
|
||||
| pquerna/ffjson | **652** | **520** | **10** |
|
||||
| mailru/easyjson | **312** | **80** | **4** |
|
||||
| buger/jsonparser (ObjectEach) | **214** | 64 | 2 |
|
||||
| buger/jsonparser (EachKey) | **241** | **0** | **0** |
|
||||
| buger/jsonparser (Get) | **382** | **0** | **0** |
|
||||
|
||||
`jsonparser` with `EachKey` is **5.5x faster** than `encoding/json` and **zero allocations**.
|
||||
| encoding/json struct | 1,300 | 416 | 9 |
|
||||
| bytedance/sonic | 460 | 522 | 4 |
|
||||
| tidwall/gjson | 402 | 64 | 3 |
|
||||
| pquerna/ffjson | **632** | **520** | **10** |
|
||||
| mailru/easyjson | **237** | **216** | **7** |
|
||||
| buger/jsonparser (ObjectEach) | **205** | 64 | 2 |
|
||||
| buger/jsonparser (EachKey) | **227** | **0** | **0** |
|
||||
| buger/jsonparser (Get) | **339** | **0** | **0** |
|
||||
|
||||
#### Medium payload
|
||||
|
||||
@@ -394,13 +382,15 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_paylo
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| ------- | ------- | -------- | --------- |
|
||||
| encoding/json struct | 10564 | 616 | 18 |
|
||||
| pquerna/ffjson | 3962 | 736 | 15 |
|
||||
| mailru/easyjson | **2444** | **216** | **7** |
|
||||
| buger/jsonparser (Get) | **3894** | **0** | **0** |
|
||||
| buger/jsonparser (EachKey) | **1923** | **0** | **0** |
|
||||
| encoding/json struct | 9,911 | 616 | 18 |
|
||||
| bytedance/sonic | 2,703 | 3,428 | 14 |
|
||||
| tidwall/gjson | 2,241 | 168 | 4 |
|
||||
| pquerna/ffjson | 3,731 | 736 | 15 |
|
||||
| mailru/easyjson | 2,368 | 216 | 7 |
|
||||
| buger/jsonparser (Get) | **3,141** | **0** | **0** |
|
||||
| buger/jsonparser (EachKey) | **1,657** | **0** | **0** |
|
||||
|
||||
`jsonparser` with `EachKey` beats `easyjson` on medium payload and remains zero-allocation.
|
||||
`jsonparser` with `EachKey` beats every competitor on medium payloads while remaining zero-allocation.
|
||||
|
||||
#### Large payload
|
||||
|
||||
@@ -412,14 +402,14 @@ https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payloa
|
||||
|
||||
| Library | time/op | bytes/op | allocs/op |
|
||||
| --- | --- | --- | --- |
|
||||
| encoding/json struct | 134123 | 4432 | 147 |
|
||||
| encoding/json interface{} | 176246 | 135824 | 2814 |
|
||||
| a8m/djson | 99295 | 135136 | 2679 |
|
||||
| pquerna/ffjson | 60129 | 4822 | 144 |
|
||||
| mailru/easyjson | 32765 | 4016 | 134 |
|
||||
| buger/jsonparser | **20788** | **0** | **0** |
|
||||
| encoding/json struct | 130,565 | 4,432 | 147 |
|
||||
| bytedance/sonic | 41,053 | 31,368 | 71 |
|
||||
| pquerna/ffjson | 59,063 | 4,822 | 144 |
|
||||
| mailru/easyjson | 33,771 | 4,016 | 134 |
|
||||
| tidwall/gjson | 22,756 | 28,672 | 2 |
|
||||
| buger/jsonparser | **20,114** | **0** | **0** |
|
||||
|
||||
`jsonparser` is the **fastest library overall** on large payloads: **6.4x faster than encoding/json**, **1.6x faster than easyjson**, and **zero allocations**.
|
||||
`jsonparser` is the **fastest library overall** on large payloads: **6.5x faster than encoding/json**, **2x faster than sonic**, **1.7x faster than easyjson**, **1.1x faster than gjson** — and the **only zero-allocation** parser.
|
||||
|
||||
## Formal Verification
|
||||
|
||||
|
||||
+54
@@ -340,6 +340,14 @@ func stringEndConfig(_ Config, data []byte, quote byte) (int, bool) {
|
||||
}
|
||||
escaped := false
|
||||
for ; i < n; i++ {
|
||||
// gjson trick: the only bytes this loop acts on are the closing quote
|
||||
// and the backslash. For double-quote strings quote=0x22, for
|
||||
// single-quote quote=0x27; backslash=0x5C. All three are <= 0x5C, so a
|
||||
// single unsigned comparison skips every other byte (letters, digits,
|
||||
// punctuation, high UTF-8 bytes) without touching them.
|
||||
if data[i] > '\\' {
|
||||
continue
|
||||
}
|
||||
c := data[i]
|
||||
if c == quote {
|
||||
if !escaped {
|
||||
@@ -377,6 +385,30 @@ func blockEndConfig(config Config, data []byte, openSym byte, closeSym byte) int
|
||||
ln := len(data)
|
||||
|
||||
for i < ln {
|
||||
// Fast-skip non-structural bytes before dispatching to the switch.
|
||||
// Two categories are skipped in bulk with a single comparison each:
|
||||
// 1. Control/whitespace bytes (<= 0x20): indentation, spaces, newlines.
|
||||
// 2. Bytes > 0x5C that are not the open/close symbol: lowercase letters
|
||||
// (true/false/null), and high UTF-8 bytes.
|
||||
// The open/close symbols themselves (e.g. '{'=0x7B, '}'=0x7D, ']'=0x5D)
|
||||
// are > 0x5C and must NOT be skipped, hence the explicit exclusions.
|
||||
// '"' (0x22), '\'' (0x27) and '[' (0x5B) are <= 0x5C so they are never
|
||||
// caught by the second clause and always reach the switch.
|
||||
for i < ln {
|
||||
c := data[i]
|
||||
if c <= ' ' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if c > '\\' && c != openSym && c != closeSym {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if i >= ln {
|
||||
break
|
||||
}
|
||||
switch data[i] {
|
||||
case '"', '\'': // If inside a configured string, skip it
|
||||
quote := data[i]
|
||||
@@ -425,6 +457,28 @@ func searchKeysConfig(config Config, data []byte, keys ...string) int {
|
||||
var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings
|
||||
|
||||
for i < ln {
|
||||
// Fast-skip non-structural bytes before dispatching to the switch.
|
||||
// Skip control/whitespace (<= 0x20) and bytes > 0x5C that are not '{'
|
||||
// (0x7B) or '}' (0x7D) — the only structural chars handled below that
|
||||
// exceed the 0x5C threshold. '"' (0x22), '\'' (0x27), '[' (0x5B) and
|
||||
// ':' (0x3A) are all <= 0x5C and always reach the switch. This is the
|
||||
// gjson key-scan trick: a single unsigned comparison advances past
|
||||
// value content (true/false/null letters, high bytes) and indentation.
|
||||
for i < ln {
|
||||
c := data[i]
|
||||
if c <= ' ' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if c > '\\' && c != '{' && c != '}' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if i >= ln {
|
||||
break
|
||||
}
|
||||
switch data[i] {
|
||||
case '"', '\'':
|
||||
quote := data[i]
|
||||
|
||||
+27
@@ -1,5 +1,32 @@
|
||||
# Changelog
|
||||
|
||||
## 0.49.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
- removing DisableLogs and DisableMetrics client options. Sending metrics and logs is already gated by the usage of our APIs already, so having a global kill switch is counter intuitive. Users that won't to opt out should just not call the relevant APIs or setup the integrations. by @giortzisg in [#1392](https://github.com/getsentry/sentry-go/pull/1392)
|
||||
|
||||
### New Features ✨
|
||||
|
||||
- add `WithProxy`option for OTLP. This allows setting an `otlptracehttp.HTTPTransportProxyFunc` for the span exporter by @pierrre in [#1377](https://github.com/getsentry/sentry-go/pull/1377)
|
||||
|
||||
### Bug Fixes 🐛
|
||||
|
||||
- (echo) Propagate span through request context by @EricGusmao in [#1385](https://github.com/getsentry/sentry-go/pull/1385)
|
||||
- Skip recover frames on panic. This changes stacktrace behavior for captured panics, removing `sentry.Recover` frames to focus on the actual panic frames. The changes might affect issue grouping. by @giortzisg in [#1364](https://github.com/getsentry/sentry-go/pull/1364)
|
||||
|
||||
### Internal Changes 🔧
|
||||
|
||||
#### Deps
|
||||
|
||||
- Bump github.com/labstack/echo/v5 from 5.0.3 to 5.2.0 in /echo by @dependabot in [#1399](https://github.com/getsentry/sentry-go/pull/1399)
|
||||
- Bump github.com/gorilla/websocket from 1.5.1 to 1.5.3 by @dependabot in [#1397](https://github.com/getsentry/sentry-go/pull/1397)
|
||||
- Bump getsentry/craft from 2.26.6 to 2.27.2 by @dependabot in [#1381](https://github.com/getsentry/sentry-go/pull/1381)
|
||||
- Bump actions/setup-go from 6.4.0 to 7.0.0 by @dependabot in [#1382](https://github.com/getsentry/sentry-go/pull/1382)
|
||||
- Bump actions/checkout from 6.0.3 to 7.0.1 by @dependabot in [#1380](https://github.com/getsentry/sentry-go/pull/1380)
|
||||
- Bump google.golang.org/grpc to 1.82.1 and golang.org/x/sys to 0.46.0 by @dependabot in [#1375](https://github.com/getsentry/sentry-go/pull/1375)
|
||||
- Bump golang.org/x/text to v0.39.0 and x/net to v0.56.0 by @giortzisg in [#1374](https://github.com/getsentry/sentry-go/pull/1374)
|
||||
|
||||
## 0.48.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
+4
-13
@@ -270,11 +270,6 @@ type ClientOptions struct {
|
||||
MaxErrorDepth int
|
||||
// Default event tags. These are overridden by tags set on a scope.
|
||||
Tags map[string]string
|
||||
// DisableLogs controls whether logs should be emitted.
|
||||
// By default, logs are enabled. Set to true to disable log emission.
|
||||
DisableLogs bool
|
||||
// DisableMetrics controls when metrics should be emitted.
|
||||
DisableMetrics bool
|
||||
// DisableClientReports controls when client reports should be emitted.
|
||||
DisableClientReports bool
|
||||
// TraceIgnoreStatusCodes is a list of HTTP status codes that should not be traced.
|
||||
@@ -442,14 +437,10 @@ func NewClient(options ClientOptions) (*Client, error) {
|
||||
}
|
||||
client.setupTransport()
|
||||
|
||||
if !options.DisableLogs {
|
||||
client.batchLogger = newLogBatchProcessor(&client)
|
||||
client.batchLogger.Start()
|
||||
}
|
||||
if !options.DisableMetrics {
|
||||
client.batchMeter = newMetricBatchProcessor(&client)
|
||||
client.batchMeter.Start()
|
||||
}
|
||||
client.batchLogger = newLogBatchProcessor(&client)
|
||||
client.batchLogger.Start()
|
||||
client.batchMeter = newMetricBatchProcessor(&client)
|
||||
client.batchMeter.Start()
|
||||
}
|
||||
client.setupIntegrations()
|
||||
if options.OrgID != 0 && client.dsn != nil {
|
||||
|
||||
+16
@@ -13,6 +13,7 @@ git.sr.ht/~sbinet/gg v0.6.0 h1:RIzgkizAk+9r7uPzf/VfbJHBMKUr0F5hRFxTUGMnt38=
|
||||
git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm94=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.32.0/go.mod h1:RD2SsorTmYhF6HkTmDw7KmPYQk8OBYwTkuasChwv7R4=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=
|
||||
@@ -34,6 +35,7 @@ github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927 h1:SKI1/fuSdodxmNNyV
|
||||
github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927/go.mod h1:h/aW8ynjgkuj+NQRlZcDbAbM1ORAbXjXX77sX7T289U=
|
||||
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5 h1:6xNmx7iTtyBRev0+D/Tv1FZd4SCg8axKApyNyRsAt/w=
|
||||
github.com/cncf/xds/go v0.0.0-20251210132809-ee656c7534f5/go.mod h1:KdCmV+x/BuvyMxRnYBlmVaq4OLiKW6iRQfvC62cvdkI=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8iXXhfZs=
|
||||
github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w=
|
||||
github.com/dgraph-io/badger/v2 v2.2007.4 h1:TRWBQg8UrlUhaFdco01nO2uXwzKS7zd+HVdwV/GHc4o=
|
||||
@@ -52,12 +54,15 @@ github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwB
|
||||
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.36.0 h1:yg/JjO5E7ubRyKX3m07GF3reDNEnfOboJ0QySbH736g=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.36.0/go.mod h1:ty89S1YCCVruQAm9OtKeEkQLTb+Lkz0k8v9W0Oxsv98=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.0 h1:TvGH1wof4H33rezVKWSpqKz5NXWg5VPuZ0uONDT6eb4=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.0/go.mod h1:HvYl7zwPa5mffgyeTUHA9zHIH36nmrm7oCbo4YKoSWA=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3 h1:CVLmWDhDVRa6Mi/IgCgaopNosCaHz7zrMeF9MlZRkrs=
|
||||
github.com/go-jose/go-jose/v4 v4.1.3/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
|
||||
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
@@ -155,6 +160,7 @@ go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ=
|
||||
go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.39.0 h1:kWRNZMsfBHZ+uHjiH4y7Etn2FK26LAGkNFw7RHv1DhE=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.39.0/go.mod h1:t/OGqzHBa5v6RHZwrDBJ2OirWc+4q/w2fTbLZwAKjTk=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.43.0/go.mod h1:RyaZMFY7yi1kAs45S6mbFGz8O8rqB0dTY14uzvG4LCs=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U=
|
||||
@@ -165,15 +171,19 @@ golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
|
||||
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
|
||||
golang.org/x/net v0.49.0/go.mod h1:/ysNB2EvaqvesRkuLAyjI1ycPZlQHM3q01F02UY/MV8=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
|
||||
golang.org/x/oauth2 v0.34.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
|
||||
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
@@ -183,12 +193,17 @@ golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4 h1:bTLqdHv7xrGlFbvf5/TXNxy/iUwwdkjhqQTJDjW7aj0=
|
||||
golang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4/go.mod h1:g5NllXBEermZrmR51cJDQxmJUHUOfRAaNyWBM+R+548=
|
||||
golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=
|
||||
golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57/go.mod h1:3AWMyWHS+caVoiEXpiq6+tzKA40J4vQT3MYr80ZtQpc=
|
||||
golang.org/x/term v0.41.0 h1:QCgPso/Q3RTJx2Th4bDLqML4W6iJiaXFq2/ftQF13YU=
|
||||
golang.org/x/term v0.41.0/go.mod h1:3pfBgksrReYfZ5lvYM0kSO0LIkAl4Yl2bXOkKP7Ec2A=
|
||||
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
|
||||
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
|
||||
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
golang.org/x/tools v0.26.0/go.mod h1:TPVVj70c7JJ3WCazhD8OdXcZg/og+b9+tH/KxylGwH0=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
@@ -196,6 +211,7 @@ golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0
|
||||
golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0=
|
||||
golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
|
||||
golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
|
||||
gonum.org/v1/plot v0.15.2 h1:Tlfh/jBk2tqjLZ4/P8ZIwGrLEWQSPDLRm/SNWKNXiGI=
|
||||
gonum.org/v1/plot v0.15.2/go.mod h1:DX+x+DWso3LTha+AdkJEv5Txvi+Tql3KAGkehP0/Ubg=
|
||||
|
||||
+3
-3
@@ -51,7 +51,7 @@ type logEntry struct {
|
||||
shouldFatal bool
|
||||
}
|
||||
|
||||
// NewLogger returns a Logger that emits logs to Sentry. If logging is turned off, all logs get discarded.
|
||||
// NewLogger returns a Logger that emits logs to Sentry.
|
||||
func NewLogger(ctx context.Context) Logger { // nolint: dupl
|
||||
var hub *Hub
|
||||
hub = GetHubFromContext(ctx)
|
||||
@@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
|
||||
}
|
||||
|
||||
client := hub.Client()
|
||||
if client != nil && !client.options.DisableLogs {
|
||||
if client != nil {
|
||||
// Build default attrs
|
||||
serverAddr := client.options.ServerName
|
||||
if serverAddr == "" {
|
||||
@@ -91,7 +91,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
|
||||
}
|
||||
}
|
||||
|
||||
debuglog.Println("fallback to noopLogger: SDK not initialized or logs disabled")
|
||||
debuglog.Println("fallback to noopLogger: SDK not initialized")
|
||||
return &noopLogger{}
|
||||
}
|
||||
|
||||
|
||||
+7
-7
@@ -47,7 +47,7 @@ const (
|
||||
UnitPercent = "percent"
|
||||
)
|
||||
|
||||
// NewMeter returns a new Meter. If there is no Client bound to the current hub, or if metrics are disabled,
|
||||
// NewMeter returns a new Meter. If there is no Client bound to the current hub,
|
||||
// it returns a no-op Meter that discards all metrics.
|
||||
func NewMeter(ctx context.Context) Meter {
|
||||
hub := GetHubFromContext(ctx)
|
||||
@@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter {
|
||||
hub = CurrentHub()
|
||||
}
|
||||
client := hub.Client()
|
||||
if client != nil && !client.options.DisableMetrics {
|
||||
if client != nil {
|
||||
// build default attrs
|
||||
serverAddr := client.options.ServerName
|
||||
if serverAddr == "" {
|
||||
@@ -86,7 +86,7 @@ func NewMeter(ctx context.Context) Meter {
|
||||
}
|
||||
}
|
||||
|
||||
debuglog.Printf("fallback to noopMeter: metrics disabled")
|
||||
debuglog.Printf("fallback to noopMeter: SDK not initialized")
|
||||
return &noopMeter{}
|
||||
}
|
||||
|
||||
@@ -222,20 +222,20 @@ func (n *noopMeter) WithCtx(_ context.Context) Meter {
|
||||
|
||||
// Count implements Meter.
|
||||
func (n *noopMeter) Count(name string, _ int64, _ ...MeterOption) {
|
||||
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
|
||||
debuglog.Printf("Metric %q is being dropped. Ensure the SDK is initialized", name)
|
||||
}
|
||||
|
||||
// Distribution implements Meter.
|
||||
func (n *noopMeter) Distribution(name string, _ float64, _ ...MeterOption) {
|
||||
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
|
||||
debuglog.Printf("Metric %q is being dropped. Ensure the SDK is initialized", name)
|
||||
}
|
||||
|
||||
// Gauge implements Meter.
|
||||
func (n *noopMeter) Gauge(name string, _ float64, _ ...MeterOption) {
|
||||
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
|
||||
debuglog.Printf("Metric %q is being dropped. Ensure the SDK is initialized", name)
|
||||
}
|
||||
|
||||
// SetAttributes implements Meter.
|
||||
func (n *noopMeter) SetAttributes(_ ...attribute.Builder) {
|
||||
debuglog.Printf("No attributes attached. Turn on metrics by setting DisableMetrics to false")
|
||||
debuglog.Printf("No attributes attached")
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// The version of the SDK.
|
||||
const SDKVersion = "0.48.0"
|
||||
const SDKVersion = "0.49.0"
|
||||
|
||||
// apiVersion is the minimum version of the Sentry API compatible with the
|
||||
// sentry-go SDK.
|
||||
|
||||
+16
@@ -33,6 +33,7 @@ func NewStacktrace() *Stacktrace {
|
||||
}
|
||||
|
||||
runtimeFrames := extractFrames(pcs[:n])
|
||||
runtimeFrames = trimPanicFrames(runtimeFrames)
|
||||
frames := createFrames(runtimeFrames)
|
||||
|
||||
stacktrace := Stacktrace{
|
||||
@@ -282,6 +283,21 @@ func extractFrames(pcs []uintptr) []runtime.Frame {
|
||||
return frames
|
||||
}
|
||||
|
||||
// trimPanicFrames removes frames added while handling an active panic.
|
||||
//
|
||||
// The runtime.gopanic frame indicates the part of the code that caused the panic.
|
||||
// This is helpful for skipping any wrapper code that was used to handle and recover
|
||||
// from the panic, so that we only keep the relevant frames.
|
||||
func trimPanicFrames(frames []runtime.Frame) []runtime.Frame {
|
||||
for i := len(frames) - 1; i >= 0; i-- {
|
||||
if frames[i].Function == "runtime.gopanic" {
|
||||
return frames[:i]
|
||||
}
|
||||
}
|
||||
|
||||
return frames
|
||||
}
|
||||
|
||||
// createFrames creates Frame objects while filtering out frames that are not
|
||||
// meant to be reported to Sentry, those are frames internal to the SDK or Go.
|
||||
func createFrames(frames []runtime.Frame) []Frame {
|
||||
|
||||
+2
@@ -43,6 +43,7 @@ go get -u github.com/go-faker/faker/v4
|
||||
- [language: example_with_tags_lang_test.go](/example_with_tags_lang_test.go)
|
||||
- [unique: example_with_tags_unique_test.go](example_with_tags_unique_test.go)
|
||||
- [slice length: example_with_tags_slicelength_test.go](example_with_tags_slicelength_test.go)
|
||||
- [template (derived fields): example_template_tag_test.go](example_template_tag_test.go)
|
||||
- Custom Struct's tag (define your own faker data): [example_custom_faker_test.go](/example_custom_faker_test.go)
|
||||
- Without struct's tag: [example_without_tag_test.go](/example_without_tag_test.go)
|
||||
- Single Fake Data Function: [example_single_fake_data_test.go](/example_single_fake_data_test.go)
|
||||
@@ -103,6 +104,7 @@ Unfortunately this library has some limitation
|
||||
- It does not support the `map[any]any`, `map[T]any` & `map[any]T` data types (where `T` is any concrete type). Once again, we cannot generate values for an unknown data type.
|
||||
- Some extra custom types can be supported IF AND ONLY IF extended with [AddProvider()](https://github.com/go-faker/faker/blob/7473ac7d8d0440d24addac302c73e13c08895764/faker.go#L303) please see [example](example_custom_faker_test.go#L46)
|
||||
- The `oneof` tag currently only supports `string`, the `int` types, and both `float32` & `float64`. Further support is coming soon (i.e. hex numbers, etc). See [example](example_with_tags_test.go#L53) for usage.
|
||||
- The `template` tag currently only supports `string`, named string types & `*string`, and can only reference the fields of the struct that declares it. See [example](example_template_tag_test.go) for usage.
|
||||
|
||||
## Contribution
|
||||
|
||||
|
||||
+64
-1
@@ -91,6 +91,7 @@ const (
|
||||
comma = ","
|
||||
colon = ":"
|
||||
ONEOF = "oneof"
|
||||
TemplateTag = "template"
|
||||
RussianFirstNameMaleTag = "russian_first_name_male"
|
||||
RussianMiddleNameMaleTag = "russian_middle_name_male"
|
||||
RussianLastNameMaleTag = "russian_last_name_male"
|
||||
@@ -586,6 +587,8 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
|
||||
}
|
||||
originalDataVal := reflect.ValueOf(item)
|
||||
v := reflect.New(t).Elem()
|
||||
// collect template fields to evaluate in a second pass
|
||||
var templateFields []int
|
||||
if opts.MaxFieldDepthOption == 0 {
|
||||
return v, nil
|
||||
} else if opts.MaxFieldDepthOption > 0 {
|
||||
@@ -617,6 +620,27 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
|
||||
}
|
||||
|
||||
tags := decodeTags(t, i, opts.TagName)
|
||||
// A template field is derived from other fields, so it is deferred to a
|
||||
// second pass that runs once every other field has been generated.
|
||||
if tags.isTemplate {
|
||||
if tags.unique {
|
||||
// A template over fixed inputs is deterministic, so the retry loop
|
||||
// could never produce a different value. Fail loudly instead.
|
||||
return reflect.Value{}, fmt.Errorf(fakerErrors.ErrTemplateWithUnique, t.Field(i).Name)
|
||||
}
|
||||
if tags.keepOriginal {
|
||||
zero, err := isZero(originalDataVal.Field(i))
|
||||
if err != nil {
|
||||
return reflect.Value{}, err
|
||||
}
|
||||
if !zero {
|
||||
v.Field(i).Set(originalDataVal.Field(i))
|
||||
continue
|
||||
}
|
||||
}
|
||||
templateFields = append(templateFields, i)
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case tags.keepOriginal:
|
||||
zero, err := isZero(reflect.ValueOf(item).Field(i))
|
||||
@@ -675,6 +699,10 @@ func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (re
|
||||
}
|
||||
|
||||
}
|
||||
// second pass: evaluate template fields using values generated above
|
||||
if err := evaluateTemplateFields(t, v, templateFields, opts.TagName); err != nil {
|
||||
return reflect.Value{}, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
@@ -699,6 +727,10 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
|
||||
uni := false
|
||||
res := make([]string, 0)
|
||||
pMap := make(map[string]string)
|
||||
// body collects the template body once a "template:" chunk is seen. Everything
|
||||
// after that chunk belongs to the body, so a template may contain commas; only
|
||||
// the standalone "keep" and "unique" chunks keep their usual meaning.
|
||||
var body []string
|
||||
for _, tag := range tags {
|
||||
if tag == keep {
|
||||
keepOriginal = true
|
||||
@@ -707,12 +739,30 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
|
||||
uni = true
|
||||
continue
|
||||
}
|
||||
if body != nil {
|
||||
body = append(body, tag)
|
||||
continue
|
||||
}
|
||||
if hasTemplatePrefix(strings.TrimSpace(tag)) {
|
||||
body = append(body, strings.TrimSpace(tag)[len(TemplateTag)+1:])
|
||||
continue
|
||||
}
|
||||
// res = append(res, tag)
|
||||
ptag := strings.ToLower(strings.Trim(strings.Split(tag, "=")[0], " "))
|
||||
pMap[ptag] = tag
|
||||
ptag = strings.ToLower(strings.Trim(strings.Split(tag, ":")[0], " "))
|
||||
pMap[ptag] = tag
|
||||
}
|
||||
if body != nil {
|
||||
// A template body is opaque: it must never reach the priority scanner, which
|
||||
// would otherwise hijack a chunk such as ", email: {{.X}}" as the email tag.
|
||||
return structTag{
|
||||
template: strings.Join(body, comma),
|
||||
isTemplate: true,
|
||||
unique: uni,
|
||||
keepOriginal: keepOriginal,
|
||||
}
|
||||
}
|
||||
// Priority
|
||||
for _, ptag := range PriorityTags {
|
||||
if tag, ok := pMap[ptag]; ok {
|
||||
@@ -739,9 +789,22 @@ func decodeTags(typ reflect.Type, i int, tagName string) structTag {
|
||||
}
|
||||
|
||||
type structTag struct {
|
||||
fieldType string
|
||||
fieldType string
|
||||
// template holds the verbatim template body when isTemplate is set. It is kept
|
||||
// out of fieldType because a template body is not a tag and must not be parsed
|
||||
// as one.
|
||||
template string
|
||||
unique bool
|
||||
keepOriginal bool
|
||||
isTemplate bool
|
||||
}
|
||||
|
||||
// hasTemplatePrefix reports whether s starts with "template:" (case-insensitive).
|
||||
// The colon is required, so `faker:"template"` and `faker:"templated"` stay with
|
||||
// the normal tag pipeline.
|
||||
func hasTemplatePrefix(s string) bool {
|
||||
const n = len(TemplateTag) + 1
|
||||
return len(s) >= n && strings.EqualFold(s[:n], TemplateTag+colon)
|
||||
}
|
||||
|
||||
func setDataWithTag(v reflect.Value, tag string, opt options.Options) error {
|
||||
|
||||
+13
@@ -10,6 +10,12 @@ package errors
|
||||
// ErrTagDoesNotExist: Error when tag does not exist and call RemoveProvider
|
||||
// ErrMoreArguments: Error on passing more arguments
|
||||
// ErrNotSupportedPointer: Error when passing unsupported pointer
|
||||
// ErrTemplateNotStringField: Error when the template tag is used on a non-string field
|
||||
// ErrTemplateEmptyBody: Error when the template tag has no body
|
||||
// ErrTemplateParse: Error when the template body fails to parse
|
||||
// ErrTemplateEvaluate: Error when the template body fails to execute
|
||||
// ErrTemplateCycle: Error when template fields reference each other in a cycle
|
||||
// ErrTemplateWithUnique: Error when the template tag is combined with the unique tag
|
||||
var (
|
||||
ErrUnsupportedKindPtr = "Unsupported kind: %s Change Without using * (pointer) in Field of %s"
|
||||
ErrUnsupportedKind = "Unsupported kind: %s"
|
||||
@@ -33,4 +39,11 @@ var (
|
||||
ErrNotEnoughTagArguments = "Not enough arguments for tag."
|
||||
ErrUnsupportedNumberType = "Unsupported Number type."
|
||||
ErrOnlyStructTypeSupported = "only struct type supported."
|
||||
|
||||
ErrTemplateNotStringField = "Template tag is only supported on string fields, field \"%s\" is %s"
|
||||
ErrTemplateEmptyBody = "Template tag for field \"%s\" has an empty body"
|
||||
ErrTemplateParse = "Failed to parse template for field \"%s\": %w"
|
||||
ErrTemplateEvaluate = "Failed to evaluate template for field \"%s\": %w"
|
||||
ErrTemplateCycle = "Template tag cycle detected: %s"
|
||||
ErrTemplateWithUnique = "Tag \"unique\" can not be combined with the template tag (field \"%s\")"
|
||||
)
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
package faker
|
||||
|
||||
// The template tag (`faker:"template:{{.Other}}"`) derives a field's value from
|
||||
// other fields of the same struct. Because a template reads values that faker
|
||||
// itself generates, template fields are filled in a second pass that runs after
|
||||
// every other field of the struct is done — see getFakedValueForStruct.
|
||||
//
|
||||
// Within that second pass, template fields are evaluated in dependency order
|
||||
// rather than declaration order, so a template may reference another template
|
||||
// field declared later. Only a true cycle is an error.
|
||||
//
|
||||
// TemplateTag is deliberately absent from PriorityTags: it is not a provider, and
|
||||
// listing it there would route the tag through setDataWithTag.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"text/template"
|
||||
"text/template/parse"
|
||||
"unicode"
|
||||
|
||||
fakerErrors "github.com/go-faker/faker/v4/pkg/errors"
|
||||
)
|
||||
|
||||
// templateField is one parsed, validated template-tagged field of a struct.
|
||||
type templateField struct {
|
||||
index int // index of the field within the struct
|
||||
name string // field name, used in error messages
|
||||
tpl *template.Template
|
||||
deps []int // positions within templatePlan.fields this field depends on
|
||||
}
|
||||
|
||||
// templatePlan is the validated evaluation plan for the template fields of one
|
||||
// struct type.
|
||||
type templatePlan struct {
|
||||
fields []templateField // declaration order
|
||||
order []int // positions within fields, in dependency order
|
||||
}
|
||||
|
||||
// evaluateTemplateFields fills the template-tagged fields of v listed in fields.
|
||||
// v must be an addressable struct value of type t. fields holds struct field
|
||||
// indices collected by the first pass; a template field missing from it was
|
||||
// handled by a higher-precedence option (IgnoreFields, OnlyZeroFields,
|
||||
// FieldProviders, keep) and is left alone.
|
||||
func evaluateTemplateFields(t reflect.Type, v reflect.Value, fields []int, tagName string) error {
|
||||
if len(fields) == 0 {
|
||||
return nil
|
||||
}
|
||||
if !v.CanAddr() {
|
||||
return errors.New(fakerErrors.ErrValueNotPtr)
|
||||
}
|
||||
plan, err := buildTemplatePlan(t, tagName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Templates read the struct itself rather than a map built by reflection. That
|
||||
// is what makes unexported fields safe: text/template reports them as an error
|
||||
// instead of us panicking on reflect.Value.Interface. Taking the address means
|
||||
// each template also sees the results written by earlier ones.
|
||||
data := v.Addr().Interface()
|
||||
var buf bytes.Buffer
|
||||
for _, p := range plan.order {
|
||||
tf := &plan.fields[p]
|
||||
if !containsFieldIndex(fields, tf.index) {
|
||||
continue
|
||||
}
|
||||
buf.Reset()
|
||||
if err := tf.tpl.Execute(&buf, data); err != nil {
|
||||
return fmt.Errorf(fakerErrors.ErrTemplateEvaluate, tf.name, err)
|
||||
}
|
||||
setTemplateResult(v.Field(tf.index), buf.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func containsFieldIndex(fields []int, idx int) bool {
|
||||
for _, f := range fields {
|
||||
if f == idx {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// buildTemplatePlan parses and validates every template-tagged field of t and
|
||||
// works out the order they must be evaluated in.
|
||||
func buildTemplatePlan(t reflect.Type, tagName string) (*templatePlan, error) {
|
||||
plan := &templatePlan{}
|
||||
posByName := make(map[string]int)
|
||||
|
||||
for i := range t.NumField() {
|
||||
f := t.Field(i)
|
||||
if !f.IsExported() {
|
||||
continue
|
||||
}
|
||||
tags := decodeTags(t, i, tagName)
|
||||
if !tags.isTemplate {
|
||||
continue
|
||||
}
|
||||
// Validate the destination before anything is evaluated, so a bad tag can
|
||||
// never leave some fields written and others not.
|
||||
if !templateAssignable(f.Type) {
|
||||
return nil, fmt.Errorf(fakerErrors.ErrTemplateNotStringField, f.Name, f.Type)
|
||||
}
|
||||
if strings.TrimSpace(tags.template) == "" {
|
||||
return nil, fmt.Errorf(fakerErrors.ErrTemplateEmptyBody, f.Name)
|
||||
}
|
||||
tpl, err := template.New(f.Name).Funcs(templateHelpers).Parse(tags.template)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(fakerErrors.ErrTemplateParse, f.Name, err)
|
||||
}
|
||||
posByName[f.Name] = len(plan.fields)
|
||||
plan.fields = append(plan.fields, templateField{index: i, name: f.Name, tpl: tpl})
|
||||
}
|
||||
if len(plan.fields) == 0 {
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// Only references to other template fields become edges. References to ordinary
|
||||
// fields need no ordering: the first pass already filled them.
|
||||
for p := range plan.fields {
|
||||
for _, ref := range templateFieldRefs(plan.fields[p].tpl.Tree) {
|
||||
if q, ok := posByName[ref]; ok {
|
||||
plan.fields[p].deps = append(plan.fields[p].deps, q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
order, err := topoSortTemplateFields(plan.fields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan.order = order
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// templateAssignable reports whether the template result can be stored in a field
|
||||
// of type t. Named string types work through SetString; *string is allocated.
|
||||
func templateAssignable(t reflect.Type) bool {
|
||||
return t.Kind() == reflect.String ||
|
||||
(t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.String)
|
||||
}
|
||||
|
||||
func setTemplateResult(f reflect.Value, s string) {
|
||||
if f.Kind() == reflect.Pointer {
|
||||
p := reflect.New(f.Type().Elem())
|
||||
p.Elem().SetString(s)
|
||||
f.Set(p)
|
||||
return
|
||||
}
|
||||
f.SetString(s)
|
||||
}
|
||||
|
||||
// templateFieldRefs returns the names of the struct fields a template reads, in
|
||||
// source order and deduplicated.
|
||||
//
|
||||
// It walks the parse tree rather than matching the template source with a regular
|
||||
// expression: only the tree can tell a field reference from literal text such as
|
||||
// "@Example.Com", can report `{{.Addr.City}}` as a reference to Addr alone, and
|
||||
// can tell that the dot inside a `range` or `with` body is the loop value rather
|
||||
// than the struct.
|
||||
func templateFieldRefs(tree *parse.Tree) []string {
|
||||
if tree == nil || tree.Root == nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
seen := make(map[string]struct{})
|
||||
add := func(name string) {
|
||||
if _, ok := seen[name]; !ok {
|
||||
seen[name] = struct{}{}
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
var walk func(parse.Node)
|
||||
// walkBranch handles if/range/with. The controlling pipe is always evaluated
|
||||
// with the outer dot; range and with rebind dot for their body, so the body
|
||||
// cannot reference our struct's fields. An else body runs with the outer dot.
|
||||
walkBranch := func(b *parse.BranchNode, rebindsDot bool) {
|
||||
walk(b.Pipe)
|
||||
if !rebindsDot && b.List != nil {
|
||||
walk(b.List)
|
||||
}
|
||||
if b.ElseList != nil {
|
||||
walk(b.ElseList)
|
||||
}
|
||||
}
|
||||
walk = func(n parse.Node) {
|
||||
switch n := n.(type) {
|
||||
case *parse.ListNode:
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
for _, c := range n.Nodes {
|
||||
walk(c)
|
||||
}
|
||||
case *parse.ActionNode:
|
||||
walk(n.Pipe)
|
||||
case *parse.PipeNode:
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
for _, d := range n.Decl {
|
||||
walk(d)
|
||||
}
|
||||
for _, c := range n.Cmds {
|
||||
walk(c)
|
||||
}
|
||||
case *parse.CommandNode:
|
||||
for _, a := range n.Args {
|
||||
walk(a)
|
||||
}
|
||||
case *parse.FieldNode:
|
||||
if len(n.Ident) > 0 {
|
||||
add(n.Ident[0])
|
||||
}
|
||||
case *parse.ChainNode:
|
||||
if _, isDot := n.Node.(*parse.DotNode); isDot && len(n.Field) > 0 {
|
||||
add(n.Field[0])
|
||||
}
|
||||
walk(n.Node)
|
||||
case *parse.IfNode:
|
||||
walkBranch(&n.BranchNode, false)
|
||||
case *parse.RangeNode:
|
||||
walkBranch(&n.BranchNode, true)
|
||||
case *parse.WithNode:
|
||||
walkBranch(&n.BranchNode, true)
|
||||
case *parse.TemplateNode:
|
||||
walk(n.Pipe)
|
||||
}
|
||||
}
|
||||
walk(tree.Root)
|
||||
return out
|
||||
}
|
||||
|
||||
// topoSortTemplateFields returns the positions of fields in dependency order:
|
||||
// every field appears after the template fields it references. Roots are visited
|
||||
// in declaration order so the result is deterministic. A cycle, including a field
|
||||
// that references itself, is an error.
|
||||
func topoSortTemplateFields(fields []templateField) ([]int, error) {
|
||||
const (
|
||||
white = iota
|
||||
grey
|
||||
black
|
||||
)
|
||||
state := make([]int8, len(fields))
|
||||
order := make([]int, 0, len(fields))
|
||||
stack := make([]int, 0, len(fields))
|
||||
|
||||
var visit func(p int) error
|
||||
visit = func(p int) error {
|
||||
switch state[p] {
|
||||
case black:
|
||||
return nil
|
||||
case grey:
|
||||
return fmt.Errorf(fakerErrors.ErrTemplateCycle, cyclePath(fields, stack, p))
|
||||
}
|
||||
state[p] = grey
|
||||
stack = append(stack, p)
|
||||
for _, d := range fields[p].deps {
|
||||
if err := visit(d); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
state[p] = black
|
||||
order = append(order, p)
|
||||
return nil
|
||||
}
|
||||
for p := range fields {
|
||||
if err := visit(p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// cyclePath renders a cycle as "A -> B -> A", starting from where p first appears
|
||||
// on the visit stack.
|
||||
func cyclePath(fields []templateField, stack []int, p int) string {
|
||||
start := 0
|
||||
for i, s := range stack {
|
||||
if s == p {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
names := make([]string, 0, len(stack)-start+1)
|
||||
for _, s := range stack[start:] {
|
||||
names = append(names, fields[s].name)
|
||||
}
|
||||
names = append(names, fields[p].name)
|
||||
return strings.Join(names, " -> ")
|
||||
}
|
||||
|
||||
// templateHelpers is read-only after initialization and shared by every template.
|
||||
var templateHelpers = template.FuncMap{
|
||||
"lower": func(v any) string { return strings.ToLower(templateString(v)) },
|
||||
"upper": func(v any) string { return strings.ToUpper(templateString(v)) },
|
||||
"trim": func(v any) string { return strings.TrimSpace(templateString(v)) },
|
||||
"slug": func(v any) string { return slugify(templateString(v)) },
|
||||
}
|
||||
|
||||
// templateString coerces a template argument to a string so the helpers also work
|
||||
// on named string types, numbers and fmt.Stringer values.
|
||||
func templateString(v any) string {
|
||||
switch s := v.(type) {
|
||||
case nil:
|
||||
return ""
|
||||
case string:
|
||||
return s
|
||||
case fmt.Stringer:
|
||||
return s.String()
|
||||
}
|
||||
if rv := reflect.ValueOf(v); rv.Kind() == reflect.String {
|
||||
return rv.String()
|
||||
}
|
||||
return fmt.Sprint(v)
|
||||
}
|
||||
|
||||
// slugify lowercases s and replaces each run of non-alphanumeric characters with
|
||||
// a single dash, trimming dashes from both ends. Letters and digits of any script
|
||||
// are kept, so names generated by the Chinese and Russian providers survive.
|
||||
func slugify(s string) string {
|
||||
s = strings.ToLower(s)
|
||||
var b strings.Builder
|
||||
b.Grow(len(s))
|
||||
lastDash := false
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case unicode.IsLetter(r) || unicode.IsDigit(r):
|
||||
b.WriteRune(r)
|
||||
lastDash = false
|
||||
case !lastDash:
|
||||
b.WriteByte('-')
|
||||
lastDash = true
|
||||
}
|
||||
}
|
||||
return strings.Trim(b.String(), "-")
|
||||
}
|
||||
+15
-188
@@ -1,222 +1,49 @@
|
||||
//go:build amd64 && !appengine && !noasm && gc
|
||||
|
||||
// This file contains the specialisation of Decoder.Decompress4X
|
||||
// and Decoder.Decompress1X that use an asm implementation of thir main loops.
|
||||
// amd64 stubs and dispatch for the asm loops used by decompress_asm.go.
|
||||
package huff0
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/klauspost/compress/internal/cpuinfo"
|
||||
)
|
||||
|
||||
// decompress4x_main_loop_x86 is an x86 assembler implementation
|
||||
// decompress4x_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_loop_x86 is an x86 assembler implementation
|
||||
// decompress4x_8b_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress4X when tablelog <= 8 which decodes 4 entries
|
||||
// per loop.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext)
|
||||
|
||||
// fallback8BitSize is the size where using Go version is faster.
|
||||
const fallback8BitSize = 800
|
||||
|
||||
type decompress4xContext struct {
|
||||
pbr *[4]bitReaderShifted
|
||||
peekBits uint8
|
||||
out *byte
|
||||
dstEvery int
|
||||
tbl *dEntrySingle
|
||||
decoded int
|
||||
limit *byte
|
||||
}
|
||||
|
||||
// Decompress4X will decompress a 4X encoded stream.
|
||||
// The length of the supplied input must match the end of a block exactly.
|
||||
// The *capacity* of the dst slice must match the destination size of
|
||||
// the uncompressed data exactly.
|
||||
func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) {
|
||||
if len(d.dt.single) == 0 {
|
||||
return nil, errors.New("no table loaded")
|
||||
}
|
||||
if len(src) < 6+(4*1) {
|
||||
return nil, errors.New("input too small")
|
||||
}
|
||||
|
||||
use8BitTables := d.actualTableLog <= 8
|
||||
if cap(dst) < fallback8BitSize && use8BitTables {
|
||||
return d.decompress4X8bit(dst, src)
|
||||
}
|
||||
|
||||
var br [4]bitReaderShifted
|
||||
// Decode "jump table"
|
||||
start := 6
|
||||
for i := range 3 {
|
||||
length := int(src[i*2]) | (int(src[i*2+1]) << 8)
|
||||
if start+length >= len(src) {
|
||||
return nil, errors.New("truncated input (or invalid offset)")
|
||||
}
|
||||
err := br[i].init(src[start : start+length])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
start += length
|
||||
}
|
||||
err := br[3].init(src[start:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// destination, offset to match first output
|
||||
dstSize := cap(dst)
|
||||
dst = dst[:dstSize]
|
||||
out := dst
|
||||
dstEvery := (dstSize + 3) / 4
|
||||
|
||||
const tlSize = 1 << tableLogMax
|
||||
const tlMask = tlSize - 1
|
||||
single := d.dt.single[:tlSize]
|
||||
|
||||
var decoded int
|
||||
|
||||
if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) {
|
||||
ctx := decompress4xContext{
|
||||
pbr: &br,
|
||||
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
|
||||
out: &out[0],
|
||||
dstEvery: dstEvery,
|
||||
tbl: &single[0],
|
||||
limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last.
|
||||
}
|
||||
if use8BitTables {
|
||||
decompress4x_8b_main_loop_amd64(&ctx)
|
||||
} else {
|
||||
decompress4x_main_loop_amd64(&ctx)
|
||||
}
|
||||
|
||||
decoded = ctx.decoded
|
||||
out = out[decoded/4:]
|
||||
}
|
||||
|
||||
// Decode remaining.
|
||||
remainBytes := dstEvery - (decoded / 4)
|
||||
for i := range br {
|
||||
offset := dstEvery * i
|
||||
endsAt := min(offset+remainBytes, len(out))
|
||||
br := &br[i]
|
||||
bitsLeft := br.remaining()
|
||||
for bitsLeft > 0 {
|
||||
br.fill()
|
||||
if offset >= endsAt {
|
||||
return nil, errors.New("corruption detected: stream overrun 4")
|
||||
}
|
||||
|
||||
// Read value and increment offset.
|
||||
val := br.peekBitsFast(d.actualTableLog)
|
||||
v := single[val&tlMask].entry
|
||||
nBits := uint8(v)
|
||||
br.advance(nBits)
|
||||
bitsLeft -= uint(nBits)
|
||||
out[offset] = uint8(v >> 8)
|
||||
offset++
|
||||
}
|
||||
if offset != endsAt {
|
||||
return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt)
|
||||
}
|
||||
decoded += offset - dstEvery*i
|
||||
err = br.close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if dstSize != decoded {
|
||||
return nil, errors.New("corruption detected: short output block")
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
// decompress4x_main_loop_x86 is an x86 assembler implementation
|
||||
// decompress1x_main_loop_amd64 is an x86 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_amd64(ctx *decompress1xContext)
|
||||
|
||||
// decompress4x_main_loop_x86 is an x86 with BMI2 assembler implementation
|
||||
// decompress1x_main_loop_bmi2 is an x86 with BMI2 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_bmi2(ctx *decompress1xContext)
|
||||
|
||||
type decompress1xContext struct {
|
||||
pbr *bitReaderShifted
|
||||
peekBits uint8
|
||||
out *byte
|
||||
outCap int
|
||||
tbl *dEntrySingle
|
||||
decoded int
|
||||
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_main_loop_amd64(ctx)
|
||||
}
|
||||
|
||||
// Error reported by asm implementations
|
||||
const error_max_decoded_size_exeeded = -1
|
||||
func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_8b_main_loop_amd64(ctx)
|
||||
}
|
||||
|
||||
// Decompress1X will decompress a 1X encoded stream.
|
||||
// The cap of the output buffer will be the maximum decompressed size.
|
||||
// The length of the supplied input must match the end of a block exactly.
|
||||
func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) {
|
||||
if len(d.dt.single) == 0 {
|
||||
return nil, errors.New("no table loaded")
|
||||
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress1x_main_loop_bmi2(ctx)
|
||||
} else {
|
||||
decompress1x_main_loop_amd64(ctx)
|
||||
}
|
||||
var br bitReaderShifted
|
||||
err := br.init(src)
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
maxDecodedSize := cap(dst)
|
||||
dst = dst[:maxDecodedSize]
|
||||
|
||||
const tlSize = 1 << tableLogMax
|
||||
const tlMask = tlSize - 1
|
||||
|
||||
if maxDecodedSize >= 4 {
|
||||
ctx := decompress1xContext{
|
||||
pbr: &br,
|
||||
out: &dst[0],
|
||||
outCap: maxDecodedSize,
|
||||
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
|
||||
tbl: &d.dt.single[0],
|
||||
}
|
||||
|
||||
if cpuinfo.HasBMI2() {
|
||||
decompress1x_main_loop_bmi2(&ctx)
|
||||
} else {
|
||||
decompress1x_main_loop_amd64(&ctx)
|
||||
}
|
||||
if ctx.decoded == error_max_decoded_size_exeeded {
|
||||
return nil, ErrMaxDecodedSizeExceeded
|
||||
}
|
||||
|
||||
dst = dst[:ctx.decoded]
|
||||
}
|
||||
|
||||
// br < 8, so uint8 is fine
|
||||
bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead
|
||||
for bitsLeft > 0 {
|
||||
br.fill()
|
||||
if len(dst) >= maxDecodedSize {
|
||||
br.close()
|
||||
return nil, ErrMaxDecodedSizeExceeded
|
||||
}
|
||||
v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask]
|
||||
nBits := uint8(v.entry)
|
||||
br.advance(nBits)
|
||||
bitsLeft -= nBits
|
||||
dst = append(dst, uint8(v.entry>>8))
|
||||
}
|
||||
return dst, br.close()
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
// Code generated by command: go run gen.go -out ../decompress_amd64.s -pkg=huff0. DO NOT EDIT.
|
||||
// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -pkg=huff0. DO NOT EDIT.
|
||||
|
||||
//go:build amd64 && !appengine && !noasm && gc
|
||||
//go:build !appengine && !noasm && gc
|
||||
|
||||
// func decompress4x_main_loop_amd64(ctx *decompress4xContext)
|
||||
TEXT ·decompress4x_main_loop_amd64(SB), $0-8
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
//go:build arm64 && !appengine && !noasm && gc
|
||||
|
||||
// arm64 stubs and dispatch for the asm loops used by decompress_asm.go.
|
||||
// The asm (decompress_arm64.s) is generated by the avo arm64 lowering
|
||||
// printer from the same source as the amd64 asm; see _generate/gen.go.
|
||||
package huff0
|
||||
|
||||
// decompress4x_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress4x_8b_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress4X when tablelog <= 8 which decodes 4 entries
|
||||
// per loop.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress4x_8b_main_loop_arm64(ctx *decompress4xContext)
|
||||
|
||||
// decompress1x_main_loop_arm64 is an arm64 assembler implementation
|
||||
// of Decompress1X when tablelog > 8.
|
||||
//
|
||||
//go:noescape
|
||||
func decompress1x_main_loop_arm64(ctx *decompress1xContext)
|
||||
|
||||
func decompress4x_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress4x_8b_main_loop_asm(ctx *decompress4xContext) {
|
||||
decompress4x_8b_main_loop_arm64(ctx)
|
||||
}
|
||||
|
||||
func decompress1x_main_loop_asm(ctx *decompress1xContext) {
|
||||
decompress1x_main_loop_arm64(ctx)
|
||||
}
|
||||
+851
@@ -0,0 +1,851 @@
|
||||
// Code generated by command: go run gen.go -out ../decompress.s -arch amd64,arm64 -pkg=huff0. DO NOT EDIT.
|
||||
// EXPERIMENTAL arm64 output lowered from an amd64 avo program.
|
||||
|
||||
//go:build arm64 && !appengine && !noasm && gc
|
||||
|
||||
// func decompress4x_main_loop_amd64(ctx *decompress4xContext)
|
||||
TEXT ·decompress4x_main_loop_arm64(SB), $0-8
|
||||
// Preload values
|
||||
MOVD ctx+0(FP), R0
|
||||
MOVBU 8(R0), R6
|
||||
MOVD 16(R0), R3
|
||||
MOVD 48(R0), R5
|
||||
MOVD 24(R0), R7
|
||||
MOVD 32(R0), R8
|
||||
MOVD (R0), R9
|
||||
|
||||
// Main loop
|
||||
main_loop:
|
||||
MOVD $0, R2
|
||||
CMP R5, R3
|
||||
CSET GE, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
// br0.fillFast32()
|
||||
MOVD 32(R9), R10
|
||||
MOVBU 40(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill0
|
||||
MOVD 24(R9), R0
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R0, R0
|
||||
MOVD (R9), R12
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R12, R0, R15
|
||||
MOVWU (R15), R12
|
||||
MOVD R11, R1
|
||||
LSL R1, R12, R12
|
||||
MOVD R0, 24(R9)
|
||||
ORR R12, R10, R10
|
||||
|
||||
// exhausted += (br0.off < 4)
|
||||
CMP $0x04, R0
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill0:
|
||||
// val0 := br0.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br0.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br0.peekTopBits(peekBits)
|
||||
MOVD R6, R1
|
||||
MOVD R10, R12
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val1&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br0.advance(uint8(v1.entry))
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// these two writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
MOVH R0, (R3)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 32(R9)
|
||||
MOVB R11, 40(R9)
|
||||
|
||||
// br1.fillFast32()
|
||||
MOVD 80(R9), R10
|
||||
MOVBU 88(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill1
|
||||
MOVD 72(R9), R0
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R0, R0
|
||||
MOVD 48(R9), R12
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R12, R0, R15
|
||||
MOVWU (R15), R12
|
||||
MOVD R11, R1
|
||||
LSL R1, R12, R12
|
||||
MOVD R0, 72(R9)
|
||||
ORR R12, R10, R10
|
||||
|
||||
// exhausted += (br1.off < 4)
|
||||
CMP $0x04, R0
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill1:
|
||||
// val0 := br1.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br1.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br1.peekTopBits(peekBits)
|
||||
MOVD R6, R1
|
||||
MOVD R10, R12
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val1&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br1.advance(uint8(v1.entry))
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// these two writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
ADD R7, R3, R15
|
||||
MOVH R0, (R15)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 80(R9)
|
||||
MOVB R11, 88(R9)
|
||||
|
||||
// br2.fillFast32()
|
||||
MOVD 128(R9), R10
|
||||
MOVBU 136(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill2
|
||||
MOVD 120(R9), R0
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R0, R0
|
||||
MOVD 96(R9), R12
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R12, R0, R15
|
||||
MOVWU (R15), R12
|
||||
MOVD R11, R1
|
||||
LSL R1, R12, R12
|
||||
MOVD R0, 120(R9)
|
||||
ORR R12, R10, R10
|
||||
|
||||
// exhausted += (br2.off < 4)
|
||||
CMP $0x04, R0
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill2:
|
||||
// val0 := br2.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br2.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br2.peekTopBits(peekBits)
|
||||
MOVD R6, R1
|
||||
MOVD R10, R12
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val1&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br2.advance(uint8(v1.entry))
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// these two writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
ADD R7<<1, R3, R15
|
||||
MOVH R0, (R15)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 128(R9)
|
||||
MOVB R11, 136(R9)
|
||||
|
||||
// br3.fillFast32()
|
||||
MOVD 176(R9), R10
|
||||
MOVBU 184(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill3
|
||||
MOVD 168(R9), R0
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R0, R0
|
||||
MOVD 144(R9), R12
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R12, R0, R15
|
||||
MOVWU (R15), R12
|
||||
MOVD R11, R1
|
||||
LSL R1, R12, R12
|
||||
MOVD R0, 168(R9)
|
||||
ORR R12, R10, R10
|
||||
|
||||
// exhausted += (br3.off < 4)
|
||||
CMP $0x04, R0
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill3:
|
||||
// val0 := br3.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br3.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br3.peekTopBits(peekBits)
|
||||
MOVD R6, R1
|
||||
MOVD R10, R12
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val1&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br3.advance(uint8(v1.entry))
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// these two writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
ADD R7<<1, R7, R1
|
||||
ADD R1, R3, R15
|
||||
MOVH R0, (R15)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 176(R9)
|
||||
MOVB R11, 184(R9)
|
||||
ADD $0x02, R3, R3
|
||||
AND $0xff, R2, R15
|
||||
AND $0xff, R2, R16
|
||||
TST R16, R15
|
||||
BEQ main_loop
|
||||
MOVD ctx+0(FP), R0
|
||||
MOVD 16(R0), R16
|
||||
SUB R16, R3, R3
|
||||
LSL $0x02, R3, R3
|
||||
MOVD R3, 40(R0)
|
||||
RET
|
||||
|
||||
// func decompress4x_8b_main_loop_amd64(ctx *decompress4xContext)
|
||||
TEXT ·decompress4x_8b_main_loop_arm64(SB), $0-8
|
||||
// Preload values
|
||||
MOVD ctx+0(FP), R1
|
||||
MOVBU 8(R1), R6
|
||||
MOVD 16(R1), R3
|
||||
MOVD 48(R1), R5
|
||||
MOVD 24(R1), R7
|
||||
MOVD 32(R1), R8
|
||||
MOVD (R1), R9
|
||||
|
||||
// Main loop
|
||||
main_loop:
|
||||
MOVD $0, R2
|
||||
CMP R5, R3
|
||||
CSET GE, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
// br0.fillFast32()
|
||||
MOVD 32(R9), R10
|
||||
MOVBU 40(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill0
|
||||
MOVD 24(R9), R12
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R12, R12
|
||||
MOVD (R9), R13
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R13, R12, R15
|
||||
MOVWU (R15), R13
|
||||
MOVD R11, R1
|
||||
LSL R1, R13, R13
|
||||
MOVD R12, 24(R9)
|
||||
ORR R13, R10, R10
|
||||
|
||||
// exhausted += (br0.off < 4)
|
||||
CMP $0x04, R12
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill0:
|
||||
// val0 := br0.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br0.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br0.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br0.advance(uint8(v1.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// val2 := br0.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v2 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br0.advance(uint8(v2.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val3 := br0.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v3 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br0.advance(uint8(v3.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// these four writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
// out[id * dstEvery + 3] = uint8(v2.entry >> 8)
|
||||
// out[id * dstEvery + 4] = uint8(v3.entry >> 8)
|
||||
MOVW R0, (R3)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 32(R9)
|
||||
MOVB R11, 40(R9)
|
||||
|
||||
// br1.fillFast32()
|
||||
MOVD 80(R9), R10
|
||||
MOVBU 88(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill1
|
||||
MOVD 72(R9), R12
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R12, R12
|
||||
MOVD 48(R9), R13
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R13, R12, R15
|
||||
MOVWU (R15), R13
|
||||
MOVD R11, R1
|
||||
LSL R1, R13, R13
|
||||
MOVD R12, 72(R9)
|
||||
ORR R13, R10, R10
|
||||
|
||||
// exhausted += (br1.off < 4)
|
||||
CMP $0x04, R12
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill1:
|
||||
// val0 := br1.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br1.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br1.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br1.advance(uint8(v1.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// val2 := br1.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v2 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br1.advance(uint8(v2.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val3 := br1.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v3 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br1.advance(uint8(v3.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// these four writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
// out[id * dstEvery + 3] = uint8(v2.entry >> 8)
|
||||
// out[id * dstEvery + 4] = uint8(v3.entry >> 8)
|
||||
ADD R7, R3, R15
|
||||
MOVW R0, (R15)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 80(R9)
|
||||
MOVB R11, 88(R9)
|
||||
|
||||
// br2.fillFast32()
|
||||
MOVD 128(R9), R10
|
||||
MOVBU 136(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill2
|
||||
MOVD 120(R9), R12
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R12, R12
|
||||
MOVD 96(R9), R13
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R13, R12, R15
|
||||
MOVWU (R15), R13
|
||||
MOVD R11, R1
|
||||
LSL R1, R13, R13
|
||||
MOVD R12, 120(R9)
|
||||
ORR R13, R10, R10
|
||||
|
||||
// exhausted += (br2.off < 4)
|
||||
CMP $0x04, R12
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill2:
|
||||
// val0 := br2.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br2.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br2.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br2.advance(uint8(v1.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// val2 := br2.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v2 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br2.advance(uint8(v2.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val3 := br2.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v3 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br2.advance(uint8(v3.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// these four writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
// out[id * dstEvery + 3] = uint8(v2.entry >> 8)
|
||||
// out[id * dstEvery + 4] = uint8(v3.entry >> 8)
|
||||
ADD R7<<1, R3, R15
|
||||
MOVW R0, (R15)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 128(R9)
|
||||
MOVB R11, 136(R9)
|
||||
|
||||
// br3.fillFast32()
|
||||
MOVD 176(R9), R10
|
||||
MOVBU 184(R9), R11
|
||||
CMP $0x20, R11
|
||||
BLS skip_fill3
|
||||
MOVD 168(R9), R12
|
||||
SUB $0x20, R11, R11
|
||||
SUB $0x04, R12, R12
|
||||
MOVD 144(R9), R13
|
||||
|
||||
// b.value |= uint64(low) << (b.bitsRead & 63)
|
||||
ADD R13, R12, R15
|
||||
MOVWU (R15), R13
|
||||
MOVD R11, R1
|
||||
LSL R1, R13, R13
|
||||
MOVD R12, 168(R9)
|
||||
ORR R13, R10, R10
|
||||
|
||||
// exhausted += (br3.off < 4)
|
||||
CMP $0x04, R12
|
||||
CSINC HS, R2, R2, R16
|
||||
BFI $0, R16, $8, R2
|
||||
|
||||
skip_fill3:
|
||||
// val0 := br3.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v0 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br3.advance(uint8(v0.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val1 := br3.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v1 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br3.advance(uint8(v1.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// val2 := br3.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v2 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br3.advance(uint8(v2.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
|
||||
// val3 := br3.peekTopBits(peekBits)
|
||||
MOVD R10, R12
|
||||
MOVD R6, R1
|
||||
LSR R1, R12, R12
|
||||
|
||||
// v3 := table[val0&mask]
|
||||
ADD R12<<1, R8, R15
|
||||
MOVHU (R15), R1
|
||||
|
||||
// br3.advance(uint8(v3.entry)
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
LSL R1, R10, R10
|
||||
ADD R1, R11, R15
|
||||
BFI $0, R15, $8, R11
|
||||
REVW R0, R0
|
||||
|
||||
// these four writes get coalesced
|
||||
// out[id * dstEvery + 0] = uint8(v0.entry >> 8)
|
||||
// out[id * dstEvery + 1] = uint8(v1.entry >> 8)
|
||||
// out[id * dstEvery + 3] = uint8(v2.entry >> 8)
|
||||
// out[id * dstEvery + 4] = uint8(v3.entry >> 8)
|
||||
ADD R7<<1, R7, R1
|
||||
ADD R1, R3, R15
|
||||
MOVW R0, (R15)
|
||||
|
||||
// update the bitreader structure
|
||||
MOVD R10, 176(R9)
|
||||
MOVB R11, 184(R9)
|
||||
ADD $0x04, R3, R3
|
||||
AND $0xff, R2, R15
|
||||
AND $0xff, R2, R16
|
||||
TST R16, R15
|
||||
BEQ main_loop
|
||||
MOVD ctx+0(FP), R0
|
||||
MOVD 16(R0), R16
|
||||
SUB R16, R3, R3
|
||||
LSL $0x02, R3, R3
|
||||
MOVD R3, 40(R0)
|
||||
RET
|
||||
|
||||
// func decompress1x_main_loop_amd64(ctx *decompress1xContext)
|
||||
TEXT ·decompress1x_main_loop_arm64(SB), $0-8
|
||||
MOVD ctx+0(FP), R1
|
||||
MOVD 16(R1), R2
|
||||
MOVD 24(R1), R3
|
||||
CMP $0x04, R3
|
||||
BLO error_max_decoded_size_exceeded
|
||||
ADD R3, R2, R3
|
||||
MOVD (R1), R5
|
||||
MOVD (R5), R7
|
||||
MOVD 24(R5), R8
|
||||
MOVD 32(R5), R9
|
||||
MOVBU 40(R5), R10
|
||||
MOVD 32(R1), R5
|
||||
MOVBU 8(R1), R6
|
||||
JMP loop_condition
|
||||
|
||||
main_loop:
|
||||
// Check if we have room for 4 bytes in the output buffer
|
||||
ADD $4, R2, R1
|
||||
CMP R3, R1
|
||||
BGE error_max_decoded_size_exceeded
|
||||
|
||||
// Decode 4 values
|
||||
CMP $0x20, R10
|
||||
BLT bitReader_fillFast_1_end
|
||||
SUB $0x20, R10, R10
|
||||
SUB $0x04, R8, R8
|
||||
ADD R8, R7, R15
|
||||
MOVWU (R15), R11
|
||||
MOVD R10, R1
|
||||
LSL R1, R11, R11
|
||||
ORR R11, R9, R9
|
||||
|
||||
bitReader_fillFast_1_end:
|
||||
MOVD R6, R1
|
||||
MOVD R9, R11
|
||||
LSR R1, R11, R11
|
||||
ADD R11<<1, R5, R15
|
||||
MOVHU (R15), R1
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
MOVBU R1, R1
|
||||
ADD R1, R10, R10
|
||||
LSL R1, R9, R9
|
||||
MOVD R6, R1
|
||||
MOVD R9, R11
|
||||
LSR R1, R11, R11
|
||||
ADD R11<<1, R5, R15
|
||||
MOVHU (R15), R1
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
MOVBU R1, R1
|
||||
ADD R1, R10, R10
|
||||
LSL R1, R9, R9
|
||||
REVW R0, R0
|
||||
CMP $0x20, R10
|
||||
BLT bitReader_fillFast_2_end
|
||||
SUB $0x20, R10, R10
|
||||
SUB $0x04, R8, R8
|
||||
ADD R8, R7, R15
|
||||
MOVWU (R15), R11
|
||||
MOVD R10, R1
|
||||
LSL R1, R11, R11
|
||||
ORR R11, R9, R9
|
||||
|
||||
bitReader_fillFast_2_end:
|
||||
MOVD R6, R1
|
||||
MOVD R9, R11
|
||||
LSR R1, R11, R11
|
||||
ADD R11<<1, R5, R15
|
||||
MOVHU (R15), R1
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $8, R16, $8, R0
|
||||
MOVBU R1, R1
|
||||
ADD R1, R10, R10
|
||||
LSL R1, R9, R9
|
||||
MOVD R6, R1
|
||||
MOVD R9, R11
|
||||
LSR R1, R11, R11
|
||||
ADD R11<<1, R5, R15
|
||||
MOVHU (R15), R1
|
||||
UBFX $8, R1, $8, R16
|
||||
BFI $0, R16, $8, R0
|
||||
MOVBU R1, R1
|
||||
ADD R1, R10, R10
|
||||
LSL R1, R9, R9
|
||||
REVW R0, R0
|
||||
|
||||
// Store the decoded values
|
||||
MOVW R0, (R2)
|
||||
ADD $0x04, R2, R2
|
||||
|
||||
loop_condition:
|
||||
CMP $0x08, R8
|
||||
BGE main_loop
|
||||
|
||||
// Update ctx structure
|
||||
MOVD ctx+0(FP), R0
|
||||
MOVD 16(R0), R16
|
||||
SUB R16, R2, R2
|
||||
MOVD R2, 40(R0)
|
||||
MOVD (R0), R0
|
||||
MOVD R8, 24(R0)
|
||||
MOVD R9, 32(R0)
|
||||
MOVB R10, 40(R0)
|
||||
RET
|
||||
|
||||
// Report error
|
||||
error_max_decoded_size_exceeded:
|
||||
MOVD ctx+0(FP), R0
|
||||
MOVD $-1, R1
|
||||
MOVD R1, 40(R0)
|
||||
RET
|
||||
|
||||
// skipped decompress1x_main_loop_bmi2 (generic twin preferred on arm64)
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
//go:build (amd64 || arm64) && !appengine && !noasm && gc
|
||||
|
||||
// This file contains the specialisation of Decoder.Decompress4X
|
||||
// and Decoder.Decompress1X that use an asm implementation of their main loops.
|
||||
// The asm function stubs and any per-arch dispatch live in decompress_amd64.go
|
||||
// and decompress_arm64.go.
|
||||
package huff0
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// fallback8BitSize is the size where using Go version is faster.
|
||||
const fallback8BitSize = 800
|
||||
|
||||
type decompress4xContext struct {
|
||||
pbr *[4]bitReaderShifted
|
||||
peekBits uint8
|
||||
out *byte
|
||||
dstEvery int
|
||||
tbl *dEntrySingle
|
||||
decoded int
|
||||
limit *byte
|
||||
}
|
||||
|
||||
// Decompress4X will decompress a 4X encoded stream.
|
||||
// The length of the supplied input must match the end of a block exactly.
|
||||
// The *capacity* of the dst slice must match the destination size of
|
||||
// the uncompressed data exactly.
|
||||
func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) {
|
||||
if len(d.dt.single) == 0 {
|
||||
return nil, errors.New("no table loaded")
|
||||
}
|
||||
if len(src) < 6+(4*1) {
|
||||
return nil, errors.New("input too small")
|
||||
}
|
||||
|
||||
use8BitTables := d.actualTableLog <= 8
|
||||
if cap(dst) < fallback8BitSize && use8BitTables {
|
||||
return d.decompress4X8bit(dst, src)
|
||||
}
|
||||
|
||||
var br [4]bitReaderShifted
|
||||
// Decode "jump table"
|
||||
start := 6
|
||||
for i := range 3 {
|
||||
length := int(src[i*2]) | (int(src[i*2+1]) << 8)
|
||||
if start+length >= len(src) {
|
||||
return nil, errors.New("truncated input (or invalid offset)")
|
||||
}
|
||||
err := br[i].init(src[start : start+length])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
start += length
|
||||
}
|
||||
err := br[3].init(src[start:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// destination, offset to match first output
|
||||
dstSize := cap(dst)
|
||||
dst = dst[:dstSize]
|
||||
out := dst
|
||||
dstEvery := (dstSize + 3) / 4
|
||||
|
||||
const tlSize = 1 << tableLogMax
|
||||
const tlMask = tlSize - 1
|
||||
single := d.dt.single[:tlSize]
|
||||
|
||||
var decoded int
|
||||
|
||||
if len(out) > 4*4 && !(br[0].off < 4 || br[1].off < 4 || br[2].off < 4 || br[3].off < 4) {
|
||||
ctx := decompress4xContext{
|
||||
pbr: &br,
|
||||
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
|
||||
out: &out[0],
|
||||
dstEvery: dstEvery,
|
||||
tbl: &single[0],
|
||||
limit: &out[dstEvery-4], // Always stop decoding when first buffer gets here to avoid writing OOB on last.
|
||||
}
|
||||
if use8BitTables {
|
||||
decompress4x_8b_main_loop_asm(&ctx)
|
||||
} else {
|
||||
decompress4x_main_loop_asm(&ctx)
|
||||
}
|
||||
|
||||
decoded = ctx.decoded
|
||||
out = out[decoded/4:]
|
||||
}
|
||||
|
||||
// Decode remaining.
|
||||
remainBytes := dstEvery - (decoded / 4)
|
||||
for i := range br {
|
||||
offset := dstEvery * i
|
||||
endsAt := min(offset+remainBytes, len(out))
|
||||
br := &br[i]
|
||||
bitsLeft := br.remaining()
|
||||
for bitsLeft > 0 {
|
||||
br.fill()
|
||||
if offset >= endsAt {
|
||||
return nil, errors.New("corruption detected: stream overrun 4")
|
||||
}
|
||||
|
||||
// Read value and increment offset.
|
||||
val := br.peekBitsFast(d.actualTableLog)
|
||||
v := single[val&tlMask].entry
|
||||
nBits := uint8(v)
|
||||
br.advance(nBits)
|
||||
bitsLeft -= uint(nBits)
|
||||
out[offset] = uint8(v >> 8)
|
||||
offset++
|
||||
}
|
||||
if offset != endsAt {
|
||||
return nil, fmt.Errorf("corruption detected: short output block %d, end %d != %d", i, offset, endsAt)
|
||||
}
|
||||
decoded += offset - dstEvery*i
|
||||
err = br.close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if dstSize != decoded {
|
||||
return nil, errors.New("corruption detected: short output block")
|
||||
}
|
||||
return dst, nil
|
||||
}
|
||||
|
||||
type decompress1xContext struct {
|
||||
pbr *bitReaderShifted
|
||||
peekBits uint8
|
||||
out *byte
|
||||
outCap int
|
||||
tbl *dEntrySingle
|
||||
decoded int
|
||||
}
|
||||
|
||||
// Error reported by asm implementations
|
||||
const error_max_decoded_size_exeeded = -1
|
||||
|
||||
// Decompress1X will decompress a 1X encoded stream.
|
||||
// The cap of the output buffer will be the maximum decompressed size.
|
||||
// The length of the supplied input must match the end of a block exactly.
|
||||
func (d *Decoder) Decompress1X(dst, src []byte) ([]byte, error) {
|
||||
if len(d.dt.single) == 0 {
|
||||
return nil, errors.New("no table loaded")
|
||||
}
|
||||
var br bitReaderShifted
|
||||
err := br.init(src)
|
||||
if err != nil {
|
||||
return dst, err
|
||||
}
|
||||
maxDecodedSize := cap(dst)
|
||||
dst = dst[:maxDecodedSize]
|
||||
|
||||
const tlSize = 1 << tableLogMax
|
||||
const tlMask = tlSize - 1
|
||||
|
||||
if maxDecodedSize >= 4 {
|
||||
ctx := decompress1xContext{
|
||||
pbr: &br,
|
||||
out: &dst[0],
|
||||
outCap: maxDecodedSize,
|
||||
peekBits: uint8((64 - d.actualTableLog) & 63), // see: bitReaderShifted.peekBitsFast()
|
||||
tbl: &d.dt.single[0],
|
||||
}
|
||||
|
||||
decompress1x_main_loop_asm(&ctx)
|
||||
if ctx.decoded == error_max_decoded_size_exeeded {
|
||||
return nil, ErrMaxDecodedSizeExceeded
|
||||
}
|
||||
|
||||
dst = dst[:ctx.decoded]
|
||||
}
|
||||
|
||||
// br < 8, so uint8 is fine
|
||||
bitsLeft := uint8(br.off)*8 + 64 - br.bitsRead
|
||||
for bitsLeft > 0 {
|
||||
br.fill()
|
||||
if len(dst) >= maxDecodedSize {
|
||||
br.close()
|
||||
return nil, ErrMaxDecodedSizeExceeded
|
||||
}
|
||||
v := d.dt.single[br.peekBitsFast(d.actualTableLog)&tlMask]
|
||||
nBits := uint8(v.entry)
|
||||
br.advance(nBits)
|
||||
bitsLeft -= nBits
|
||||
dst = append(dst, uint8(v.entry>>8))
|
||||
}
|
||||
return dst, br.close()
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
//go:build !amd64 || appengine || !gc || noasm
|
||||
//go:build (!amd64 && !arm64) || appengine || !gc || noasm
|
||||
|
||||
// This file contains a generic implementation of Decoder.Decompress4X.
|
||||
package huff0
|
||||
|
||||
+3
-6
@@ -400,8 +400,9 @@ func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err
|
||||
}
|
||||
}
|
||||
var err error
|
||||
// Use our out buffer.
|
||||
huff.MaxDecodedSize = litRegenSize
|
||||
// Decoder.Decompress* uses cap(dst) for the size limit. Do not write
|
||||
// MaxDecodedSize on hist.huffTree: with a trained dictionary that
|
||||
// pointer aliases the shared dict.litEnc and concurrent DecodeAll races.
|
||||
if fourStreams {
|
||||
literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals)
|
||||
} else {
|
||||
@@ -673,10 +674,6 @@ func (b *blockDec) executeSequences(hist *history) error {
|
||||
hbytes := hist.b
|
||||
if len(hbytes) > hist.windowSize {
|
||||
hbytes = hbytes[len(hbytes)-hist.windowSize:]
|
||||
// We do not need history anymore.
|
||||
if hist.dict != nil {
|
||||
hist.dict.content = nil
|
||||
}
|
||||
}
|
||||
hist.decoders.windowSize = hist.windowSize
|
||||
hist.decoders.out = b.dst[:0]
|
||||
|
||||
+64
-21
@@ -296,40 +296,81 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
|
||||
if offset > 3 {
|
||||
newOffsets[offset-3]++
|
||||
} else {
|
||||
newOffsets[uint32(o.Offsets[offset-1])]++
|
||||
// Repeat codes reference the training Offsets. Skip unset
|
||||
// (zero) entries so they are not ranked as real offsets.
|
||||
prev := o.Offsets[offset-1]
|
||||
if prev > 0 {
|
||||
newOffsets[uint32(prev)]++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Find most used offsets.
|
||||
var sortedOffsets []uint32
|
||||
for k := range newOffsets {
|
||||
if k == 0 {
|
||||
continue
|
||||
}
|
||||
sortedOffsets = append(sortedOffsets, k)
|
||||
}
|
||||
sort.Slice(sortedOffsets, func(i, j int) bool {
|
||||
a, b := sortedOffsets[i], sortedOffsets[j]
|
||||
if a == b {
|
||||
ca, cb := newOffsets[a], newOffsets[b]
|
||||
if ca == cb {
|
||||
// Prefer the longer offset
|
||||
return sortedOffsets[i] > sortedOffsets[j]
|
||||
return a > b
|
||||
}
|
||||
return newOffsets[sortedOffsets[i]] > newOffsets[sortedOffsets[j]]
|
||||
return ca > cb
|
||||
})
|
||||
if len(sortedOffsets) > 3 {
|
||||
if debug {
|
||||
print("Offsets:")
|
||||
for i, v := range sortedOffsets {
|
||||
if i > 20 {
|
||||
break
|
||||
}
|
||||
printf("[%d: %d],", v, newOffsets[v])
|
||||
if debug {
|
||||
print("Offsets:")
|
||||
for i, v := range sortedOffsets {
|
||||
if i > 20 {
|
||||
break
|
||||
}
|
||||
println("")
|
||||
printf("[%d: %d],", v, newOffsets[v])
|
||||
}
|
||||
|
||||
sortedOffsets = sortedOffsets[:3]
|
||||
println("")
|
||||
}
|
||||
for i, v := range sortedOffsets {
|
||||
o.Offsets[i] = int(v)
|
||||
// Dictionary recent-offsets must be three positive values within the
|
||||
// history. Ranked matches may be fewer (or empty when only unset
|
||||
// repeat codes were seen), so fill remaining slots with defaults.
|
||||
used := make(map[int]bool, 3)
|
||||
var finalOffsets [3]int
|
||||
nOff := 0
|
||||
for _, v := range sortedOffsets {
|
||||
iv := int(v)
|
||||
if iv <= 0 || iv > len(hist) || used[iv] {
|
||||
continue
|
||||
}
|
||||
finalOffsets[nOff] = iv
|
||||
used[iv] = true
|
||||
nOff++
|
||||
if nOff == 3 {
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, def := range []int{1, 4, 8} {
|
||||
if nOff == 3 {
|
||||
break
|
||||
}
|
||||
if def <= len(hist) && !used[def] {
|
||||
finalOffsets[nOff] = def
|
||||
used[def] = true
|
||||
nOff++
|
||||
}
|
||||
}
|
||||
for def := 1; nOff < 3 && def <= len(hist); def++ {
|
||||
if !used[def] {
|
||||
finalOffsets[nOff] = def
|
||||
used[def] = true
|
||||
nOff++
|
||||
}
|
||||
}
|
||||
if nOff < 3 {
|
||||
return nil, fmt.Errorf("could not determine 3 valid dictionary offsets (history size %d)", len(hist))
|
||||
}
|
||||
o.Offsets = finalOffsets
|
||||
if debug {
|
||||
println("New repeat offsets", o.Offsets)
|
||||
}
|
||||
@@ -337,6 +378,9 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
|
||||
if nUsed == 0 || seqs == 0 {
|
||||
return nil, fmt.Errorf("%d blocks, %d sequences found", nUsed, seqs)
|
||||
}
|
||||
if litTotal == 0 {
|
||||
return nil, errors.New("0 literals found")
|
||||
}
|
||||
if debug {
|
||||
println("Sequences:", seqs, "Blocks:", nUsed, "Literals:", litTotal)
|
||||
}
|
||||
@@ -517,11 +561,10 @@ func BuildDict(o BuildDictOptions) ([]byte, error) {
|
||||
out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[1])))
|
||||
out.Write(binary.LittleEndian.AppendUint32(nil, uint32(o.Offsets[2])))
|
||||
out.Write(hist)
|
||||
if _, err := loadDict(out.Bytes()); err != nil {
|
||||
return nil, fmt.Errorf("built dictionary failed validation: %w", err)
|
||||
}
|
||||
if debug {
|
||||
_, err := loadDict(out.Bytes())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
i, err := InspectDictionary(out.Bytes())
|
||||
if err != nil {
|
||||
panic(err)
|
||||
|
||||
+2
-2
@@ -2081,7 +2081,7 @@ sequenceDecs_decodeSync_amd64_match_len_ofs_ok:
|
||||
MOVQ 16(SP), R13
|
||||
|
||||
// Check if we have enough space in s.out
|
||||
LEAQ (AX)(R13*1), R14
|
||||
LEAQ 16(AX)(R13*1), R14
|
||||
ADDQ R10, R14
|
||||
CMPQ R14, 32(SP)
|
||||
JA error_not_enough_space
|
||||
@@ -2601,7 +2601,7 @@ sequenceDecs_decodeSync_bmi2_match_len_ofs_ok:
|
||||
MOVQ 16(SP), R13
|
||||
|
||||
// Check if we have enough space in s.out
|
||||
LEAQ (CX)(R13*1), R14
|
||||
LEAQ 16(CX)(R13*1), R14
|
||||
ADDQ R9, R14
|
||||
CMPQ R14, 32(SP)
|
||||
JA error_not_enough_space
|
||||
|
||||
+323
-278
File diff suppressed because it is too large.
Load diff
+30
-3
@@ -77,6 +77,35 @@ const errorNotEnoughSpace = 5
|
||||
// error reported when bits are overread.
|
||||
const errorOverread = 6
|
||||
|
||||
// useSafeDecodeSync reports whether decodeSyncSimple must use the bounds-exact
|
||||
// ("safe") copy variants for the current buffer geometry.
|
||||
//
|
||||
// When the output and literal buffers have compressedBlockOverAlloc (16)
|
||||
// bytes of slack past their logical use, the assembly may use extended
|
||||
// memory copies that read and write in 16-byte blocks, overrunning the end
|
||||
// of a literal run or match by up to 15 bytes. Otherwise it must use the
|
||||
// bounds-exact ("safe") copies. This mirrors the analogous, always-dynamic
|
||||
// selection in executeSimple below.
|
||||
//
|
||||
// The unsafe copies were disabled in #644 (2022) as a mitigation for a
|
||||
// crash, but that crash's root cause — an unguarded bitReader overread that
|
||||
// produced out-of-range match offsets/lengths — was fixed three days later
|
||||
// in #645, which also added the fuzz corpus that has guarded this path since.
|
||||
// See #1168. An asan-instrumented fuzz job (see .github/workflows/go.yml)
|
||||
// covers the extended-copy path, which -race and plain fuzzing cannot.
|
||||
func (s *sequenceDecs) useSafeDecodeSync() bool {
|
||||
if s.maxSyncLen == 0 && cap(s.out)-len(s.out) < maxCompressedBlockSizeAlloc {
|
||||
return true
|
||||
}
|
||||
if s.maxSyncLen > 0 && cap(s.out)-len(s.out)-compressedBlockOverAlloc < int(s.maxSyncLen) {
|
||||
return true
|
||||
}
|
||||
if cap(s.literals) < len(s.literals)+compressedBlockOverAlloc {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// decode sequences from the stream with the provided history but without a dictionary.
|
||||
func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) {
|
||||
if len(s.dict) > 0 {
|
||||
@@ -86,9 +115,7 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// FIXME: Using unsafe memory copies leads to rare, random crashes
|
||||
// with fuzz testing. It is therefore disabled for now.
|
||||
const useSafe = true
|
||||
useSafe := s.useSafeDecodeSync()
|
||||
|
||||
br := s.br
|
||||
|
||||
|
||||
Generated
-24
@@ -1,24 +0,0 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
*.prof
|
||||
-10
@@ -1,10 +0,0 @@
|
||||
language: go
|
||||
go_import_path: github.com/pkg/errors
|
||||
go:
|
||||
- 1.11.x
|
||||
- 1.12.x
|
||||
- 1.13.x
|
||||
- tip
|
||||
|
||||
script:
|
||||
- make check
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
PKGS := github.com/pkg/errors
|
||||
SRCDIRS := $(shell go list -f '{{.Dir}}' $(PKGS))
|
||||
GO := go
|
||||
|
||||
check: test vet gofmt misspell unconvert staticcheck ineffassign unparam
|
||||
|
||||
test:
|
||||
$(GO) test $(PKGS)
|
||||
|
||||
vet: | test
|
||||
$(GO) vet $(PKGS)
|
||||
|
||||
staticcheck:
|
||||
$(GO) get honnef.co/go/tools/cmd/staticcheck
|
||||
staticcheck -checks all $(PKGS)
|
||||
|
||||
misspell:
|
||||
$(GO) get github.com/client9/misspell/cmd/misspell
|
||||
misspell \
|
||||
-locale GB \
|
||||
-error \
|
||||
*.md *.go
|
||||
|
||||
unconvert:
|
||||
$(GO) get github.com/mdempsky/unconvert
|
||||
unconvert -v $(PKGS)
|
||||
|
||||
ineffassign:
|
||||
$(GO) get github.com/gordonklaus/ineffassign
|
||||
find $(SRCDIRS) -name '*.go' | xargs ineffassign
|
||||
|
||||
pedantic: check errcheck
|
||||
|
||||
unparam:
|
||||
$(GO) get mvdan.cc/unparam
|
||||
unparam ./...
|
||||
|
||||
errcheck:
|
||||
$(GO) get github.com/kisielk/errcheck
|
||||
errcheck $(PKGS)
|
||||
|
||||
gofmt:
|
||||
@echo Checking code is gofmted
|
||||
@test -z "$(shell gofmt -s -l -d -e $(SRCDIRS) | tee /dev/stderr)"
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
# errors [](https://travis-ci.org/pkg/errors) [](https://ci.appveyor.com/project/davecheney/errors/branch/master) [](http://godoc.org/github.com/pkg/errors) [](https://goreportcard.com/report/github.com/pkg/errors) [](https://sourcegraph.com/github.com/pkg/errors?badge)
|
||||
|
||||
Package errors provides simple error handling primitives.
|
||||
|
||||
`go get github.com/pkg/errors`
|
||||
|
||||
The traditional error handling idiom in Go is roughly akin to
|
||||
```go
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
```
|
||||
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
|
||||
|
||||
## Adding context to an error
|
||||
|
||||
The errors.Wrap function returns a new error that adds context to the original error. For example
|
||||
```go
|
||||
_, err := ioutil.ReadAll(r)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "read failed")
|
||||
}
|
||||
```
|
||||
## Retrieving the cause of an error
|
||||
|
||||
Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`.
|
||||
```go
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
```
|
||||
`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example:
|
||||
```go
|
||||
switch err := errors.Cause(err).(type) {
|
||||
case *MyError:
|
||||
// handle specifically
|
||||
default:
|
||||
// unknown error
|
||||
}
|
||||
```
|
||||
|
||||
[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors).
|
||||
|
||||
## Roadmap
|
||||
|
||||
With the upcoming [Go2 error proposals](https://go.googlesource.com/proposal/+/master/design/go2draft.md) this package is moving into maintenance mode. The roadmap for a 1.0 release is as follows:
|
||||
|
||||
- 0.9. Remove pre Go 1.9 and Go 1.10 support, address outstanding pull requests (if possible)
|
||||
- 1.0. Final release.
|
||||
|
||||
## Contributing
|
||||
|
||||
Because of the Go2 errors changes, this package is not accepting proposals for new functionality. With that said, we welcome pull requests, bug fixes and issue reports.
|
||||
|
||||
Before sending a PR, please discuss your change by raising an issue.
|
||||
|
||||
## License
|
||||
|
||||
BSD-2-Clause
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
version: build-{build}.{branch}
|
||||
|
||||
clone_folder: C:\gopath\src\github.com\pkg\errors
|
||||
shallow_clone: true # for startup speed
|
||||
|
||||
environment:
|
||||
GOPATH: C:\gopath
|
||||
|
||||
platform:
|
||||
- x64
|
||||
|
||||
# http://www.appveyor.com/docs/installed-software
|
||||
install:
|
||||
# some helpful output for debugging builds
|
||||
- go version
|
||||
- go env
|
||||
# pre-installed MinGW at C:\MinGW is 32bit only
|
||||
# but MSYS2 at C:\msys64 has mingw64
|
||||
- set PATH=C:\msys64\mingw64\bin;%PATH%
|
||||
- gcc --version
|
||||
- g++ --version
|
||||
|
||||
build_script:
|
||||
- go install -v ./...
|
||||
|
||||
test_script:
|
||||
- set PATH=C:\gopath\bin;%PATH%
|
||||
- go test -v ./...
|
||||
|
||||
#artifacts:
|
||||
# - path: '%GOPATH%\bin\*.exe'
|
||||
deploy: off
|
||||
-288
@@ -1,288 +0,0 @@
|
||||
// Package errors provides simple error handling primitives.
|
||||
//
|
||||
// The traditional error handling idiom in Go is roughly akin to
|
||||
//
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
//
|
||||
// which when applied recursively up the call stack results in error reports
|
||||
// without context or debugging information. The errors package allows
|
||||
// programmers to add context to the failure path in their code in a way
|
||||
// that does not destroy the original value of the error.
|
||||
//
|
||||
// Adding context to an error
|
||||
//
|
||||
// The errors.Wrap function returns a new error that adds context to the
|
||||
// original error by recording a stack trace at the point Wrap is called,
|
||||
// together with the supplied message. For example
|
||||
//
|
||||
// _, err := ioutil.ReadAll(r)
|
||||
// if err != nil {
|
||||
// return errors.Wrap(err, "read failed")
|
||||
// }
|
||||
//
|
||||
// If additional control is required, the errors.WithStack and
|
||||
// errors.WithMessage functions destructure errors.Wrap into its component
|
||||
// operations: annotating an error with a stack trace and with a message,
|
||||
// respectively.
|
||||
//
|
||||
// Retrieving the cause of an error
|
||||
//
|
||||
// Using errors.Wrap constructs a stack of errors, adding context to the
|
||||
// preceding error. Depending on the nature of the error it may be necessary
|
||||
// to reverse the operation of errors.Wrap to retrieve the original error
|
||||
// for inspection. Any error value which implements this interface
|
||||
//
|
||||
// type causer interface {
|
||||
// Cause() error
|
||||
// }
|
||||
//
|
||||
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
|
||||
// the topmost error that does not implement causer, which is assumed to be
|
||||
// the original cause. For example:
|
||||
//
|
||||
// switch err := errors.Cause(err).(type) {
|
||||
// case *MyError:
|
||||
// // handle specifically
|
||||
// default:
|
||||
// // unknown error
|
||||
// }
|
||||
//
|
||||
// Although the causer interface is not exported by this package, it is
|
||||
// considered a part of its stable public interface.
|
||||
//
|
||||
// Formatted printing of errors
|
||||
//
|
||||
// All error values returned from this package implement fmt.Formatter and can
|
||||
// be formatted by the fmt package. The following verbs are supported:
|
||||
//
|
||||
// %s print the error. If the error has a Cause it will be
|
||||
// printed recursively.
|
||||
// %v see %s
|
||||
// %+v extended format. Each Frame of the error's StackTrace will
|
||||
// be printed in detail.
|
||||
//
|
||||
// Retrieving the stack trace of an error or wrapper
|
||||
//
|
||||
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
|
||||
// invoked. This information can be retrieved with the following interface:
|
||||
//
|
||||
// type stackTracer interface {
|
||||
// StackTrace() errors.StackTrace
|
||||
// }
|
||||
//
|
||||
// The returned errors.StackTrace type is defined as
|
||||
//
|
||||
// type StackTrace []Frame
|
||||
//
|
||||
// The Frame type represents a call site in the stack trace. Frame supports
|
||||
// the fmt.Formatter interface that can be used for printing information about
|
||||
// the stack trace of this error. For example:
|
||||
//
|
||||
// if err, ok := err.(stackTracer); ok {
|
||||
// for _, f := range err.StackTrace() {
|
||||
// fmt.Printf("%+s:%d\n", f, f)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Although the stackTracer interface is not exported by this package, it is
|
||||
// considered a part of its stable public interface.
|
||||
//
|
||||
// See the documentation for Frame.Format for more details.
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// New returns an error with the supplied message.
|
||||
// New also records the stack trace at the point it was called.
|
||||
func New(message string) error {
|
||||
return &fundamental{
|
||||
msg: message,
|
||||
stack: callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// Errorf formats according to a format specifier and returns the string
|
||||
// as a value that satisfies error.
|
||||
// Errorf also records the stack trace at the point it was called.
|
||||
func Errorf(format string, args ...interface{}) error {
|
||||
return &fundamental{
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
stack: callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// fundamental is an error that has a message and a stack, but no caller.
|
||||
type fundamental struct {
|
||||
msg string
|
||||
*stack
|
||||
}
|
||||
|
||||
func (f *fundamental) Error() string { return f.msg }
|
||||
|
||||
func (f *fundamental) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
io.WriteString(s, f.msg)
|
||||
f.stack.Format(s, verb)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's':
|
||||
io.WriteString(s, f.msg)
|
||||
case 'q':
|
||||
fmt.Fprintf(s, "%q", f.msg)
|
||||
}
|
||||
}
|
||||
|
||||
// WithStack annotates err with a stack trace at the point WithStack was called.
|
||||
// If err is nil, WithStack returns nil.
|
||||
func WithStack(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
type withStack struct {
|
||||
error
|
||||
*stack
|
||||
}
|
||||
|
||||
func (w *withStack) Cause() error { return w.error }
|
||||
|
||||
// Unwrap provides compatibility for Go 1.13 error chains.
|
||||
func (w *withStack) Unwrap() error { return w.error }
|
||||
|
||||
func (w *withStack) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
fmt.Fprintf(s, "%+v", w.Cause())
|
||||
w.stack.Format(s, verb)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's':
|
||||
io.WriteString(s, w.Error())
|
||||
case 'q':
|
||||
fmt.Fprintf(s, "%q", w.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Wrap returns an error annotating err with a stack trace
|
||||
// at the point Wrap is called, and the supplied message.
|
||||
// If err is nil, Wrap returns nil.
|
||||
func Wrap(err error, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: message,
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapf returns an error annotating err with a stack trace
|
||||
// at the point Wrapf is called, and the format specifier.
|
||||
// If err is nil, Wrapf returns nil.
|
||||
func Wrapf(err error, format string, args ...interface{}) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
err = &withMessage{
|
||||
cause: err,
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
}
|
||||
return &withStack{
|
||||
err,
|
||||
callers(),
|
||||
}
|
||||
}
|
||||
|
||||
// WithMessage annotates err with a new message.
|
||||
// If err is nil, WithMessage returns nil.
|
||||
func WithMessage(err error, message string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withMessage{
|
||||
cause: err,
|
||||
msg: message,
|
||||
}
|
||||
}
|
||||
|
||||
// WithMessagef annotates err with the format specifier.
|
||||
// If err is nil, WithMessagef returns nil.
|
||||
func WithMessagef(err error, format string, args ...interface{}) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return &withMessage{
|
||||
cause: err,
|
||||
msg: fmt.Sprintf(format, args...),
|
||||
}
|
||||
}
|
||||
|
||||
type withMessage struct {
|
||||
cause error
|
||||
msg string
|
||||
}
|
||||
|
||||
func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
|
||||
func (w *withMessage) Cause() error { return w.cause }
|
||||
|
||||
// Unwrap provides compatibility for Go 1.13 error chains.
|
||||
func (w *withMessage) Unwrap() error { return w.cause }
|
||||
|
||||
func (w *withMessage) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
if s.Flag('+') {
|
||||
fmt.Fprintf(s, "%+v\n", w.Cause())
|
||||
io.WriteString(s, w.msg)
|
||||
return
|
||||
}
|
||||
fallthrough
|
||||
case 's', 'q':
|
||||
io.WriteString(s, w.Error())
|
||||
}
|
||||
}
|
||||
|
||||
// Cause returns the underlying cause of the error, if possible.
|
||||
// An error value has a cause if it implements the following
|
||||
// interface:
|
||||
//
|
||||
// type causer interface {
|
||||
// Cause() error
|
||||
// }
|
||||
//
|
||||
// If the error does not implement Cause, the original error will
|
||||
// be returned. If the error is nil, nil will be returned without further
|
||||
// investigation.
|
||||
func Cause(err error) error {
|
||||
type causer interface {
|
||||
Cause() error
|
||||
}
|
||||
|
||||
for err != nil {
|
||||
cause, ok := err.(causer)
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
err = cause.Cause()
|
||||
}
|
||||
return err
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
// +build go1.13
|
||||
|
||||
package errors
|
||||
|
||||
import (
|
||||
stderrors "errors"
|
||||
)
|
||||
|
||||
// Is reports whether any error in err's chain matches target.
|
||||
//
|
||||
// The chain consists of err itself followed by the sequence of errors obtained by
|
||||
// repeatedly calling Unwrap.
|
||||
//
|
||||
// An error is considered to match a target if it is equal to that target or if
|
||||
// it implements a method Is(error) bool such that Is(target) returns true.
|
||||
func Is(err, target error) bool { return stderrors.Is(err, target) }
|
||||
|
||||
// As finds the first error in err's chain that matches target, and if so, sets
|
||||
// target to that error value and returns true.
|
||||
//
|
||||
// The chain consists of err itself followed by the sequence of errors obtained by
|
||||
// repeatedly calling Unwrap.
|
||||
//
|
||||
// An error matches target if the error's concrete value is assignable to the value
|
||||
// pointed to by target, or if the error has a method As(interface{}) bool such that
|
||||
// As(target) returns true. In the latter case, the As method is responsible for
|
||||
// setting target.
|
||||
//
|
||||
// As will panic if target is not a non-nil pointer to either a type that implements
|
||||
// error, or to any interface type. As returns false if err is nil.
|
||||
func As(err error, target interface{}) bool { return stderrors.As(err, target) }
|
||||
|
||||
// Unwrap returns the result of calling the Unwrap method on err, if err's
|
||||
// type contains an Unwrap method returning error.
|
||||
// Otherwise, Unwrap returns nil.
|
||||
func Unwrap(err error) error {
|
||||
return stderrors.Unwrap(err)
|
||||
}
|
||||
-177
@@ -1,177 +0,0 @@
|
||||
package errors
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Frame represents a program counter inside a stack frame.
|
||||
// For historical reasons if Frame is interpreted as a uintptr
|
||||
// its value represents the program counter + 1.
|
||||
type Frame uintptr
|
||||
|
||||
// pc returns the program counter for this frame;
|
||||
// multiple frames may have the same PC value.
|
||||
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
|
||||
|
||||
// file returns the full path to the file that contains the
|
||||
// function for this Frame's pc.
|
||||
func (f Frame) file() string {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return "unknown"
|
||||
}
|
||||
file, _ := fn.FileLine(f.pc())
|
||||
return file
|
||||
}
|
||||
|
||||
// line returns the line number of source code of the
|
||||
// function for this Frame's pc.
|
||||
func (f Frame) line() int {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return 0
|
||||
}
|
||||
_, line := fn.FileLine(f.pc())
|
||||
return line
|
||||
}
|
||||
|
||||
// name returns the name of this function, if known.
|
||||
func (f Frame) name() string {
|
||||
fn := runtime.FuncForPC(f.pc())
|
||||
if fn == nil {
|
||||
return "unknown"
|
||||
}
|
||||
return fn.Name()
|
||||
}
|
||||
|
||||
// Format formats the frame according to the fmt.Formatter interface.
|
||||
//
|
||||
// %s source file
|
||||
// %d source line
|
||||
// %n function name
|
||||
// %v equivalent to %s:%d
|
||||
//
|
||||
// Format accepts flags that alter the printing of some verbs, as follows:
|
||||
//
|
||||
// %+s function name and path of source file relative to the compile time
|
||||
// GOPATH separated by \n\t (<funcname>\n\t<path>)
|
||||
// %+v equivalent to %+s:%d
|
||||
func (f Frame) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 's':
|
||||
switch {
|
||||
case s.Flag('+'):
|
||||
io.WriteString(s, f.name())
|
||||
io.WriteString(s, "\n\t")
|
||||
io.WriteString(s, f.file())
|
||||
default:
|
||||
io.WriteString(s, path.Base(f.file()))
|
||||
}
|
||||
case 'd':
|
||||
io.WriteString(s, strconv.Itoa(f.line()))
|
||||
case 'n':
|
||||
io.WriteString(s, funcname(f.name()))
|
||||
case 'v':
|
||||
f.Format(s, 's')
|
||||
io.WriteString(s, ":")
|
||||
f.Format(s, 'd')
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText formats a stacktrace Frame as a text string. The output is the
|
||||
// same as that of fmt.Sprintf("%+v", f), but without newlines or tabs.
|
||||
func (f Frame) MarshalText() ([]byte, error) {
|
||||
name := f.name()
|
||||
if name == "unknown" {
|
||||
return []byte(name), nil
|
||||
}
|
||||
return []byte(fmt.Sprintf("%s %s:%d", name, f.file(), f.line())), nil
|
||||
}
|
||||
|
||||
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
|
||||
type StackTrace []Frame
|
||||
|
||||
// Format formats the stack of Frames according to the fmt.Formatter interface.
|
||||
//
|
||||
// %s lists source files for each Frame in the stack
|
||||
// %v lists the source file and line number for each Frame in the stack
|
||||
//
|
||||
// Format accepts flags that alter the printing of some verbs, as follows:
|
||||
//
|
||||
// %+v Prints filename, function, and line number for each Frame in the stack.
|
||||
func (st StackTrace) Format(s fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
switch {
|
||||
case s.Flag('+'):
|
||||
for _, f := range st {
|
||||
io.WriteString(s, "\n")
|
||||
f.Format(s, verb)
|
||||
}
|
||||
case s.Flag('#'):
|
||||
fmt.Fprintf(s, "%#v", []Frame(st))
|
||||
default:
|
||||
st.formatSlice(s, verb)
|
||||
}
|
||||
case 's':
|
||||
st.formatSlice(s, verb)
|
||||
}
|
||||
}
|
||||
|
||||
// formatSlice will format this StackTrace into the given buffer as a slice of
|
||||
// Frame, only valid when called with '%s' or '%v'.
|
||||
func (st StackTrace) formatSlice(s fmt.State, verb rune) {
|
||||
io.WriteString(s, "[")
|
||||
for i, f := range st {
|
||||
if i > 0 {
|
||||
io.WriteString(s, " ")
|
||||
}
|
||||
f.Format(s, verb)
|
||||
}
|
||||
io.WriteString(s, "]")
|
||||
}
|
||||
|
||||
// stack represents a stack of program counters.
|
||||
type stack []uintptr
|
||||
|
||||
func (s *stack) Format(st fmt.State, verb rune) {
|
||||
switch verb {
|
||||
case 'v':
|
||||
switch {
|
||||
case st.Flag('+'):
|
||||
for _, pc := range *s {
|
||||
f := Frame(pc)
|
||||
fmt.Fprintf(st, "\n%+v", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stack) StackTrace() StackTrace {
|
||||
f := make([]Frame, len(*s))
|
||||
for i := 0; i < len(f); i++ {
|
||||
f[i] = Frame((*s)[i])
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func callers() *stack {
|
||||
const depth = 32
|
||||
var pcs [depth]uintptr
|
||||
n := runtime.Callers(3, pcs[:])
|
||||
var st stack = pcs[0:n]
|
||||
return &st
|
||||
}
|
||||
|
||||
// funcname removes the path prefix component of a function's name reported by func.Name().
|
||||
func funcname(name string) string {
|
||||
i := strings.LastIndex(name, "/")
|
||||
name = name[i+1:]
|
||||
i = strings.Index(name, ".")
|
||||
return name[i+1:]
|
||||
}
|
||||
+20
-8
@@ -84,7 +84,7 @@ func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, ar
|
||||
return Equal(t, expected, actual, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
|
||||
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
|
||||
// and that it is equal to the provided error.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
@@ -124,7 +124,7 @@ func EqualValuesf(t TestingT, expected interface{}, actual interface{}, msg stri
|
||||
return EqualValues(t, expected, actual, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// Errorf asserts that a function returned an error (i.e. not `nil`).
|
||||
// Errorf asserts that a function returned a non-nil error (ie. an error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// assert.Errorf(t, err, "error message %s", "formatted")
|
||||
@@ -144,8 +144,8 @@ func ErrorAsf(t TestingT, err error, target interface{}, msg string, args ...int
|
||||
return ErrorAs(t, err, target, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
|
||||
// and that the error contains the specified substring.
|
||||
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
|
||||
// error) and that the error contains the specified substring.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// assert.ErrorContainsf(t, err, expectedErrorSubString, "error message %s", "formatted")
|
||||
@@ -190,10 +190,10 @@ func Eventuallyf(t TestingT, condition func() bool, waitFor time.Duration, tick
|
||||
// time.Sleep(8*time.Second)
|
||||
// externalValue = true
|
||||
// }()
|
||||
// assert.EventuallyWithTf(t, func(c *assert.CollectT, "error message %s", "formatted") {
|
||||
// assert.EventuallyWithTf(t, func(c *assert.CollectT) {
|
||||
// // add assertions as needed; any assertion failure will fail the current tick
|
||||
// assert.True(c, externalValue, "expected 'externalValue' to be true")
|
||||
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
|
||||
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
|
||||
func EventuallyWithTf(t TestingT, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
@@ -552,7 +552,7 @@ func NoDirExistsf(t TestingT, path string, msg string, args ...interface{}) bool
|
||||
return NoDirExists(t, path, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// NoErrorf asserts that a function returned no error (i.e. `nil`).
|
||||
// NoErrorf asserts that a function returned a nil error (ie. no error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if assert.NoErrorf(t, err, "error message %s", "formatted") {
|
||||
@@ -849,7 +849,19 @@ func WithinRangef(t TestingT, actual time.Time, start time.Time, end time.Time,
|
||||
return WithinRange(t, actual, start, end, append([]interface{}{msg}, args...)...)
|
||||
}
|
||||
|
||||
// YAMLEqf asserts that two YAML strings are equivalent.
|
||||
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
|
||||
//
|
||||
// expected := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a second document, it is not evaluated
|
||||
// `
|
||||
// actual := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a subsequent document, it is not evaluated
|
||||
// `
|
||||
// assert.YAMLEqf(t, expected, actual, "error message %s", "formatted")
|
||||
func YAMLEqf(t TestingT, expected string, actual string, msg string, args ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
|
||||
+38
-14
@@ -146,7 +146,7 @@ func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs
|
||||
return Equal(a.t, expected, actual, msgAndArgs...)
|
||||
}
|
||||
|
||||
// EqualError asserts that a function returned an error (i.e. not `nil`)
|
||||
// EqualError asserts that a function returned a non-nil error (i.e. an error)
|
||||
// and that it is equal to the provided error.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
@@ -158,7 +158,7 @@ func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...
|
||||
return EqualError(a.t, theError, errString, msgAndArgs...)
|
||||
}
|
||||
|
||||
// EqualErrorf asserts that a function returned an error (i.e. not `nil`)
|
||||
// EqualErrorf asserts that a function returned a non-nil error (i.e. an error)
|
||||
// and that it is equal to the provided error.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
@@ -240,7 +240,7 @@ func (a *Assertions) Equalf(expected interface{}, actual interface{}, msg string
|
||||
return Equalf(a.t, expected, actual, msg, args...)
|
||||
}
|
||||
|
||||
// Error asserts that a function returned an error (i.e. not `nil`).
|
||||
// Error asserts that a function returned a non-nil error (ie. an error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// a.Error(err)
|
||||
@@ -269,8 +269,8 @@ func (a *Assertions) ErrorAsf(err error, target interface{}, msg string, args ..
|
||||
return ErrorAsf(a.t, err, target, msg, args...)
|
||||
}
|
||||
|
||||
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
|
||||
// and that the error contains the specified substring.
|
||||
// ErrorContains asserts that a function returned a non-nil error (i.e. an
|
||||
// error) and that the error contains the specified substring.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// a.ErrorContains(err, expectedErrorSubString)
|
||||
@@ -281,8 +281,8 @@ func (a *Assertions) ErrorContains(theError error, contains string, msgAndArgs .
|
||||
return ErrorContains(a.t, theError, contains, msgAndArgs...)
|
||||
}
|
||||
|
||||
// ErrorContainsf asserts that a function returned an error (i.e. not `nil`)
|
||||
// and that the error contains the specified substring.
|
||||
// ErrorContainsf asserts that a function returned a non-nil error (i.e. an
|
||||
// error) and that the error contains the specified substring.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// a.ErrorContainsf(err, expectedErrorSubString, "error message %s", "formatted")
|
||||
@@ -311,7 +311,7 @@ func (a *Assertions) ErrorIsf(err error, target error, msg string, args ...inter
|
||||
return ErrorIsf(a.t, err, target, msg, args...)
|
||||
}
|
||||
|
||||
// Errorf asserts that a function returned an error (i.e. not `nil`).
|
||||
// Errorf asserts that a function returned a non-nil error (ie. an error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// a.Errorf(err, "error message %s", "formatted")
|
||||
@@ -372,10 +372,10 @@ func (a *Assertions) EventuallyWithT(condition func(collect *CollectT), waitFor
|
||||
// time.Sleep(8*time.Second)
|
||||
// externalValue = true
|
||||
// }()
|
||||
// a.EventuallyWithTf(func(c *assert.CollectT, "error message %s", "formatted") {
|
||||
// a.EventuallyWithTf(func(c *assert.CollectT) {
|
||||
// // add assertions as needed; any assertion failure will fail the current tick
|
||||
// assert.True(c, externalValue, "expected 'externalValue' to be true")
|
||||
// }, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")
|
||||
// }, 10*time.Second, 1*time.Second, "error message %s", "formatted")
|
||||
func (a *Assertions) EventuallyWithTf(condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msg string, args ...interface{}) bool {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
@@ -1096,7 +1096,7 @@ func (a *Assertions) NoDirExistsf(path string, msg string, args ...interface{})
|
||||
return NoDirExistsf(a.t, path, msg, args...)
|
||||
}
|
||||
|
||||
// NoError asserts that a function returned no error (i.e. `nil`).
|
||||
// NoError asserts that a function returned a nil error (ie. no error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if a.NoError(err) {
|
||||
@@ -1109,7 +1109,7 @@ func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool {
|
||||
return NoError(a.t, err, msgAndArgs...)
|
||||
}
|
||||
|
||||
// NoErrorf asserts that a function returned no error (i.e. `nil`).
|
||||
// NoErrorf asserts that a function returned a nil error (ie. no error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if a.NoErrorf(err, "error message %s", "formatted") {
|
||||
@@ -1690,7 +1690,19 @@ func (a *Assertions) WithinRangef(actual time.Time, start time.Time, end time.Ti
|
||||
return WithinRangef(a.t, actual, start, end, msg, args...)
|
||||
}
|
||||
|
||||
// YAMLEq asserts that two YAML strings are equivalent.
|
||||
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
|
||||
//
|
||||
// expected := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a second document, it is not evaluated
|
||||
// `
|
||||
// actual := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a subsequent document, it is not evaluated
|
||||
// `
|
||||
// a.YAMLEq(expected, actual)
|
||||
func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
@@ -1698,7 +1710,19 @@ func (a *Assertions) YAMLEq(expected string, actual string, msgAndArgs ...interf
|
||||
return YAMLEq(a.t, expected, actual, msgAndArgs...)
|
||||
}
|
||||
|
||||
// YAMLEqf asserts that two YAML strings are equivalent.
|
||||
// YAMLEqf asserts that the first documents in the two YAML strings are equivalent.
|
||||
//
|
||||
// expected := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a second document, it is not evaluated
|
||||
// `
|
||||
// actual := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a subsequent document, it is not evaluated
|
||||
// `
|
||||
// a.YAMLEqf(expected, actual, "error message %s", "formatted")
|
||||
func (a *Assertions) YAMLEqf(expected string, actual string, msg string, args ...interface{}) bool {
|
||||
if h, ok := a.t.(tHelper); ok {
|
||||
h.Helper()
|
||||
|
||||
+13
-1
@@ -9,7 +9,7 @@ import (
|
||||
func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareResult, failMessage string, msgAndArgs ...interface{}) bool {
|
||||
objKind := reflect.TypeOf(object).Kind()
|
||||
if objKind != reflect.Slice && objKind != reflect.Array {
|
||||
return false
|
||||
return Fail(t, fmt.Sprintf("object %T is not an ordered collection", object), msgAndArgs...)
|
||||
}
|
||||
|
||||
objValue := reflect.ValueOf(object)
|
||||
@@ -50,6 +50,9 @@ func isOrdered(t TestingT, object interface{}, allowedComparesResults []compareR
|
||||
// assert.IsIncreasing(t, []float{1, 2})
|
||||
// assert.IsIncreasing(t, []string{"a", "b"})
|
||||
func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return isOrdered(t, object, []compareResult{compareLess}, "\"%v\" is not less than \"%v\"", msgAndArgs...)
|
||||
}
|
||||
|
||||
@@ -59,6 +62,9 @@ func IsIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
|
||||
// assert.IsNonIncreasing(t, []float{2, 1})
|
||||
// assert.IsNonIncreasing(t, []string{"b", "a"})
|
||||
func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return isOrdered(t, object, []compareResult{compareEqual, compareGreater}, "\"%v\" is not greater than or equal to \"%v\"", msgAndArgs...)
|
||||
}
|
||||
|
||||
@@ -68,6 +74,9 @@ func IsNonIncreasing(t TestingT, object interface{}, msgAndArgs ...interface{})
|
||||
// assert.IsDecreasing(t, []float{2, 1})
|
||||
// assert.IsDecreasing(t, []string{"b", "a"})
|
||||
func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return isOrdered(t, object, []compareResult{compareGreater}, "\"%v\" is not greater than \"%v\"", msgAndArgs...)
|
||||
}
|
||||
|
||||
@@ -77,5 +86,8 @@ func IsDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) boo
|
||||
// assert.IsNonDecreasing(t, []float{1, 2})
|
||||
// assert.IsNonDecreasing(t, []string{"a", "b"})
|
||||
func IsNonDecreasing(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return isOrdered(t, object, []compareResult{compareLess, compareEqual}, "\"%v\" is not less than or equal to \"%v\"", msgAndArgs...)
|
||||
}
|
||||
+83
-64
@@ -17,11 +17,10 @@ import (
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/pmezard/go-difflib/difflib"
|
||||
|
||||
// Wrapper around gopkg.in/yaml.v3
|
||||
// Wrapper around go.yaml.in/yaml/v3
|
||||
"github.com/stretchr/testify/assert/yaml"
|
||||
"github.com/stretchr/testify/internal/difflib"
|
||||
"github.com/stretchr/testify/internal/spew"
|
||||
)
|
||||
|
||||
//go:generate sh -c "cd ../_codegen && go build && cd - && ../_codegen/_codegen -output-package=assert -template=assertion_format.go.tmpl"
|
||||
@@ -33,19 +32,19 @@ type TestingT interface {
|
||||
|
||||
// ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful
|
||||
// for table driven tests.
|
||||
type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool
|
||||
type ComparisonAssertionFunc = func(TestingT, interface{}, interface{}, ...interface{}) bool
|
||||
|
||||
// ValueAssertionFunc is a common function prototype when validating a single value. Can be useful
|
||||
// for table driven tests.
|
||||
type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool
|
||||
type ValueAssertionFunc = func(TestingT, interface{}, ...interface{}) bool
|
||||
|
||||
// BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful
|
||||
// for table driven tests.
|
||||
type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool
|
||||
type BoolAssertionFunc = func(TestingT, bool, ...interface{}) bool
|
||||
|
||||
// ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful
|
||||
// for table driven tests.
|
||||
type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool
|
||||
type ErrorAssertionFunc = func(TestingT, error, ...interface{}) bool
|
||||
|
||||
// PanicAssertionFunc is a common function prototype when validating a panic value. Can be useful
|
||||
// for table driven tests.
|
||||
@@ -325,13 +324,15 @@ func messageFromMsgAndArgs(msgAndArgs ...interface{}) string {
|
||||
func indentMessageLines(message string, longestLabelLen int) string {
|
||||
outBuf := new(bytes.Buffer)
|
||||
|
||||
for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ {
|
||||
// no need to align first line because it starts at the correct location (after the label)
|
||||
if i != 0 {
|
||||
// append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab
|
||||
outBuf.WriteString("\n\t" + strings.Repeat(" ", longestLabelLen+1) + "\t")
|
||||
scanner := bufio.NewScanner(strings.NewReader(message))
|
||||
for firstLine := true; scanner.Scan(); firstLine = false {
|
||||
if !firstLine {
|
||||
fmt.Fprint(outBuf, "\n\t"+strings.Repeat(" ", longestLabelLen+1)+"\t")
|
||||
}
|
||||
outBuf.WriteString(scanner.Text())
|
||||
fmt.Fprint(outBuf, scanner.Text())
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Sprintf("cannot display message: %s", err)
|
||||
}
|
||||
|
||||
return outBuf.String()
|
||||
@@ -544,9 +545,8 @@ func Same(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) b
|
||||
if !same {
|
||||
// both are pointers but not the same type & pointing to the same address
|
||||
return Fail(t, fmt.Sprintf("Not same: \n"+
|
||||
"expected: %p %#[1]v\n"+
|
||||
"actual : %p %#[2]v",
|
||||
expected, actual), msgAndArgs...)
|
||||
"expected: %[2]s (%[1]T)(%[1]p)\n"+
|
||||
"actual : %[4]s (%[3]T)(%[3]p)", expected, truncatingFormat("%#v", expected), actual, truncatingFormat("%#v", actual)), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -571,8 +571,8 @@ func NotSame(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}
|
||||
|
||||
if same {
|
||||
return Fail(t, fmt.Sprintf(
|
||||
"Expected and actual point to the same object: %p %#[1]v",
|
||||
expected), msgAndArgs...)
|
||||
"Expected and actual point to the same object: %p %s",
|
||||
expected, truncatingFormat("%#v", expected)), msgAndArgs...)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -604,25 +604,26 @@ func samePointers(first, second interface{}) (same bool, ok bool) {
|
||||
// to a type conversion in the Go grammar.
|
||||
func formatUnequalValues(expected, actual interface{}) (e string, a string) {
|
||||
if reflect.TypeOf(expected) != reflect.TypeOf(actual) {
|
||||
return fmt.Sprintf("%T(%s)", expected, truncatingFormat(expected)),
|
||||
fmt.Sprintf("%T(%s)", actual, truncatingFormat(actual))
|
||||
return fmt.Sprintf("%T(%s)", expected, truncatingFormat("%#v", expected)),
|
||||
fmt.Sprintf("%T(%s)", actual, truncatingFormat("%#v", actual))
|
||||
}
|
||||
switch expected.(type) {
|
||||
case time.Duration:
|
||||
return fmt.Sprintf("%v", expected), fmt.Sprintf("%v", actual)
|
||||
}
|
||||
return truncatingFormat(expected), truncatingFormat(actual)
|
||||
return truncatingFormat("%#v", expected), truncatingFormat("%#v", actual)
|
||||
}
|
||||
|
||||
// truncatingFormat formats the data and truncates it if it's too long.
|
||||
//
|
||||
// This helps keep formatted error messages lines from exceeding the
|
||||
// bufio.MaxScanTokenSize max line length that the go testing framework imposes.
|
||||
func truncatingFormat(data interface{}) string {
|
||||
value := fmt.Sprintf("%#v", data)
|
||||
max := bufio.MaxScanTokenSize - 100 // Give us some space the type info too if needed.
|
||||
if len(value) > max {
|
||||
value = value[0:max] + "<... truncated>"
|
||||
func truncatingFormat(format string, data interface{}) string {
|
||||
value := fmt.Sprintf(format, data)
|
||||
// Give us space for two truncated objects and the surrounding sentence.
|
||||
maxMessageSize := bufio.MaxScanTokenSize/2 - 100
|
||||
if len(value) > maxMessageSize {
|
||||
value = value[0:maxMessageSize] + "<... truncated>"
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -743,7 +744,7 @@ func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("Expected nil, but got: %s", truncatingFormat("%#v", object)), msgAndArgs...)
|
||||
}
|
||||
|
||||
// isEmpty gets whether the specified object is considered empty or not.
|
||||
@@ -793,7 +794,7 @@ func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...)
|
||||
Fail(t, fmt.Sprintf("Should be empty, but was %s", truncatingFormat("%v", object)), msgAndArgs...)
|
||||
}
|
||||
|
||||
return pass
|
||||
@@ -836,11 +837,11 @@ func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{})
|
||||
}
|
||||
l, ok := getLen(object)
|
||||
if !ok {
|
||||
return Fail(t, fmt.Sprintf("\"%v\" could not be applied builtin len()", object), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%q could not be applied builtin len()", truncatingFormat("%v", object)), msgAndArgs...)
|
||||
}
|
||||
|
||||
if l != length {
|
||||
return Fail(t, fmt.Sprintf("\"%v\" should have %d item(s), but has %d", object, length, l), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%q should have %d item(s), but has %d", truncatingFormat("%v", object), length, l), msgAndArgs...)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -889,7 +890,7 @@ func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{
|
||||
}
|
||||
|
||||
if ObjectsAreEqual(expected, actual) {
|
||||
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("Should not be: %s\n", truncatingFormat("%#v", actual)), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -904,7 +905,7 @@ func NotEqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...inte
|
||||
}
|
||||
|
||||
if ObjectsAreEqualValues(expected, actual) {
|
||||
return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("Should not be: %s\n", truncatingFormat("%#v", actual)), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -964,10 +965,10 @@ func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bo
|
||||
|
||||
ok, found := containsElement(s, contains)
|
||||
if !ok {
|
||||
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s could not be applied builtin len()", truncatingFormat("%#v", s)), msgAndArgs...)
|
||||
}
|
||||
if !found {
|
||||
return Fail(t, fmt.Sprintf("%#v does not contain %#v", s, contains), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s does not contain %#v", truncatingFormat("%#v", s), contains), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -986,10 +987,10 @@ func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{})
|
||||
|
||||
ok, found := containsElement(s, contains)
|
||||
if !ok {
|
||||
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", s), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s could not be applied builtin len()", truncatingFormat("%#v", s)), msgAndArgs...)
|
||||
}
|
||||
if found {
|
||||
return Fail(t, fmt.Sprintf("%#v should not contain %#v", s, contains), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s should not contain %#v", truncatingFormat("%#v", s), contains), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -1031,10 +1032,10 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
|
||||
av := actualMap.MapIndex(k)
|
||||
|
||||
if !av.IsValid() {
|
||||
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s does not contain %s", truncatingFormat("%#v", list), truncatingFormat("%#v", subset)), msgAndArgs...)
|
||||
}
|
||||
if !ObjectsAreEqual(ev.Interface(), av.Interface()) {
|
||||
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, subset), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s does not contain %s", truncatingFormat("%#v", list), truncatingFormat("%#v", subset)), msgAndArgs...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1056,7 +1057,7 @@ func Subset(t TestingT, list, subset interface{}, msgAndArgs ...interface{}) (ok
|
||||
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
|
||||
}
|
||||
if !found {
|
||||
return Fail(t, fmt.Sprintf("%#v does not contain %#v", list, element), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s does not contain %#v", truncatingFormat("%#v", list), element), msgAndArgs...)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1082,12 +1083,12 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
|
||||
|
||||
listKind := reflect.TypeOf(list).Kind()
|
||||
if listKind != reflect.Array && listKind != reflect.Slice && listKind != reflect.Map {
|
||||
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", list, listKind), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%#v has an unsupported type %s", list, listKind), msgAndArgs...)
|
||||
}
|
||||
|
||||
subsetKind := reflect.TypeOf(subset).Kind()
|
||||
if subsetKind != reflect.Array && subsetKind != reflect.Slice && subsetKind != reflect.Map {
|
||||
return Fail(t, fmt.Sprintf("%q has an unsupported type %s", subset, subsetKind), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%#v has an unsupported type %s", subset, subsetKind), msgAndArgs...)
|
||||
}
|
||||
|
||||
if subsetKind == reflect.Map && listKind == reflect.Map {
|
||||
@@ -1106,7 +1107,7 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
|
||||
}
|
||||
}
|
||||
|
||||
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s is a subset of %s", truncatingFormat("%#v", subset), truncatingFormat("%#v", list)), msgAndArgs...)
|
||||
}
|
||||
|
||||
subsetList := reflect.ValueOf(subset)
|
||||
@@ -1121,14 +1122,14 @@ func NotSubset(t TestingT, list, subset interface{}, msgAndArgs ...interface{})
|
||||
element := subsetList.Index(i).Interface()
|
||||
ok, found := containsElement(list, element)
|
||||
if !ok {
|
||||
return Fail(t, fmt.Sprintf("%q could not be applied builtin len()", list), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%#v could not be applied builtin len()", list), msgAndArgs...)
|
||||
}
|
||||
if !found {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return Fail(t, fmt.Sprintf("%q is a subset of %q", subset, list), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("%s is a subset of %s", truncatingFormat("%#v", subset), truncatingFormat("%#v", list)), msgAndArgs...)
|
||||
}
|
||||
|
||||
// ElementsMatch asserts that the specified listA(array, slice...) is equal to specified
|
||||
@@ -1343,9 +1344,15 @@ func PanicsWithError(t TestingT, errString string, f PanicTestFunc, msgAndArgs .
|
||||
if !funcDidPanic {
|
||||
return Fail(t, fmt.Sprintf("func %#v should panic\n\tPanic value:\t%#v", f, panicValue), msgAndArgs...)
|
||||
}
|
||||
panicErr, ok := panicValue.(error)
|
||||
if !ok || panicErr.Error() != errString {
|
||||
return Fail(t, fmt.Sprintf("func %#v should panic with error message:\t%#v\n\tPanic value:\t%#v\n\tPanic stack:\t%s", f, errString, panicValue, panickedStack), msgAndArgs...)
|
||||
panicErr, isError := panicValue.(error)
|
||||
if !isError || panicErr.Error() != errString {
|
||||
msg := fmt.Sprintf("func %#v should panic with error message:\t%#v\n", f, errString)
|
||||
if isError {
|
||||
msg += fmt.Sprintf("\tError message:\t%#v\n", panicErr.Error())
|
||||
}
|
||||
msg += fmt.Sprintf("\tPanic value:\t%#v\n", panicValue)
|
||||
msg += fmt.Sprintf("\tPanic stack:\t%s\n", panickedStack)
|
||||
return Fail(t, msg, msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -1624,7 +1631,7 @@ func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, m
|
||||
Errors
|
||||
*/
|
||||
|
||||
// NoError asserts that a function returned no error (i.e. `nil`).
|
||||
// NoError asserts that a function returned a nil error (ie. no error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// if assert.NoError(t, err) {
|
||||
@@ -1635,13 +1642,13 @@ func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
}
|
||||
return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("Received unexpected error:\n%s", truncatingFormat("%+v", err)), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Error asserts that a function returned an error (i.e. not `nil`).
|
||||
// Error asserts that a function returned a non-nil error (ie. an error).
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// assert.Error(t, err)
|
||||
@@ -1656,7 +1663,7 @@ func Error(t TestingT, err error, msgAndArgs ...interface{}) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// EqualError asserts that a function returned an error (i.e. not `nil`)
|
||||
// EqualError asserts that a function returned a non-nil error (i.e. an error)
|
||||
// and that it is equal to the provided error.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
@@ -1674,13 +1681,13 @@ func EqualError(t TestingT, theError error, errString string, msgAndArgs ...inte
|
||||
if expected != actual {
|
||||
return Fail(t, fmt.Sprintf("Error message not equal:\n"+
|
||||
"expected: %q\n"+
|
||||
"actual : %q", expected, actual), msgAndArgs...)
|
||||
"actual : %s", expected, truncatingFormat("%q", actual)), msgAndArgs...)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
|
||||
// and that the error contains the specified substring.
|
||||
// ErrorContains asserts that a function returned a non-nil error (i.e. an
|
||||
// error) and that the error contains the specified substring.
|
||||
//
|
||||
// actualObj, err := SomeFunction()
|
||||
// assert.ErrorContains(t, err, expectedErrorSubString)
|
||||
@@ -1694,7 +1701,7 @@ func ErrorContains(t TestingT, theError error, contains string, msgAndArgs ...in
|
||||
|
||||
actual := theError.Error()
|
||||
if !strings.Contains(actual, contains) {
|
||||
return Fail(t, fmt.Sprintf("Error %#v does not contain %#v", actual, contains), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("Error %s does not contain %#v", truncatingFormat("%#v", actual), contains), msgAndArgs...)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -1760,7 +1767,7 @@ func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool {
|
||||
h.Helper()
|
||||
}
|
||||
if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) {
|
||||
return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...)
|
||||
return Fail(t, fmt.Sprintf("Should be zero, but was %s", truncatingFormat("%v", i)), msgAndArgs...)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1874,7 +1881,19 @@ func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{
|
||||
return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...)
|
||||
}
|
||||
|
||||
// YAMLEq asserts that two YAML strings are equivalent.
|
||||
// YAMLEq asserts that the first documents in the two YAML strings are equivalent.
|
||||
//
|
||||
// expected := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a second document, it is not evaluated
|
||||
// `
|
||||
// actual := `---
|
||||
// key: value
|
||||
// ---
|
||||
// key: this is a subsequent document, it is not evaluated
|
||||
// `
|
||||
// assert.YAMLEq(t, expected, actual)
|
||||
func YAMLEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool {
|
||||
if h, ok := t.(tHelper); ok {
|
||||
h.Helper()
|
||||
@@ -2188,8 +2207,8 @@ func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
|
||||
chain := buildErrorChainString(err, false)
|
||||
|
||||
return Fail(t, fmt.Sprintf("Target error should be in err chain:\n"+
|
||||
"expected: %q\n"+
|
||||
"in chain: %s", expectedText, chain,
|
||||
"expected: %s\n"+
|
||||
"in chain: %s", truncatingFormat("%q", expectedText), truncatingFormat("%s", chain),
|
||||
), msgAndArgs...)
|
||||
}
|
||||
|
||||
@@ -2211,8 +2230,8 @@ func NotErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool {
|
||||
chain := buildErrorChainString(err, false)
|
||||
|
||||
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
|
||||
"found: %q\n"+
|
||||
"in chain: %s", expectedText, chain,
|
||||
"found: %s\n"+
|
||||
"in chain: %s", truncatingFormat("%q", expectedText), truncatingFormat("%s", chain),
|
||||
), msgAndArgs...)
|
||||
}
|
||||
|
||||
@@ -2236,7 +2255,7 @@ func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{
|
||||
|
||||
return Fail(t, fmt.Sprintf("Should be in error chain:\n"+
|
||||
"expected: %s\n"+
|
||||
"in chain: %s", expectedType, chain,
|
||||
"in chain: %s", expectedType, truncatingFormat("%s", chain),
|
||||
), msgAndArgs...)
|
||||
}
|
||||
|
||||
@@ -2254,7 +2273,7 @@ func NotErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interfa
|
||||
|
||||
return Fail(t, fmt.Sprintf("Target error should not be in err chain:\n"+
|
||||
"found: %s\n"+
|
||||
"in chain: %s", reflect.TypeOf(target).Elem().String(), chain,
|
||||
"in chain: %s", reflect.TypeOf(target).Elem().String(), truncatingFormat("%s", chain),
|
||||
), msgAndArgs...)
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -40,8 +40,8 @@
|
||||
//
|
||||
// # Assertions
|
||||
//
|
||||
// Assertions allow you to easily write test code, and are global funcs in the `assert` package.
|
||||
// All assertion functions take, as the first argument, the `*testing.T` object provided by the
|
||||
// Assertions allow you to easily write test code, and are global funcs in the assert package.
|
||||
// All assertion functions take, as the first argument, the [*testing.T] object provided by the
|
||||
// testing framework. This allows the assertion funcs to write the failings and other details to
|
||||
// the correct place.
|
||||
//
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
// go test -tags testify_yaml_custom
|
||||
//
|
||||
// This implementation can be used at build time to replace the default implementation
|
||||
// to avoid linking with [gopkg.in/yaml.v3].
|
||||
// to avoid linking with [go.yaml.in/yaml/v3].
|
||||
//
|
||||
// In your test package:
|
||||
//
|
||||
|
||||
Loaded 100 of 371 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user