diff --git a/.gitignore b/.gitignore index fd5a0ab..ece2bf0 100644 --- a/.gitignore +++ b/.gitignore @@ -69,8 +69,6 @@ fabric.properties *.out /node_modules/ -/vendor/ -google/ package.json yarn.lock /bin/golangci-lint diff --git a/.version b/.version index 295ec49..3769235 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -6.8.2 \ No newline at end of file +7.1.0 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index dbb8012..bbf72ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,16 @@ +### 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 +* Изменена логика авторизации через СУДИР: + * Изменена схема конфигурации для авторизации через СУДИР + * Изменён контракт взаимодействия по `admin/auth/login_with_sudir` + * Добавлен endpoint для получения ссылок для login и logout через sudir - `admin/ui_settings/sudir` ### v6.8.2 * обновлены зависимости ### v6.8.1 diff --git a/README.md b/README.md index 5d50a47..632941e 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -# msp-admin-service \ No newline at end of file +# isp-admin-service \ No newline at end of file diff --git a/assembly/assembly.go b/assembly/assembly.go index c0955b7..e873a9f 100644 --- a/assembly/assembly.go +++ b/assembly/assembly.go @@ -4,45 +4,48 @@ 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" "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/observability/sentry" ) type Assembly struct { boot *bootstrap.Bootstrap db *dbrx.Client server *grpc.Server - httpCli *httpcli.Client + oauthCli *httpcli.Client logger *log.Adapter bgjobCli *bgjobx.Client } func New(boot *bootstrap.Bootstrap) (*Assembly, error) { logger := boot.App.Logger() - server := grpc.NewServer() - httpCli := httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(logger))) - db := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, logger)) - bgjobCli := bgjobx.NewClient(db, logger) + wrappedLogger := sentry.WrapErrorLogger(logger, boot.SentryHub) + + db := dbrx.New(logger, dbx.WithMigrationRunner(boot.MigrationsDir, wrappedLogger)) + boot.HealthcheckRegistry.Register("db", db) + + bgjobCli := bgjobx.NewClient(db, wrappedLogger) return &Assembly{ boot: boot, db: db, - server: server, + server: grpc.NewServer(), logger: logger, - httpCli: httpCli, + oauthCli: httpclix.Default(httpcli.WithMiddlewares(httpclix.Log(wrappedLogger))), bgjobCli: bgjobCli, }, nil } @@ -64,8 +67,17 @@ func (a *Assembly) ReceiveConfig(ctx context.Context, remoteConfig []byte) error a.logger.Fatal(ctx, errors.WithMessage(err, "upgrade db client")) } - locator := NewLocator(a.logger, a.httpCli, a.db) - config := locator.Config(ctx, newCfg, time.Minute) + oauthBaseUrl := "" + if newCfg.Oauth != nil { + oauthBaseUrl = newCfg.Oauth.Host + } + a.oauthCli.GlobalRequestConfig().BaseUrl = oauthBaseUrl + + 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")) + } a.server.Upgrade(config.Handler) diff --git a/assembly/locator.go b/assembly/locator.go index 9c184cf..548ef35 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -4,19 +4,20 @@ 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" + "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/grpc/endpoint" "github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/http/httpcli" @@ -29,16 +30,16 @@ type DB interface { } type Locator struct { - logger log.Logger - httpCli *httpcli.Client - db DB + logger log.Logger + oauthCli *httpcli.Client + db DB } -func NewLocator(logger log.Logger, httpCli *httpcli.Client, db DB) Locator { +func NewLocator(logger log.Logger, oauthCli *httpcli.Client, db DB) Locator { return Locator{ - logger: logger, - httpCli: httpCli, - db: db, + logger: logger, + oauthCli: oauthCli, + db: db, } } @@ -52,8 +53,8 @@ func (l Locator) Config( ctx context.Context, cfg conf.Remote, jobPollInterval time.Duration, -) Config { - sudirRepo := repository.NewSudir(l.httpCli, cfg.SudirAuth) +) (Config, error) { + oauthRepo := repository.NewOauth(l.oauthCli) roleRepo := repository.NewRole(l.db) userRepo := repository.NewUser(l.db) tokenRepo := repository.NewToken(l.db) @@ -63,7 +64,13 @@ func (l Locator) Config( auditService := service.NewAudit(ctx, l.logger, auditRepo, auditEventRepo, cfg.Audit.EventSettings) tokenService := service.NewToken(tokenRepo, cfg.ExpireSec) - sudirService := service.NewSudir(cfg.SudirAuth, sudirRepo) + + oauthBaseUrl, oauthSettings := l.getOauthSettings(cfg.Oauth) + oauthService, err := service.NewOauth(oauthSettings, oauthRepo) + if err != nil { + return Config{}, errors.WithMessage(err, "new oauth") + } + secureService := secure.NewService(tokenRepo, userRoleRepo) txManager := transaction.NewManager(l.db) @@ -80,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, ) @@ -88,6 +95,8 @@ func (l Locator) Config( permissionsService := service.NewPermission(cfg.Permissions) + uiSettingsService := service.NewUiSettings(oauthBaseUrl, oauthSettings) + userController := controller.NewUser(userService) customizationController := controller.NewCustomization(cfg.UiDesign) authController := controller.NewAuth(authService, l.logger) @@ -96,7 +105,7 @@ func (l Locator) Config( auditController := controller.NewAudit(auditService) roleController := controller.NewRole(roleService) permissionController := controller.NewPermissions(permissionsService) - + uiSettingsController := controller.NewUiSettings(uiSettingsService) handler := routes.Handler( endpoint.DefaultWrapper(l.logger), routes.Controllers{ @@ -108,6 +117,7 @@ func (l Locator) Config( Audit: auditController, Role: roleController, Permissions: permissionController, + UiSettings: uiSettingsController, }, ) @@ -139,5 +149,13 @@ func (l Locator) Config( PollInterval: jobPollInterval, Handle: expireSessionWorker, }}, + }, nil +} + +func (l Locator) getOauthSettings(oauthAuth *conf.Oauth) (string, []conf.OauthClientConfig) { + if oauthAuth == nil { + return "", []conf.OauthClientConfig{} } + + return oauthAuth.Host, oauthAuth.Clients } diff --git a/conf/config.yml b/conf/config.yml index df916e2..789b33d 100644 --- a/conf/config.yml +++ b/conf/config.yml @@ -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 diff --git a/conf/remote.go b/conf/remote.go index c4888bb..d5a701d 100644 --- a/conf/remote.go +++ b/conf/remote.go @@ -1,3 +1,4 @@ +//nolint:lll package conf import ( @@ -10,7 +11,7 @@ import ( ) // nolint: gochecknoinits -func init() { // +func init() { schema.CustomGenerators.Register("logLevel", func(field reflect.StructField, t *jsonschema.Schema) { t.Type = "string" t.Enum = []any{"debug", "info", "error", "fatal"} @@ -18,13 +19,12 @@ func init() { // } type Remote struct { - Audit Audit - Database dbx.Config - ExpireSec int `validate:"required" schema:"Время жизни токена в секундах,in seconds"` - UiDesign UIDesign `schema:"Кастомизация интерфейса"` - //nolint:lll + Audit Audit `schema:"Настройки audit"` + Database dbx.Config `schema:"Настройка подключения к БД"` + 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:"Блокировка неактивных УЗ"` @@ -32,30 +32,41 @@ type Remote struct { } type Audit struct { - EventSettings []AuditEventSetting - AuditTTl AuditTTlSetting + EventSettings []AuditEventSetting `schema:"Маппинг событий"` + AuditTTl AuditTTlSetting `schema:"Настройки TTL для audit"` } type AuditTTlSetting struct { - TimeToLiveInMin int `validate:"required"` - ExpireSyncPeriodInMin int `validate:"required"` + TimeToLiveInMin int `validate:"required" schema:"TTL события в минутах"` + ExpireSyncPeriodInMin int `validate:"required" schema:"Интервал запуска воркера"` } type AuditEventSetting struct { - Event string - Name string + Event string `schema:"Ключ события"` + Name string `schema:"Пользовательское название события"` } type UIDesign struct { Name string `schema:"Название стенда"` - PrimaryColor string `schema:"Цвет в HEX, примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"` + PrimaryColor string `schema:"Цвет в HEX,примеры: #ff4d4f #fa8c16 #a0d911 #1890ff #722ed1 #d4b106 #e91e63 #ff5722 #795548 #abb8c3 #525252 #689f38"` } -type SudirAuth struct { - ClientId string `validate:"required"` - ClientSecret string `validate:"required"` - Host string `validate:"required" schema:"Хост, пример https://sudir.mos.ru"` - RedirectURI string `validate:"required"` +type Oauth struct { + Host string `validate:"required" schema:"Базовый путь до методов, пример https://oauth.example.com"` + Clients []OauthClientConfig `validate:"omitempty,min=1" schema:"Настройка взаимодействия для логина по authCode"` +} + +type OauthClientConfig struct { + ClientName string `validate:"required" schema:"Уникальное имя конфигурации клиента"` + ClientId string `validate:"required" schema:"Идентификатор клиента,выданный для basicAuth"` + ClientSecret string `validate:"required" schema:"Пароль клиента,выданный для basicAuth"` + RedirectURI string `validate:"required" schema:"URI для редиректа,передаётся в запросе токена в query"` + UiSetting *UiOauthSetting `schema:"Настройки OAuth для админки"` +} + +type UiOauthSetting struct { + LoginEndpoint string `validate:"required" schema:"Эндпоинт для входа через OAuth в адмиинке,может содержать query параметры,client_id и redirect_uri добавляются автоматически"` + LogoutEndpoint string `validate:"required" schema:"Эндпоинт для выхода через OAuth в адмиинке"` } type AntiBruteforce struct { @@ -69,6 +80,6 @@ type BlockInactiveWorker struct { } type Permission struct { - Key string - Name string + Key string `schema:"Ключ прав"` + Name string `schema:"Пользовательское название"` } diff --git a/conf/remote_test.go b/conf/remote_test.go index 03fc95d..0f66d7b 100644 --- a/conf/remote_test.go +++ b/conf/remote_test.go @@ -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) { diff --git a/controller/audit.go b/controller/audit.go index e39634f..396ce80 100644 --- a/controller/audit.go +++ b/controller/audit.go @@ -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" ) diff --git a/controller/auth.go b/controller/auth.go index 8473d0f..d9da2cc 100644 --- a/controller/auth.go +++ b/controller/auth.go @@ -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 401 {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 } diff --git a/controller/customization.go b/controller/customization.go index 954c555..3c5492b 100644 --- a/controller/customization.go +++ b/controller/customization.go @@ -1,16 +1,20 @@ package controller import ( - "msp-admin-service/conf" + "isp-admin-service/conf" + "isp-admin-service/domain" ) type Customization struct { - uiCfg conf.UIDesign + uiCfg domain.UIDesign } func NewCustomization(uiCfg conf.UIDesign) Customization { return Customization{ - uiCfg: uiCfg, + uiCfg: domain.UIDesign{ + Name: uiCfg.Name, + PrimaryColor: uiCfg.PrimaryColor, + }, } } @@ -21,10 +25,10 @@ func NewCustomization(uiCfg conf.UIDesign) Customization { // @Accept json // @Produce json // @Param X-AUTH-ADMIN header string true "Токен администратора" -// @Success 200 {object} conf.UIDesign +// @Success 200 {object} domain.UIDesign // @Failure 400 {object} domain.GrpcError "Невалидный токен" // @Failure 500 {object} domain.GrpcError // @Router /user/get_design [POST] -func (c Customization) GetUIDesign() (conf.UIDesign, error) { +func (c Customization) GetUIDesign() (domain.UIDesign, error) { return c.uiCfg, nil } diff --git a/controller/permissions.go b/controller/permissions.go index 0d4ca0f..61f7c21 100644 --- a/controller/permissions.go +++ b/controller/permissions.go @@ -3,7 +3,7 @@ package controller import ( "context" - "msp-admin-service/domain" + "isp-admin-service/domain" ) type permissionsService interface { diff --git a/controller/role.go b/controller/role.go index 2d3779b..fd13db7 100644 --- a/controller/role.go +++ b/controller/role.go @@ -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 { diff --git a/controller/secure.go b/controller/secure.go index dcc1ad1..0c4907d 100644 --- a/controller/secure.go +++ b/controller/secure.go @@ -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 { diff --git a/controller/session.go b/controller/session.go index 614ce1b..b96027e 100644 --- a/controller/session.go +++ b/controller/session.go @@ -3,7 +3,7 @@ package controller import ( "context" - "msp-admin-service/domain" + "isp-admin-service/domain" ) type SessionService interface { diff --git a/controller/ui_settings.go b/controller/ui_settings.go new file mode 100644 index 0000000..8cf500b --- /dev/null +++ b/controller/ui_settings.go @@ -0,0 +1,48 @@ +package controller + +import ( + "context" + "isp-admin-service/domain" + + "github.com/txix-open/isp-kit/errors" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type UiSettingsService interface { + OauthSettings(ctx context.Context, req domain.ClientNameRequest) (*domain.UiOauthSetting, error) +} + +type UiSettings struct { + service UiSettingsService +} + +func NewUiSettings(service UiSettingsService) UiSettings { + return UiSettings{ + service: service, + } +} + +// UiOauthSettings +// @Tags ui_settings +// @Summary Получение настроек для ui для авторизации через OAuth +// @Description Получение настроек для ui для авторизации через OAuth +// @Accept json +// @Produce json +// @Param body body domain.ClientNameRequest true "Тело запроса" +// @Success 200 {object} domain.UiOauthSetting +// @Failure 400 {object} domain.GrpcError +// @Failure 401 {object} domain.GrpcError "Неизвестное название клиента" +// @Failure 500 {object} domain.GrpcError +// @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") + case err != nil: + return nil, err + default: + return resp, nil + } +} diff --git a/controller/user.go b/controller/user.go index 9ddbbe5..c179af8 100644 --- a/controller/user.go +++ b/controller/user.go @@ -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" diff --git a/docs/swagger.go b/docs/swagger.go new file mode 100644 index 0000000..7579fde --- /dev/null +++ b/docs/swagger.go @@ -0,0 +1,9 @@ +package docs + +import _ "embed" + +// Embedded swagger files. +var ( + //go:embed swagger.json + SwaggerJson []byte +) diff --git a/docs/swagger.json b/docs/swagger.json new file mode 100644 index 0000000..68327ff --- /dev/null +++ b/docs/swagger.json @@ -0,0 +1,2254 @@ +{ + "swagger": "2.0", + "info": { + "description": "сервис управления администраторами", + "title": "isp-admin-service", + "contact": {}, + "license": { + "name": "GNU GPL v3.0" + }, + "version": "1.0.0" + }, + "host": "localhost:9000", + "basePath": "/api/admin", + "paths": { + "/auth/login": { + "post": { + "description": "Авторизация с получением токена администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Авторизация по логину и паролю", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.LoginRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.LoginResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "401": { + "description": "Данные для авторизации не верны", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/auth/login_with_oauth": { + "post": { + "description": "Авторизация с получением токена администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Авторизация по авторизационному коду от OAuth", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.LoginOauthRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.LoginResponse" + } + }, + "401": { + "description": "Некорректный код для авторизации или неизвестное название клиента", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "412": { + "description": "Авторизация OAuth не настроена на сервере", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/auth/logout": { + "post": { + "description": "Выход из авторизованной сессии администрирования", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Выход из авторизованной сессии", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидный токен", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/auth/logout_with_reason": { + "post": { + "description": "Выход по бездействию из авторизованной сессии администрирования", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "auth" + ], + "summary": "Выход по бездействию из авторизованной сессии", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.LogoutRequest" + } + }, + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидный токен", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/log/all": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "log" + ], + "summary": "Получение списка логов", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.AuditPageRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.AuditResponse" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/log/events": { + "post": { + "description": "Возвращает полный список доступных событий аудита", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "log" + ], + "summary": "Получение списка логов", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.AuditResponse" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.AuditEvent" + } + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/log/set_events": { + "post": { + "description": "Всегда возвращает полный список доступных событий аудита", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "log" + ], + "summary": "Получение списка логов", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.SetAuditEvent" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/role/all": { + "post": { + "description": "Получить список ролей", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "role" + ], + "summary": "Список ролей", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.Role" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/role/create": { + "post": { + "description": "Создать роль", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Создать роль", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateRoleRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.User" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "409": { + "description": "Роль с указанным именем уже существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/role/delete": { + "post": { + "description": "Удалить существующую роль", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "role" + ], + "summary": "Удалить роль", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.DeleteRoleRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/role/update": { + "post": { + "description": "Обновить данные существующую роль", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "role" + ], + "summary": "Обновить роль", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateRoleRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.Role" + } + }, + "404": { + "description": "Роль с указанным id не существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "409": { + "description": "Роль с указанным именем уже существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/secure/authenticate": { + "post": { + "description": "Проверяет токен и возвращает идентификатор администратора", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "secure" + ], + "summary": "Метод аутентификации токена", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.SecureAuthRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.SecureAuthResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/secure/authorize": { + "post": { + "description": "Проверяет наличие у администратора необходимого разрешения", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "secure" + ], + "summary": "Метод авторизации для администратора", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.SecureAuthzRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.SecureAuthzResponse" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/session/all": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "session" + ], + "summary": "Получение списка сессий", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.SessionPageRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.SessionResponse" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/session/revoke": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "session" + ], + "summary": "Отзыв сессии", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.RevokeRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/ui_settings/oauth": { + "post": { + "description": "Получение настроек для ui для авторизации через OAuth", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "ui_settings" + ], + "summary": "Получение настроек для ui для авторизации через OAuth", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ClientNameRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.UiOauthSetting" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "401": { + "description": "Неизвестное название клиента", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/block_user": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Метод блокировки/разблокировки пользователя", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.IdRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/change_password": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Метод изменения пароля пользователя", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.ChangePasswordRequest" + } + } + ], + "responses": { + "200": { + "description": "OK" + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/apierrors.Error" + } + }, + "500": { + "description": "внутренняя ошибка", + "schema": { + "$ref": "#/definitions/apierrors.Error" + } + } + } + } + }, + "/user/create_user": { + "post": { + "description": "Создать пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Создать пользователя", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.CreateUserRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.User" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "409": { + "description": "Пользователь с указанным email уже существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/delete_user": { + "post": { + "description": "Удалить существующего пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Удалить пользователя", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.IdentitiesRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.DeleteResponse" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/get_all_users": { + "post": { + "description": "Получить список пользователей", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Список пользователей", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.UsersResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/get_by_id": { + "post": { + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Метод получения данных по пользователю", + "parameters": [ + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.IdRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.User" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/get_design": { + "post": { + "description": "Получение внешнего вида (палитра и наименование) админ-интерфейса", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Получение внешнего вида", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.UIDesign" + } + }, + "400": { + "description": "Невалидный токен", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/get_permissions": { + "post": { + "description": "Получить все разрашения", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Получить все разрашения", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/domain.Permission" + } + } + } + } + } + }, + "/user/get_profile": { + "post": { + "description": "Получить данные профиля", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Получить профиль", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.AdminUserShort" + } + }, + "400": { + "description": "Невалидный токен", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "404": { + "description": "Пользователя не существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/get_users": { + "post": { + "description": "Получить список пользователей", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Список пользователей", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UsersPageRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.UsersResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + }, + "/user/update_user": { + "post": { + "description": "Обновить данные существующего пользователя", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "tags": [ + "user" + ], + "summary": "Обновить пользователя", + "parameters": [ + { + "type": "string", + "description": "Токен администратора", + "name": "X-AUTH-ADMIN", + "in": "header", + "required": true + }, + { + "description": "Тело запроса", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/domain.UpdateUserRequest" + } + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/domain.User" + } + }, + "400": { + "description": "Невалидное тело запроса", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "404": { + "description": "Пользователь с указанным id не существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "409": { + "description": "Пользователь с указанным email уже существует", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/domain.GrpcError" + } + } + } + } + } + }, + "definitions": { + "apierrors.Error": { + "type": "object", + "properties": { + "details": { + "type": "object", + "additionalProperties": {} + }, + "errorCode": { + "type": "integer" + }, + "errorMessage": { + "type": "string" + } + } + }, + "domain.AdminUserShort": { + "type": "object", + "required": [ + "email" + ], + "properties": { + "email": { + "description": "Электронный адрес", + "type": "string" + }, + "firstName": { + "description": "Имя", + "type": "string" + }, + "fullName": { + "description": "ФИО", + "type": "string" + }, + "idleTimeoutMs": { + "description": "Время бездействия пользователя в мс", + "type": "integer" + }, + "lastName": { + "description": "Фамилия", + "type": "string" + }, + "permissions": { + "description": "Список прав", + "type": "array", + "items": { + "type": "string" + } + }, + "role": { + "description": "Название роли", + "type": "string" + }, + "roleNames": { + "description": "Список названия ролей", + "type": "array", + "items": { + "type": "string" + } + }, + "roles": { + "description": "Список идентификаторов ролей", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.Audit": { + "type": "object", + "properties": { + "createdAt": { + "description": "Дата события", + "type": "string" + }, + "id": { + "description": "Идентификатор audit'а", + "type": "integer" + }, + "message": { + "description": "Сообщение", + "type": "string" + }, + "userId": { + "description": "Идентификатор пользователя", + "type": "integer" + } + } + }, + "domain.AuditEvent": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean" + }, + "event": { + "description": "Название события", + "type": "string" + }, + "name": { + "type": "string" + } + } + }, + "domain.AuditPageRequest": { + "type": "object", + "required": [ + "limit" + ], + "properties": { + "limit": { + "description": "Максимальное количество записей", + "type": "integer" + }, + "offset": { + "description": "Отступ для выборки", + "type": "integer", + "format": "int64" + }, + "order": { + "description": "Параметры сортировки", + "allOf": [ + { + "$ref": "#/definitions/domain.OrderParams" + } + ] + }, + "query": { + "description": "Параметры выборки", + "allOf": [ + { + "$ref": "#/definitions/domain.AuditQuery" + } + ] + } + } + }, + "domain.AuditQuery": { + "type": "object", + "properties": { + "createdAt": { + "description": "Фильтр по дате", + "allOf": [ + { + "$ref": "#/definitions/domain.DateFromToParams" + } + ] + }, + "id": { + "description": "Фильтр по идентификатору audit", + "type": "integer" + }, + "message": { + "description": "Фильтр по сообщению", + "type": "string" + }, + "userId": { + "description": "Фильтр по идентификатору пользователей", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.AuditResponse": { + "type": "object", + "properties": { + "items": { + "description": "Список audit'ов", + "type": "array", + "items": { + "$ref": "#/definitions/domain.Audit" + } + }, + "totalCount": { + "description": "Количество audit'ов", + "type": "integer" + } + } + }, + "domain.ChangePasswordRequest": { + "type": "object", + "required": [ + "newPassword", + "oldPassword" + ], + "properties": { + "newPassword": { + "description": "Новый пароль", + "type": "string" + }, + "oldPassword": { + "description": "Старый пароль", + "type": "string" + } + } + }, + "domain.ClientNameRequest": { + "type": "object", + "required": [ + "clientName" + ], + "properties": { + "clientName": { + "type": "string" + } + } + }, + "domain.CreateRoleRequest": { + "type": "object", + "properties": { + "changeMessage": { + "description": "Причина изменений", + "type": "string" + }, + "externalGroup": { + "description": "Внешнее название группы", + "type": "string" + }, + "name": { + "description": "Название роли", + "type": "string" + }, + "permissions": { + "description": "Набор прав", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "domain.CreateUserRequest": { + "type": "object", + "required": [ + "email", + "password" + ], + "properties": { + "description": { + "description": "Описание", + "type": "string" + }, + "email": { + "description": "Электронный адрес", + "type": "string" + }, + "firstName": { + "description": "Имя", + "type": "string" + }, + "lastName": { + "description": "Фамилия", + "type": "string" + }, + "password": { + "description": "Пароль", + "type": "string" + }, + "roles": { + "description": "Список идентификаторов ролей", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.DateFromToParams": { + "type": "object", + "required": [ + "from", + "to" + ], + "properties": { + "from": { + "description": "Дата с", + "type": "string" + }, + "to": { + "description": "Дата до", + "type": "string" + } + } + }, + "domain.DeleteResponse": { + "type": "object", + "properties": { + "deleted": { + "description": "Количество удалённых УЗ", + "type": "integer" + } + } + }, + "domain.DeleteRoleRequest": { + "type": "object", + "properties": { + "id": { + "description": "Идентификатор роли", + "type": "integer" + } + } + }, + "domain.GrpcError": { + "type": "object", + "properties": { + "details": { + "type": "array", + "items": {} + }, + "errorCode": { + "type": "string" + }, + "errorMessage": { + "type": "string" + } + } + }, + "domain.IdRequest": { + "type": "object", + "required": [ + "userId" + ], + "properties": { + "userId": { + "description": "Идентификато пользователя", + "type": "integer" + } + } + }, + "domain.IdentitiesRequest": { + "type": "object", + "required": [ + "ids" + ], + "properties": { + "ids": { + "description": "Список идентификаторов", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.LoginOauthRequest": { + "type": "object", + "required": [ + "authCode", + "clientName" + ], + "properties": { + "authCode": { + "description": "Код для авторизации у OAuth-провайдера", + "type": "string" + }, + "clientName": { + "description": "Уникальное имя конфигурации клиента", + "type": "string" + } + } + }, + "domain.LoginRequest": { + "type": "object", + "required": [ + "email", + "password" + ], + "properties": { + "email": { + "description": "Электронная почта", + "type": "string" + }, + "password": { + "description": "Пароль", + "type": "string" + } + } + }, + "domain.LoginResponse": { + "type": "object", + "properties": { + "expired": { + "description": "Дата истечения токена", + "type": "string" + }, + "headerName": { + "description": "Названия заголовка для передачи токена", + "type": "string" + }, + "token": { + "description": "Токен", + "type": "string" + } + } + }, + "domain.LogoutRequest": { + "type": "object", + "properties": { + "reason": { + "description": "Причина выхода", + "type": "string" + } + } + }, + "domain.OrderParams": { + "type": "object", + "properties": { + "field": { + "description": "Поле сортировки", + "type": "string" + }, + "type": { + "description": "Порядок сортировки", + "type": "string", + "enum": [ + "asc", + "desc", + "ASC", + "DESC" + ] + } + } + }, + "domain.Permission": { + "type": "object", + "properties": { + "key": { + "description": "Ключ прав", + "type": "string" + }, + "name": { + "description": "Пользовательское название", + "type": "string" + } + } + }, + "domain.RevokeRequest": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "id": { + "description": "Идентификатор сессии", + "type": "integer" + } + } + }, + "domain.Role": { + "type": "object", + "properties": { + "changeMessage": { + "description": "Причина изменений", + "type": "string" + }, + "createdAt": { + "description": "Дата создания", + "type": "string" + }, + "exclusive": { + "type": "boolean" + }, + "externalGroup": { + "description": "Внешнее название группы", + "type": "string" + }, + "id": { + "description": "Идентификатор роли", + "type": "integer" + }, + "immutable": { + "type": "boolean" + }, + "name": { + "description": "Название роли", + "type": "string" + }, + "permissions": { + "description": "Набор прав", + "type": "array", + "items": { + "type": "string" + } + }, + "updatedAt": { + "description": "Дата обновления", + "type": "string" + } + } + }, + "domain.SecureAuthRequest": { + "type": "object", + "properties": { + "token": { + "description": "Токен", + "type": "string" + } + } + }, + "domain.SecureAuthResponse": { + "type": "object", + "properties": { + "adminId": { + "description": "Идентификатор администратора", + "type": "integer", + "format": "int64" + }, + "authenticated": { + "description": "Флаг успешной аутентикации", + "type": "boolean" + }, + "errorReason": { + "description": "Причина ошибки", + "type": "string" + } + } + }, + "domain.SecureAuthzRequest": { + "type": "object", + "properties": { + "adminId": { + "description": "Идентификатор администратора", + "type": "integer" + }, + "permission": { + "description": "Роль", + "type": "string" + } + } + }, + "domain.SecureAuthzResponse": { + "type": "object", + "properties": { + "authorized": { + "description": "Флаг успешноЙ авторизации", + "type": "boolean" + } + } + }, + "domain.Session": { + "type": "object", + "properties": { + "createdAt": { + "description": "Дата создания сессии", + "type": "string" + }, + "expiredAt": { + "description": "Дата протухания сессии", + "type": "string" + }, + "id": { + "description": "Идентификатор сессии", + "type": "integer" + }, + "status": { + "description": "Статус сессии", + "type": "string" + }, + "userId": { + "description": "Идентификатор пользоватеккля", + "type": "integer" + } + } + }, + "domain.SessionPageRequest": { + "type": "object", + "required": [ + "limit" + ], + "properties": { + "limit": { + "description": "Максимальное количество записей", + "type": "integer" + }, + "offset": { + "description": "Отступ для выборки", + "type": "integer", + "format": "int64" + }, + "order": { + "description": "Параметры сортировки", + "allOf": [ + { + "$ref": "#/definitions/domain.OrderParams" + } + ] + }, + "query": { + "description": "Параметры выборки", + "allOf": [ + { + "$ref": "#/definitions/domain.SessionQuery" + } + ] + } + } + }, + "domain.SessionQuery": { + "type": "object", + "properties": { + "createdAt": { + "description": "Фильтр по дате создания", + "allOf": [ + { + "$ref": "#/definitions/domain.DateFromToParams" + } + ] + }, + "expiredAt": { + "description": "Фильтр по дате протухания", + "allOf": [ + { + "$ref": "#/definitions/domain.DateFromToParams" + } + ] + }, + "id": { + "description": "Фильтр по идентификатору сессии", + "type": "integer" + }, + "status": { + "description": "Фильтр по статусам", + "type": "array", + "items": { + "type": "string" + } + }, + "userId": { + "description": "Фильтр по идентификаторам пользователей", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.SessionResponse": { + "type": "object", + "properties": { + "items": { + "description": "Список сессий", + "type": "array", + "items": { + "$ref": "#/definitions/domain.Session" + } + }, + "totalCount": { + "description": "Количество сессий", + "type": "integer" + } + } + }, + "domain.SetAuditEvent": { + "type": "object", + "properties": { + "enabled": { + "description": "Включено/выключено", + "type": "boolean" + }, + "event": { + "description": "Название события", + "type": "string" + } + } + }, + "domain.UIDesign": { + "type": "object", + "properties": { + "name": { + "description": "Название ui", + "type": "string" + }, + "primaryColor": { + "description": "Цвет в HEX", + "type": "string", + "example": "#ff4d4f" + } + } + }, + "domain.UiOauthSetting": { + "type": "object", + "properties": { + "loginUrl": { + "description": "URL для получения authCode для авторизации через OAuth", + "type": "string" + }, + "logoutUrl": { + "description": "URL для завершения сессии", + "type": "string" + } + } + }, + "domain.UpdateRoleRequest": { + "type": "object", + "properties": { + "changeMessage": { + "description": "Причина изменений", + "type": "string" + }, + "externalGroup": { + "description": "Внешнее название группы", + "type": "string" + }, + "id": { + "description": "Идентификатор роли", + "type": "integer" + }, + "name": { + "description": "Название роли", + "type": "string" + }, + "permissions": { + "description": "Набор прав", + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "domain.UpdateUserRequest": { + "type": "object", + "required": [ + "id" + ], + "properties": { + "blocked": { + "description": "Флаг блокировки", + "type": "boolean" + }, + "description": { + "description": "Описание", + "type": "string" + }, + "email": { + "description": "Электронный адрес", + "type": "string" + }, + "firstName": { + "description": "Имя", + "type": "string" + }, + "id": { + "description": "Идентификатор пользователя", + "type": "integer" + }, + "lastName": { + "description": "Фамилия", + "type": "string" + }, + "roles": { + "description": "Список идентификаторов ролей", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.User": { + "type": "object", + "properties": { + "blocked": { + "description": "Флаг блокировки", + "type": "boolean" + }, + "createdAt": { + "description": "Дата создания", + "type": "string" + }, + "description": { + "description": "Описание", + "type": "string" + }, + "email": { + "description": "Электронная почта", + "type": "string" + }, + "firstName": { + "description": "Имя", + "type": "string" + }, + "fullName": { + "description": "ФИО", + "type": "string" + }, + "id": { + "description": "Идентификатор пользователя", + "type": "integer", + "format": "int64" + }, + "lastName": { + "description": "Фамилия", + "type": "string" + }, + "lastSessionCreatedAt": { + "description": "Дата создания последней сессии", + "type": "string" + }, + "roles": { + "description": "Список идентификаторов ролей", + "type": "array", + "items": { + "type": "integer" + } + }, + "updatedAt": { + "description": "Дата обновлёния", + "type": "string" + } + } + }, + "domain.UserQuery": { + "type": "object", + "properties": { + "description": { + "description": "Фильтр по описанию", + "type": "string" + }, + "email": { + "description": "Фильтр по электроннйо почты", + "type": "string" + }, + "id": { + "description": "Фильтр по идентификатору пользователя", + "type": "integer" + }, + "lastSessionCreatedAt": { + "description": "Фильтр по дате создания последней сессии", + "allOf": [ + { + "$ref": "#/definitions/domain.DateFromToParams" + } + ] + }, + "roles": { + "description": "Фильтр по ролям", + "type": "array", + "items": { + "type": "integer" + } + }, + "userId": { + "description": "Фильтр по идентификаторам пользователя", + "type": "array", + "items": { + "type": "integer" + } + } + } + }, + "domain.UsersPageRequest": { + "type": "object", + "required": [ + "limit" + ], + "properties": { + "limit": { + "description": "Максимальное количество записей", + "type": "integer" + }, + "offset": { + "description": "Отступ для выборки", + "type": "integer", + "format": "int64" + }, + "order": { + "description": "Параметры сортировки", + "allOf": [ + { + "$ref": "#/definitions/domain.OrderParams" + } + ] + }, + "query": { + "description": "Параметры выборки", + "allOf": [ + { + "$ref": "#/definitions/domain.UserQuery" + } + ] + } + } + }, + "domain.UsersResponse": { + "type": "object", + "properties": { + "items": { + "description": "Список пользователей", + "type": "array", + "items": { + "$ref": "#/definitions/domain.User" + } + } + } + } + } +} \ No newline at end of file diff --git a/docs/swagger.yaml b/docs/swagger.yaml deleted file mode 100644 index 5a81c59..0000000 --- a/docs/swagger.yaml +++ /dev/null @@ -1,1314 +0,0 @@ -basePath: /api/admin -definitions: - apierrors.Error: - properties: - details: - additionalProperties: {} - type: object - errorCode: - type: integer - errorMessage: - type: string - type: object - conf.UIDesign: - properties: - name: - type: string - primaryColor: - type: string - type: object - domain.AdminUserShort: - properties: - email: - type: string - firstName: - type: string - fullName: - type: string - idleTimeoutMs: - type: integer - lastName: - type: string - permissions: - items: - type: string - type: array - role: - type: string - roleNames: - items: - type: string - type: array - roles: - items: - type: integer - type: array - required: - - email - type: object - domain.Audit: - properties: - createdAt: - type: string - id: - type: integer - message: - type: string - userId: - type: integer - type: object - domain.AuditEvent: - properties: - enabled: - type: boolean - event: - type: string - name: - type: string - type: object - domain.AuditPageRequest: - properties: - limit: - type: integer - offset: - type: integer - order: - $ref: '#/definitions/domain.OrderParams' - query: - $ref: '#/definitions/domain.AuditQuery' - required: - - limit - type: object - domain.AuditQuery: - properties: - createdAt: - $ref: '#/definitions/domain.DateFromToParams' - id: - type: integer - message: - type: string - userId: - items: - type: integer - type: array - type: object - domain.AuditResponse: - properties: - items: - items: - $ref: '#/definitions/domain.Audit' - type: array - totalCount: - type: integer - type: object - domain.ChangePasswordRequest: - properties: - newPassword: - type: string - oldPassword: - type: string - required: - - newPassword - - oldPassword - type: object - domain.CreateRoleRequest: - properties: - changeMessage: - type: string - externalGroup: - type: string - name: - type: string - permissions: - items: - type: string - type: array - type: object - domain.CreateUserRequest: - properties: - description: - type: string - email: - type: string - firstName: - type: string - lastName: - type: string - password: - type: string - roles: - items: - type: integer - type: array - required: - - email - - password - type: object - domain.DateFromToParams: - properties: - from: - type: string - to: - type: string - required: - - from - - to - type: object - domain.DeleteResponse: - properties: - deleted: - type: integer - type: object - domain.DeleteRoleRequest: - properties: - id: - type: integer - type: object - domain.GrpcError: - properties: - details: - items: {} - type: array - errorCode: - type: string - errorMessage: - type: string - type: object - domain.IdRequest: - properties: - userId: - type: integer - required: - - userId - type: object - domain.IdentitiesRequest: - properties: - ids: - items: - type: integer - type: array - required: - - ids - type: object - domain.LoginRequest: - properties: - email: - type: string - password: - type: string - required: - - email - - password - type: object - domain.LoginResponse: - properties: - expired: - type: string - headerName: - type: string - token: - type: string - type: object - domain.LoginSudirRequest: - properties: - authCode: - type: string - required: - - authCode - type: object - domain.LogoutRequest: - properties: - reason: - type: string - type: object - domain.OrderParams: - properties: - field: - type: string - type: - enum: - - asc - - desc - - ASC - - DESC - type: string - type: object - domain.Permission: - properties: - key: - type: string - name: - type: string - type: object - domain.RevokeRequest: - properties: - id: - type: integer - required: - - id - type: object - domain.Role: - properties: - changeMessage: - type: string - createdAt: - type: string - exclusive: - type: boolean - externalGroup: - type: string - id: - type: integer - immutable: - type: boolean - name: - type: string - permissions: - items: - type: string - type: array - updatedAt: - type: string - type: object - domain.SecureAuthRequest: - properties: - token: - type: string - type: object - domain.SecureAuthResponse: - properties: - adminId: - type: integer - authenticated: - type: boolean - errorReason: - type: string - type: object - domain.SecureAuthzRequest: - properties: - adminId: - type: integer - permission: - type: string - type: object - domain.SecureAuthzResponse: - properties: - authorized: - type: boolean - type: object - domain.Session: - properties: - createdAt: - type: string - expiredAt: - type: string - id: - type: integer - status: - type: string - userId: - type: integer - type: object - domain.SessionPageRequest: - properties: - limit: - type: integer - offset: - type: integer - order: - $ref: '#/definitions/domain.OrderParams' - query: - $ref: '#/definitions/domain.SessionQuery' - required: - - limit - type: object - domain.SessionQuery: - properties: - createdAt: - $ref: '#/definitions/domain.DateFromToParams' - expiredAt: - $ref: '#/definitions/domain.DateFromToParams' - id: - type: integer - status: - items: - type: string - type: array - userId: - items: - type: integer - type: array - type: object - domain.SessionResponse: - properties: - items: - items: - $ref: '#/definitions/domain.Session' - type: array - totalCount: - type: integer - type: object - domain.SetAuditEvent: - properties: - enabled: - type: boolean - event: - type: string - type: object - domain.UpdateRoleRequest: - properties: - changeMessage: - type: string - externalGroup: - type: string - id: - type: integer - name: - type: string - permissions: - items: - type: string - type: array - type: object - domain.UpdateUserRequest: - properties: - blocked: - type: boolean - description: - type: string - email: - type: string - firstName: - type: string - id: - type: integer - lastName: - type: string - roles: - items: - type: integer - type: array - required: - - id - type: object - domain.User: - properties: - blocked: - type: boolean - createdAt: - type: string - description: - type: string - email: - type: string - firstName: - type: string - fullName: - type: string - id: - type: integer - lastName: - type: string - lastSessionCreatedAt: - type: string - roles: - items: - type: integer - type: array - updatedAt: - type: string - type: object - domain.UserQuery: - properties: - description: - type: string - email: - type: string - id: - type: integer - lastSessionCreatedAt: - $ref: '#/definitions/domain.DateFromToParams' - roles: - items: - type: integer - type: array - userId: - items: - type: integer - type: array - type: object - domain.UsersPageRequest: - properties: - limit: - type: integer - offset: - type: integer - order: - $ref: '#/definitions/domain.OrderParams' - query: - $ref: '#/definitions/domain.UserQuery' - required: - - limit - type: object - domain.UsersResponse: - properties: - items: - items: - $ref: '#/definitions/domain.User' - type: array - type: object -host: localhost:9000 -info: - contact: {} - description: сервис управления администраторами - license: - name: GNU GPL v3.0 - title: msp-admin-service - version: 1.0.0 -paths: - /auth/login: - post: - consumes: - - application/json - description: Авторизация с получением токена администратора - parameters: - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.LoginRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.LoginResponse' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.GrpcError' - "401": - description: Данные для авторизации не верны - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Авторизация по логину и паролю - tags: - - auth - /auth/login_with_sudir: - post: - consumes: - - application/json - description: Авторизация с получением токена администратора - parameters: - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.LoginSudirRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.LoginResponse' - "401": - description: Некорректный код для авторизации - schema: - $ref: '#/definitions/domain.GrpcError' - "412": - description: Авторизация СУДИР не настроена на сервере - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Авторизация по авторизационному коду от СУДИР - tags: - - auth - /auth/logout: - post: - consumes: - - application/json - description: Выход из авторизованной сессии администрирования - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидный токен - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Выход из авторизованной сессии - tags: - - auth - /auth/logout_with_reason: - post: - consumes: - - application/json - description: Выход по бездействию из авторизованной сессии администрирования - parameters: - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.LogoutRequest' - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидный токен - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Выход по бездействию из авторизованной сессии - tags: - - auth - /log/all: - post: - consumes: - - application/json - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.AuditPageRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.AuditResponse' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Получение списка логов - tags: - - log - /log/events: - post: - consumes: - - application/json - description: Возвращает полный список доступных событий аудита - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.AuditResponse' - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/domain.AuditEvent' - type: array - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Получение списка логов - tags: - - log - /log/set_events: - post: - consumes: - - application/json - description: Всегда возвращает полный список доступных событий аудита - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.SetAuditEvent' - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Получение списка логов - tags: - - log - /role/all: - post: - consumes: - - application/json - description: Получить список ролей - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/domain.Role' - type: array - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Список ролей - tags: - - role - /role/create: - post: - consumes: - - application/json - description: Создать роль - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateRoleRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.User' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "409": - description: Роль с указанным именем уже существует - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Создать роль - tags: - - user - /role/delete: - post: - consumes: - - application/json - description: Удалить существующую роль - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.DeleteRoleRequest' - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Удалить роль - tags: - - role - /role/update: - post: - consumes: - - application/json - description: Обновить данные существующую роль - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.UpdateRoleRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.Role' - "404": - description: Роль с указанным id не существует - schema: - $ref: '#/definitions/domain.GrpcError' - "409": - description: Роль с указанным именем уже существует - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Обновить роль - tags: - - role - /secure/authenticate: - post: - consumes: - - application/json - description: Проверяет токен и возвращает идентификатор администратора - parameters: - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.SecureAuthRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.SecureAuthResponse' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Метод аутентификации токена - tags: - - secure - /secure/authorize: - post: - consumes: - - application/json - description: Проверяет наличие у администратора необходимого разрешения - parameters: - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.SecureAuthzRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.SecureAuthzResponse' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Метод авторизации для администратора - tags: - - secure - /session/all: - post: - consumes: - - application/json - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.SessionPageRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.SessionResponse' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Получение списка сессий - tags: - - session - /session/revoke: - post: - consumes: - - application/json - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.RevokeRequest' - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Отзыв сессии - tags: - - session - /user/block_user: - post: - consumes: - - application/json - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.IdRequest' - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Метод блокировки/разблокировки пользователя - tags: - - user - /user/change_password: - post: - consumes: - - application/json - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.ChangePasswordRequest' - produces: - - application/json - responses: - "200": - description: OK - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/apierrors.Error' - "500": - description: внутренняя ошибка - schema: - $ref: '#/definitions/apierrors.Error' - summary: Метод изменения пароля пользователя - tags: - - user - /user/create_user: - post: - consumes: - - application/json - description: Создать пользователя - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.CreateUserRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.User' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "409": - description: Пользователь с указанным email уже существует - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Создать пользователя - tags: - - user - /user/delete_user: - post: - consumes: - - application/json - description: Удалить существующего пользователя - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.IdentitiesRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.DeleteResponse' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Удалить пользователя - tags: - - user - /user/get_all_users: - post: - consumes: - - application/json - description: Получить список пользователей - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.UsersResponse' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Список пользователей - tags: - - user - /user/get_by_id: - post: - consumes: - - application/json - parameters: - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.IdRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.User' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Метод получения данных по пользователю - tags: - - user - /user/get_design: - post: - consumes: - - application/json - description: Получение внешнего вида (палитра и наименование) админ-интерфейса - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/conf.UIDesign' - "400": - description: Невалидный токен - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Получение внешнего вида - tags: - - user - /user/get_permissions: - post: - consumes: - - application/json - description: Получить все разрашения - produces: - - application/json - responses: - "200": - description: OK - schema: - items: - $ref: '#/definitions/domain.Permission' - type: array - summary: Получить все разрашения - tags: - - user - /user/get_profile: - post: - consumes: - - application/json - description: Получить данные профиля - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.AdminUserShort' - "400": - description: Невалидный токен - schema: - $ref: '#/definitions/domain.GrpcError' - "404": - description: Пользователя не существует - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Получить профиль - tags: - - user - /user/get_users: - post: - consumes: - - application/json - description: Получить список пользователей - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.UsersPageRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.UsersResponse' - "400": - description: Bad Request - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Список пользователей - tags: - - user - /user/update_user: - post: - consumes: - - application/json - description: Обновить данные существующего пользователя - parameters: - - description: Токен администратора - in: header - name: X-AUTH-ADMIN - required: true - type: string - - description: Тело запроса - in: body - name: body - required: true - schema: - $ref: '#/definitions/domain.UpdateUserRequest' - produces: - - application/json - responses: - "200": - description: OK - schema: - $ref: '#/definitions/domain.User' - "400": - description: Невалидное тело запроса - schema: - $ref: '#/definitions/domain.GrpcError' - "404": - description: Пользователь с указанным id не существует - schema: - $ref: '#/definitions/domain.GrpcError' - "409": - description: Пользователь с указанным email уже существует - schema: - $ref: '#/definitions/domain.GrpcError' - "500": - description: Internal Server Error - schema: - $ref: '#/definitions/domain.GrpcError' - summary: Обновить пользователя - tags: - - user -swagger: "2.0" diff --git a/domain/audit.go b/domain/audit.go index 9a4150e..85fdd77 100644 --- a/domain/audit.go +++ b/domain/audit.go @@ -5,38 +5,38 @@ import ( ) type Audit struct { - Id int - UserId int - Message string - CreatedAt time.Time + Id int // Идентификатор audit'а + UserId int // Идентификатор пользователя + Message string // Сообщение + CreatedAt time.Time // Дата события } type AuditResponse struct { - TotalCount int - Items []Audit + TotalCount int // Количество audit'ов + Items []Audit // Список audit'ов } type AuditPageRequest struct { LimitOffestParams - Order *OrderParams - Query *AuditQuery + Order *OrderParams // Параметры сортировки + Query *AuditQuery // Параметры выборки } type AuditQuery struct { - Id *int - UserId []int - Message *string - CreatedAt *DateFromToParams + Id *int // Фильтр по идентификатору audit + UserId []int // Фильтр по идентификатору пользователей + Message *string // Фильтр по сообщению + CreatedAt *DateFromToParams // Фильтр по дате } type SetAuditEvent struct { - Event string - Enabled bool + Event string // Название события + Enabled bool // Включено/выключено } type AuditEvent struct { - Event string - Name string + Event string // Название события + Name string // Enabled bool } diff --git a/domain/errors.go b/domain/errors.go index 8225069..58aef3e 100644 --- a/domain/errors.go +++ b/domain/errors.go @@ -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") @@ -23,6 +23,7 @@ var ( ErrUserIsBlocked = errors.New("user is blocked") ErrNoActionRequired = errors.New("no action required") ErrInvalidPassword = errors.New("invalid password") + ErrUnknownClient = errors.New("unknown client") ) type UnknownAuditEventError struct { diff --git a/domain/login.go b/domain/login.go index 1218ef8..a2cc1a3 100644 --- a/domain/login.go +++ b/domain/login.go @@ -6,21 +6,22 @@ const ( ) type LogoutRequest struct { - Reason string + Reason string // Причина выхода } type LoginRequest struct { - Email string `validate:"required"` - Password string ` validate:"required"` + Email string `validate:"required"` // Электронная почта + Password string ` validate:"required"` // Пароль } -type LoginSudirRequest struct { - AuthCode string `validate:"required"` +type LoginOauthRequest struct { + AuthCode string `validate:"required"` // Код для авторизации у OAuth-провайдера + ClientName string `validate:"required"` // Уникальное имя конфигурации клиента } // nolint:tagliatelle,godoclint type LoginResponse struct { - Token string - Expired string `json:",omitempty"` - HeaderName string + Token string // Токен + Expired string `json:",omitempty"` // Дата истечения токена + HeaderName string // Названия заголовка для передачи токена } diff --git a/domain/params.go b/domain/params.go index 4336376..6bc7d2f 100644 --- a/domain/params.go +++ b/domain/params.go @@ -8,16 +8,16 @@ const ( ) type LimitOffestParams struct { - Limit uint64 `validate:"required"` - Offset uint64 + Limit uint64 `validate:"required"` // Максимальное количество записей + Offset uint64 // Отступ для выборки } type OrderParams struct { - Field string - Type string `validate:"oneof=asc desc ASC DESC"` + Field string // Поле сортировки + Type string `validate:"oneof=asc desc ASC DESC"` // Порядок сортировки } type DateFromToParams struct { - From time.Time `validate:"required"` - To time.Time `validate:"required"` + From time.Time `validate:"required"` // Дата с + To time.Time `validate:"required"` // Дата до } diff --git a/domain/permission.go b/domain/permission.go index 64e5c16..d5dd232 100644 --- a/domain/permission.go +++ b/domain/permission.go @@ -1,6 +1,6 @@ package domain type Permission struct { - Key string - Name string + Key string // Ключ прав + Name string // Пользовательское название } diff --git a/domain/role.go b/domain/role.go index 3233a77..b45a821 100644 --- a/domain/role.go +++ b/domain/role.go @@ -5,32 +5,32 @@ import ( ) type Role struct { - Id int - Name string - ExternalGroup string - ChangeMessage string - Permissions []string + Id int // Идентификатор роли + Name string // Название роли + ExternalGroup string // Внешнее название группы + ChangeMessage string // Причина изменений + Permissions []string // Набор прав Immutable bool Exclusive bool - CreatedAt time.Time - UpdatedAt time.Time + CreatedAt time.Time // Дата создания + UpdatedAt time.Time // Дата обновления } type CreateRoleRequest struct { - Name string - ExternalGroup string - ChangeMessage string - Permissions []string + Name string // Название роли + ExternalGroup string // Внешнее название группы + ChangeMessage string // Причина изменений + Permissions []string // Набор прав } type UpdateRoleRequest struct { - Id int - Name string - ExternalGroup string - ChangeMessage string - Permissions []string + Id int // Идентификатор роли + Name string // Название роли + ExternalGroup string // Внешнее название группы + ChangeMessage string // Причина изменений + Permissions []string // Набор прав } type DeleteRoleRequest struct { - Id int + Id int // Идентификатор роли } diff --git a/domain/secure.go b/domain/secure.go index 3417866..ad1ea05 100644 --- a/domain/secure.go +++ b/domain/secure.go @@ -1,20 +1,20 @@ package domain type SecureAuthRequest struct { - Token string + Token string // Токен } type SecureAuthResponse struct { - Authenticated bool - ErrorReason string - AdminId int64 + Authenticated bool // Флаг успешной аутентикации + ErrorReason string // Причина ошибки + AdminId int64 // Идентификатор администратора } type SecureAuthzRequest struct { - AdminId int - Permission string + AdminId int // Идентификатор администратора + Permission string // Роль } type SecureAuthzResponse struct { - Authorized bool + Authorized bool // Флаг успешноЙ авторизации } diff --git a/domain/session.go b/domain/session.go index 549fb28..97248e0 100644 --- a/domain/session.go +++ b/domain/session.go @@ -5,33 +5,33 @@ import ( ) type Session struct { - Id int - UserId int - Status string - ExpiredAt time.Time - CreatedAt time.Time + Id int // Идентификатор сессии + UserId int // Идентификатор пользоватеккля + Status string // Статус сессии + ExpiredAt time.Time // Дата протухания сессии + CreatedAt time.Time // Дата создания сессии } type SessionPageRequest struct { LimitOffestParams - Order *OrderParams - Query *SessionQuery + Order *OrderParams // Параметры сортировки + Query *SessionQuery // Параметры выборки } type SessionQuery struct { - Id *int - UserId []int - Status []string - CreatedAt *DateFromToParams - ExpiredAt *DateFromToParams + Id *int // Фильтр по идентификатору сессии + UserId []int // Фильтр по идентификаторам пользователей + Status []string // Фильтр по статусам + CreatedAt *DateFromToParams // Фильтр по дате создания + ExpiredAt *DateFromToParams // Фильтр по дате протухания } type SessionResponse struct { - TotalCount int - Items []Session + TotalCount int // Количество сессий + Items []Session // Список сессий } type RevokeRequest struct { - Id int `validate:"required"` + Id int `validate:"required"` // Идентификатор сессии } diff --git a/domain/ui_design.go b/domain/ui_design.go new file mode 100644 index 0000000..e9e8ba9 --- /dev/null +++ b/domain/ui_design.go @@ -0,0 +1,6 @@ +package domain + +type UIDesign struct { + Name string // Название ui + PrimaryColor string `example:"#ff4d4f"` // Цвет в HEX +} diff --git a/domain/ui_settings.go b/domain/ui_settings.go new file mode 100644 index 0000000..b44046e --- /dev/null +++ b/domain/ui_settings.go @@ -0,0 +1,10 @@ +package domain + +type ClientNameRequest struct { + ClientName string `validate:"required"` +} + +type UiOauthSetting struct { + LoginUrl string // URL для получения authCode для авторизации через OAuth + LogoutUrl string // URL для завершения сессии +} diff --git a/domain/user.go b/domain/user.go index 23ed0d6..d3d20d1 100644 --- a/domain/user.go +++ b/domain/user.go @@ -5,83 +5,83 @@ import ( ) type User struct { - Id int64 - Roles []int - FirstName string - LastName string - FullName string - Email string - Description string - Blocked bool - LastSessionCreatedAt *time.Time - UpdatedAt time.Time - CreatedAt time.Time + Id int64 // Идентификатор пользователя + Roles []int // Список идентификаторов ролей + FirstName string // Имя + LastName string // Фамилия + FullName string // ФИО + Email string // Электронная почта + Description string // Описание + Blocked bool // Флаг блокировки + LastSessionCreatedAt *time.Time // Дата создания последней сессии + UpdatedAt time.Time // Дата обновлёния + CreatedAt time.Time // Дата создания } type UsersResponse struct { - Items []User + Items []User // Список пользователей } type UserQuery struct { - Id *int - UserId []int - Description *string - Email *string - Roles []int - LastSessionCreatedAt *DateFromToParams + Id *int // Фильтр по идентификатору пользователя + UserId []int // Фильтр по идентификаторам пользователя + Description *string // Фильтр по описанию + Email *string // Фильтр по электроннйо почты + Roles []int // Фильтр по ролям + LastSessionCreatedAt *DateFromToParams // Фильтр по дате создания последней сессии } type UsersPageRequest struct { LimitOffestParams - Order *OrderParams - Query *UserQuery + Order *OrderParams // Параметры сортировки + Query *UserQuery // Параметры выборки } type AdminUserShort struct { - FirstName string - LastName string - FullName string - Email string `validate:"required"` - Role string - Roles []int - RoleNames []string - Permissions []string - IdleTimeoutMs int + FirstName string // Имя + LastName string // Фамилия + FullName string // ФИО + Email string `validate:"required"` // Электронный адрес + Role string // Название роли + Roles []int // Список идентификаторов ролей + RoleNames []string // Список названия ролей + Permissions []string // Список прав + IdleTimeoutMs int // Время бездействия пользователя в мс } type CreateUserRequest struct { - Roles []int - FirstName string - LastName string - Email string `validate:"required"` - Password string `validate:"required"` - Description string + Roles []int // Список идентификаторов ролей + FirstName string // Имя + LastName string // Фамилия + Email string `validate:"required"` // Электронный адрес + Password string `validate:"required"` // Пароль + Description string // Описание } type UpdateUserRequest struct { - Id int64 `validate:"required"` - Roles []int - FirstName string - LastName string - Email string - Description string - Blocked bool + Id int64 `validate:"required"` // Идентификатор пользователя + Roles []int // Список идентификаторов ролей + FirstName string // Имя + LastName string // Фамилия + Email string // Электронный адрес + Description string // Описание + Blocked bool // Флаг блокировки } type DeleteResponse struct { - Deleted int + Deleted int // Количество удалённых УЗ } type IdentitiesRequest struct { - Ids []int64 `validate:"required"` + Ids []int64 `validate:"required"` // Список идентификаторов } type IdRequest struct { - UserId int `validate:"required"` + UserId int `validate:"required"` // Идентификато пользователя } type ChangePasswordRequest struct { - OldPassword string `validate:"required"` - NewPassword string `validate:"required"` + OldPassword string `validate:"required"` // Старый пароль + NewPassword string `validate:"required"` // Новый пароль } diff --git a/entity/sudir.go b/entity/oauth.go similarity index 73% rename from entity/sudir.go rename to entity/oauth.go index 6909fd8..a091832 100644 --- a/entity/sudir.go +++ b/entity/oauth.go @@ -4,19 +4,26 @@ import ( "fmt" ) +type ClientSetting struct { + AuthCode string + ClientId string + ClientSecret string + RedirectURI string +} + // 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"` @@ -27,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"` diff --git a/entity/user.go b/entity/user.go index 6f5fe08..845de4a 100644 --- a/entity/user.go +++ b/entity/user.go @@ -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 diff --git a/go.mod b/go.mod index 32b9c30..93e3634 100644 --- a/go.mod +++ b/go.mod @@ -1,84 +1,83 @@ -module msp-admin-service +module isp-admin-service -go 1.26 +go 1.26.0 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.71.1 + 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.82.1 + 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.2.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.13 // indirect - github.com/getsentry/sentry-go v0.47.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/gabriel-vasile/mimetype v1.4.15 // 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.0 // 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.4.0 // indirect + github.com/leodido/go-urn v1.5.0 // indirect github.com/mailru/easyjson v0.9.2 // indirect github.com/mfridman/interpolate v0.0.2 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect 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.2 // indirect - github.com/prometheus/client_golang v1.23.2 // 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 - github.com/prometheus/common v0.69.0 // indirect + github.com/prometheus/common v0.70.1 // indirect github.com/prometheus/procfs v0.21.1 // indirect github.com/robfig/cron/v3 v3.0.1 // indirect - github.com/sethvargo/go-retry v0.3.0 // indirect + github.com/sethvargo/go-retry v0.4.0 // indirect github.com/txix-open/bellows v1.2.0 // indirect - github.com/txix-open/etp/v4 v4.1.1 // indirect + github.com/txix-open/etp/v4 v4.1.3 // indirect github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect 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/proto/otlp v1.10.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-20260630182238-925bb5da69e7 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df // 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 ) diff --git a/go.sum b/go.sum index 72987bb..bfab8b8 100644 --- a/go.sum +++ b/go.sum @@ -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.2.0 h1:4EFcvK1kD4jyj6YqNK6skK6w+y7FHHBR+XBCtxwu/6g= -github.com/buger/jsonparser v1.2.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,23 +19,21 @@ 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.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= -github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= -github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM= -github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= -github.com/getsentry/sentry-go v0.47.0 h1:AnSMSyrYA5qZCIN/2xpgAAwv63sVULV+vBq37ajouc8= -github.com/getsentry/sentry-go v0.47.0/go.mod h1:h+b4VHpKnK7aUXB5wc+KDnPgp9ZtfliRD4eV85FbiSA= +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.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.9.0 h1:a4HXLwueuTCtgF93VpUsl8Zd2nG1VH2SgNWDPVEBg5U= -github.com/go-faker/faker/v4 v4.9.0/go.mod h1:u1dIRP5neLB6kTzgyVjdBOV5R1uP7BdxkcWk7tiKQXk= +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.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +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= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= @@ -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.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ= -github.com/klauspost/compress v1.19.0/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= @@ -86,14 +84,14 @@ github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 h1:SOEGU9fKiNWd/HOJuq github.com/lann/builder v0.0.0-20180802200727-47ae307949d0/go.mod h1:dXGbAdH5GtBTC4WfIxhKZfyBF/HBFgRZSWwZ9g/He9o= github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 h1:P6pPBnrTSX3DEVR4fDembhRWSsG5rVo6hYhAB/ADZrk= github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0/go.mod h1:vmVJ0l/dxyfGW6FmdpVm2joNMFikkuWg0EoCKLGUMNw= -github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= -github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= +github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M= github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU= -github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs= -github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ= +github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= @@ -114,28 +112,26 @@ 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.2 h1:FjKNzcmMdGrQlSIu5alMSmakQtJFBgtw+A0bb1p/LC8= -github.com/pressly/goose/v3 v3.27.2/go.mod h1:qWW+/8dkVtJYjJrbIpwD5xxnEJTUKvxkQ9JKQp9LaIM= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +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= +github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.69.0 h1:OA85nJQS/T/MaYh/Q2CcgDKSGWqNIgrBDvDH85CuiNk= -github.com/prometheus/common v0.69.0/go.mod h1:ZzL3f6u94qUxh9p+tJTrF+FvBS1XXbbRAZCQkytAL0Y= +github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= +github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= github.com/prometheus/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.12.0 h1:V0v14Iqfs+MwHWihJt/nGS5Ulu0vw572b2Co3mwunkI= -github.com/rabbitmq/amqp091-go v1.12.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= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE= -github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas= +github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw= +github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -147,18 +143,18 @@ 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= github.com/txix-open/bgjob v1.6.0/go.mod h1:aKbwpVclWmq82s7fchazp099yWjEpVKFkxT85i4hARM= -github.com/txix-open/etp/v4 v4.1.1 h1:Yna+0mw/kQZP7Rl6QI4spCrO6qgO8ZhP8PjHlJj2lTU= -github.com/txix-open/etp/v4 v4.1.1/go.mod h1:9GK+Aje8BmLFq8Hk4j6Qb976LdU9WECCWAuLK1vAKgM= +github.com/txix-open/etp/v4 v4.1.3 h1:u9ZyU2yKGgoQ1/DSaElhazWm8xASdqGEdWjoJ2xQlfo= +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.71.1 h1:MNSuHy/HEvy7dKPQXkM+dgQpShDhcv1Sq1kLgep2LaA= -github.com/txix-open/isp-kit v1.71.1/go.mod h1:j2sj86byoKllCs+DaRWwg56NgcL2omr/bUzmU7+AF74= +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,26 +170,26 @@ github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17 github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= -go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.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/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g= -go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk= +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= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -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-20260630182238-925bb5da69e7 h1:jQ9p21COKWjP3VwuFrNRiiOTMh3mPpN45R7SLrH/HUU= -google.golang.org/genproto/googleapis/api v0.0.0-20260630182238-925bb5da69e7/go.mod h1:KqHwBx2upmfa1XSi1WuRvC+2VGCLtooKkfmyvRbUmqA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df h1:O3ig1i5WDDzsVzRp+cCdgelT9vXnlnOFdlEeFtL4HCc= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260724162435-b2f20204f0df/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE= -google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA= -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= @@ -232,11 +228,11 @@ gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYs gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA= -modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8= +modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws= +modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4= modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= -modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M= -modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s= +modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog= +modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw= diff --git a/main.go b/main.go index 5214e5f..e04beb6 100644 --- a/main.go +++ b/main.go @@ -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 сервис управления администраторами @@ -21,10 +21,9 @@ var version = "1.0.0" // @host localhost:9000 // @BasePath /api/admin -//go:generate swag init --parseDependency -//go:generate rm -f docs/swagger.json docs/docs.go +//go:generate swag init -pd -ot json -eot json func main() { - boot := bootstrap.New(version, conf.Remote{}, routes.EndpointDescriptors(), cluster.GrpcTransport) + boot := bootstrap.New(version, conf.Remote{}, cluster.Endpoints(routes.EndpointDescriptors()), cluster.GrpcTransport) app := boot.App logger := app.Logger() diff --git a/migrations/20260903115446_rename_users_sudir_user_id.sql b/migrations/20260903115446_rename_users_sudir_user_id.sql new file mode 100644 index 0000000..76f5dba --- /dev/null +++ b/migrations/20260903115446_rename_users_sudir_user_id.sql @@ -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; diff --git a/repository/audit.go b/repository/audit.go index 019fdb5..285be90 100644 --- a/repository/audit.go +++ b/repository/audit.go @@ -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" ) diff --git a/repository/audit_event.go b/repository/audit_event.go index f32ee5a..eb5c658 100644 --- a/repository/audit_event.go +++ b/repository/audit_event.go @@ -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" ) diff --git a/repository/oauth.go b/repository/oauth.go new file mode 100644 index 0000000..b481a96 --- /dev/null +++ b/repository/oauth.go @@ -0,0 +1,69 @@ +package repository + +import ( + "context" + "fmt" + + "isp-admin-service/entity" + + "github.com/txix-open/isp-kit/errors" + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/metrics/http_metrics" +) + +//nolint:gosec +const ( + getTokenEndpoint = "/oauth/te" + getUserEndpoint = "/oauth/me" +) + +type Oauth struct { + cli *httpcli.Client +} + +func NewOauth(cli *httpcli.Client) Oauth { + return Oauth{ + cli: cli, + } +} + +func (s Oauth) GetToken(ctx context.Context, clientSetting entity.ClientSetting) (*entity.OauthTokenResponse, error) { + ctx = http_metrics.ClientEndpointToContext(ctx, getTokenEndpoint) + + response := entity.OauthTokenResponse{} + err := s.cli.Post(getTokenEndpoint). + BasicAuth(httpcli.BasicAuth{ + Username: clientSetting.ClientId, + Password: clientSetting.ClientSecret, + }). + Header("Content-Type", "application/x-www-form-urlencoded"). + QueryParams(map[string]any{ + "grant_type": "authorization_code", + "code": clientSetting.AuthCode, + "redirect_uri": clientSetting.RedirectURI, + }). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "call POST: '%s'", getTokenEndpoint) + } + + return &response, nil +} + +func (s Oauth) GetUser(ctx context.Context, accessToken string) (*entity.OauthUserResponse, error) { + ctx = http_metrics.ClientEndpointToContext(ctx, getUserEndpoint) + + response := entity.OauthUserResponse{} + err := s.cli.Get(getUserEndpoint). + Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)). + JsonResponseBody(&response). + StatusCodeToError(). + DoWithoutResponse(ctx) + if err != nil { + return nil, errors.WithMessagef(err, "call GET: '%s'", getUserEndpoint) + } + + return &response, nil +} diff --git a/repository/role.go b/repository/role.go index b81f22d..2cb0f85 100644 --- a/repository/role.go +++ b/repository/role.go @@ -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 { diff --git a/repository/sudir.go b/repository/sudir.go deleted file mode 100644 index ecb6b7b..0000000 --- a/repository/sudir.go +++ /dev/null @@ -1,78 +0,0 @@ -package repository - -import ( - "context" - "fmt" - "net/url" - - "github.com/pkg/errors" - "github.com/txix-open/isp-kit/http/httpcli" - "github.com/txix-open/isp-kit/metrics/http_metrics" - "msp-admin-service/conf" - "msp-admin-service/entity" -) - -type Sudir struct { - httpCli *httpcli.Client - cfg *conf.SudirAuth -} - -func NewSudir(httpCli *httpcli.Client, cfg *conf.SudirAuth) Sudir { - return Sudir{ - httpCli: httpCli, - cfg: cfg, - } -} - -func (s Sudir) GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error) { - urlString, err := url.JoinPath(s.cfg.Host, "/oauth/te") - if err != nil { - return nil, errors.WithMessage(err, "build url") - } - - ctx = http_metrics.ClientEndpointToContext(ctx, urlString) - - response := entity.SudirTokenResponse{} - err = s.httpCli.Post(urlString). - BasicAuth(httpcli.BasicAuth{ - Username: s.cfg.ClientId, - Password: s.cfg.ClientSecret, - }). - Header("Content-Type", "application/x-www-form-urlencoded"). - QueryParams(map[string]any{ - "grant_type": "authorization_code", - "code": authCode, - "redirect_uri": s.cfg.RedirectURI, - }). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - - if err != nil { - return nil, errors.WithMessage(err, "http request") - } - - return &response, nil -} - -func (s Sudir) GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) { - urlString, err := url.JoinPath(s.cfg.Host, "/oauth/me") - if err != nil { - return nil, errors.WithMessage(err, "build url") - } - - ctx = http_metrics.ClientEndpointToContext(ctx, urlString) - - response := entity.SudirUserResponse{} - err = s.httpCli. - Get(urlString). - Header("Authorization", fmt.Sprintf("Bearer %s", accessToken)). - JsonResponseBody(&response). - StatusCodeToError(). - DoWithoutResponse(ctx) - if err != nil { - return nil, errors.WithMessage(err, "http request") - } - - return &response, nil -} diff --git a/repository/token.go b/repository/token.go index 3dea075..f7e6e4f 100644 --- a/repository/token.go +++ b/repository/token.go @@ -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" ) diff --git a/repository/user.go b/repository/user.go index 85365af..e44d7a5 100644 --- a/repository/user.go +++ b/repository/user.go @@ -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") diff --git a/repository/user_role.go b/repository/user_role.go index 01c3543..8035c72 100644 --- a/repository/user_role.go +++ b/repository/user_role.go @@ -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 { diff --git a/routes/routes.go b/routes/routes.go index 913615c..54f2e71 100644 --- a/routes/routes.go +++ b/routes/routes.go @@ -1,9 +1,11 @@ package routes import ( - "msp-admin-service/controller" + "isp-admin-service/controller" + "isp-admin-service/docs" "github.com/txix-open/isp-kit/cluster" + "github.com/txix-open/isp-kit/common_endpoints" "github.com/txix-open/isp-kit/grpc" "github.com/txix-open/isp-kit/grpc/endpoint" "github.com/txix-open/isp-kit/grpc/isp" @@ -18,10 +20,14 @@ type Controllers struct { Audit controller.Audit Role controller.Role Permissions controller.Permissions + UiSettings controller.UiSettings } func EndpointDescriptors() []cluster.EndpointDescriptor { - return endpointDescriptors(Controllers{}) + return concatEndpoints( + endpointDescriptors(Controllers{}), + commonEndpoints(), + ) } func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { // nolint:ireturn @@ -29,6 +35,9 @@ func Handler(wrapper endpoint.Wrapper, c Controllers) isp.BackendServiceServer { for _, descriptor := range endpointDescriptors(c) { muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) } + for _, descriptor := range commonEndpoints() { + muxer.Handle(descriptor.Path, wrapper.Endpoint(descriptor.Handler)) + } return muxer } @@ -41,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", @@ -179,5 +188,25 @@ func endpointDescriptors(c Controllers) []cluster.EndpointDescriptor { Inner: true, Handler: c.Secure.Authorize, }, + { + Path: "admin/ui_settings/oauth", + Inner: false, + Handler: c.UiSettings.OauthSettings, + }, } } + +func commonEndpoints() []cluster.EndpointDescriptor { + return common_endpoints.CommonEndpoints( + "isp-admin-service", + common_endpoints.WithSwaggerEndpoint(docs.SwaggerJson), + ) +} + +func concatEndpoints(endpoints ...[]cluster.EndpointDescriptor) []cluster.EndpointDescriptor { + var result []cluster.EndpointDescriptor + for _, desc := range endpoints { + result = append(result, desc...) + } + return result +} diff --git a/service/audit.go b/service/audit.go index 67df535..b175c1f 100644 --- a/service/audit.go +++ b/service/audit.go @@ -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" ) diff --git a/service/auth.go b/service/auth.go index 2160c3c..264fdda 100644 --- a/service/auth.go +++ b/service/auth.go @@ -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, authCode string, 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.AuthCode, 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, diff --git a/service/delete_old_audit_worker/init.go b/service/delete_old_audit_worker/init.go index 506a782..29d1d01 100644 --- a/service/delete_old_audit_worker/init.go +++ b/service/delete_old_audit_worker/init.go @@ -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 ( diff --git a/service/delete_old_audit_worker/service.go b/service/delete_old_audit_worker/service.go index 0903636..fa9da0f 100644 --- a/service/delete_old_audit_worker/service.go +++ b/service/delete_old_audit_worker/service.go @@ -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" ) diff --git a/service/inactive_worker/init.go b/service/inactive_worker/init.go index 4d5d90d..5f9aec7 100644 --- a/service/inactive_worker/init.go +++ b/service/inactive_worker/init.go @@ -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 ( diff --git a/service/inactive_worker/service.go b/service/inactive_worker/service.go index ecad1f8..2bcbeaa 100644 --- a/service/inactive_worker/service.go +++ b/service/inactive_worker/service.go @@ -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" ) diff --git a/service/oauth.go b/service/oauth.go new file mode 100644 index 0000000..c052801 --- /dev/null +++ b/service/oauth.go @@ -0,0 +1,99 @@ +package service + +import ( + "context" + + "isp-admin-service/conf" + "isp-admin-service/domain" + "isp-admin-service/entity" + + "github.com/txix-open/isp-kit/errors" +) + +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 { + GetRolesByExternalGroup(ctx context.Context, groups []string) ([]entity.Role, error) + InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) +} + +type Oauth struct { + oauthRepo oauthRepo + clientSettings map[string]conf.OauthClientConfig +} + +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 Oauth{}, errors.Errorf("client setting [%d] has non-unique client name", i) + } + clientSettings[setting.ClientName] = setting + } + + return Oauth{ + oauthRepo: oauthRepo, + clientSettings: clientSettings, + }, nil +} + +func (s Oauth) Authenticate(ctx context.Context, req domain.LoginOauthRequest, roleRepo roleRepo) (*entity.OauthUser, error) { + if len(s.clientSettings) == 0 { + return nil, domain.ErrOauthIsMissed + } + + setting, ok := s.clientSettings[req.ClientName] + if !ok { + return nil, domain.ErrUnauthenticated + } + + creds := entity.ClientSetting{ + AuthCode: req.AuthCode, + ClientId: setting.ClientId, + ClientSecret: setting.ClientSecret, + RedirectURI: setting.RedirectURI, + } + tokenResponse, err := s.oauthRepo.GetToken(ctx, creds) + switch { + case err != nil: + return nil, errors.WithMessage(err, "get token") + case tokenResponse.OauthAuthError != nil: + return nil, errors.WithMessage(tokenResponse.OauthAuthError, "get token") + } + + user, err := s.oauthRepo.GetUser(ctx, tokenResponse.AccessToken) + switch { + case err != nil: + return nil, errors.WithMessage(err, "get user") + case user.OauthAuthError != nil: + return nil, errors.WithMessage(user.OauthAuthError, "get user") + } + email := user.Email + if email == "" { + email = user.Sub + } + + rolesIds := make([]int, 0) + if len(user.Groups) > 0 { + roles, err := roleRepo.GetRolesByExternalGroup(ctx, user.Groups) + if err != nil { + return nil, errors.WithMessage(err, "get roles by external groups") + } + for _, role := range roles { + rolesIds = append(rolesIds, role.Id) + } + } + + return &entity.OauthUser{ + RoleIds: rolesIds, + OauthUserId: user.Sub, + FirstName: user.GivenName, + LastName: user.FamilyName, + FullName: user.Name, + Email: email, + }, nil +} diff --git a/service/permission.go b/service/permission.go index a667fd0..1d2a79d 100644 --- a/service/permission.go +++ b/service/permission.go @@ -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 { diff --git a/service/role.go b/service/role.go index 1740a5f..517cf60 100644 --- a/service/role.go +++ b/service/role.go @@ -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 { diff --git a/service/secure/service.go b/service/secure/service.go index 81165d9..6072db3 100644 --- a/service/secure/service.go +++ b/service/secure/service.go @@ -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 { diff --git a/service/session_worker/init.go b/service/session_worker/init.go index a1c7123..e2806fc 100644 --- a/service/session_worker/init.go +++ b/service/session_worker/init.go @@ -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 ( diff --git a/service/session_worker/service.go b/service/session_worker/service.go index 68ccc06..f8e9d51 100644 --- a/service/session_worker/service.go +++ b/service/session_worker/service.go @@ -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" ) diff --git a/service/sudir.go b/service/sudir.go deleted file mode 100644 index d384b1e..0000000 --- a/service/sudir.go +++ /dev/null @@ -1,79 +0,0 @@ -package service - -import ( - "context" - - "msp-admin-service/conf" - "msp-admin-service/domain" - "msp-admin-service/entity" - - "github.com/pkg/errors" -) - -type sudirRepo interface { - GetToken(ctx context.Context, authCode string) (*entity.SudirTokenResponse, error) - GetUser(ctx context.Context, accessToken string) (*entity.SudirUserResponse, error) -} - -type roleRepo interface { - GetRolesByExternalGroup(ctx context.Context, groups []string) ([]entity.Role, error) - InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) -} - -type Sudir struct { - cfg *conf.SudirAuth - sudirRepo sudirRepo -} - -func NewSudir(cfg *conf.SudirAuth, sudirRepo sudirRepo) Sudir { - return Sudir{ - cfg: cfg, - sudirRepo: sudirRepo, - } -} - -func (s Sudir) Authenticate(ctx context.Context, authCode string, roleRepo roleRepo) (*entity.SudirUser, error) { - if s.cfg == nil { - return nil, domain.ErrSudirAuthIsMissed - } - - tokenResponse, err := s.sudirRepo.GetToken(ctx, authCode) - switch { - case err != nil: - return nil, errors.WithMessage(err, "get token") - case tokenResponse.SudirAuthError != nil: - return nil, errors.WithMessage(tokenResponse.SudirAuthError, "get token") - } - - user, err := s.sudirRepo.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") - } - email := user.Email - if email == "" { - email = user.Sub - } - - rolesIds := make([]int, 0) - if len(user.Groups) > 0 { - roles, err := roleRepo.GetRolesByExternalGroup(ctx, user.Groups) - if err != nil { - return nil, errors.WithMessage(err, "get roles by external groups") - } - for _, role := range roles { - rolesIds = append(rolesIds, role.Id) - } - } - - return &entity.SudirUser{ - RoleIds: rolesIds, - SudirUserId: user.Sub, - FirstName: user.GivenName, - LastName: user.FamilyName, - FullName: user.Name, - Email: email, - }, nil -} diff --git a/service/token.go b/service/token.go index f853472..0d92752 100644 --- a/service/token.go +++ b/service/token.go @@ -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" ) diff --git a/service/ui_settings.go b/service/ui_settings.go new file mode 100644 index 0000000..379fc54 --- /dev/null +++ b/service/ui_settings.go @@ -0,0 +1,80 @@ +package service + +import ( + "context" + "isp-admin-service/conf" + "isp-admin-service/domain" + "net/url" + + "github.com/txix-open/isp-kit/errors" +) + +type UiSettings struct { + oauthBaseUrl string + settings map[string]conf.OauthClientConfig +} + +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 + } + settingsMap[setting.ClientName] = setting + } + return UiSettings{ + oauthBaseUrl: oauthBaseUrl, + settings: settingsMap, + } +} + +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 + } + + loginUrl, err := s.buildUrl( + setting.UiSetting.LoginEndpoint, + map[string]string{ + "client_id": setting.ClientId, + "redirect_uri": setting.RedirectURI, + }) + if err != nil { + return nil, errors.Errorf("build url for login: %w", err) + } + + logoutUrl, err := s.buildUrl(setting.UiSetting.LogoutEndpoint, nil) + if err != nil { + return nil, errors.Errorf("build url for logout: %w", err) + } + return &domain.UiOauthSetting{ + LoginUrl: loginUrl, + LogoutUrl: logoutUrl, + }, nil +} + +func (s UiSettings) buildUrl(methodPath string, additionalQuery map[string]string) (string, error) { + method, err := url.Parse(methodPath) + if err != nil { + return "", errors.Errorf("parse method path") + } + + joined, err := url.JoinPath(s.oauthBaseUrl, method.Path) + if err != nil { + return "", errors.Errorf("join method path and baseUrl") + } + + u, err := url.Parse(joined) + if err != nil { + return "", errors.Errorf("parse joined") + } + + q := method.Query() + for k, v := range additionalQuery { + q.Set(k, v) + } + + u.RawQuery = q.Encode() + return u.String(), nil +} diff --git a/service/user.go b/service/user.go index 430a25b..c8a0712 100644 --- a/service/user.go +++ b/service/user.go @@ -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 } } diff --git a/tests/audit_test.go b/tests/audit_test.go index 1adfeb0..b6f7556 100644 --- a/tests/audit_test.go +++ b/tests/audit_test.go @@ -1,15 +1,14 @@ package tests_test import ( - "context" "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,10 +34,10 @@ type AuditSuite struct { grpcCli *client.Client } -func (t *AuditSuite) SetupTest() { - testInstance, _ := test.New(t.T()) - t.test = testInstance - t.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) +func (s *AuditSuite) SetupTest() { + testInstance, _ := test.New(s.T()) + s.test = testInstance + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) remote := conf.Remote{ Audit: conf.Audit{ @@ -71,26 +70,26 @@ func (t *AuditSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - cfg := assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db). - Config(context.Background(), remote, time.Minute) - - t.insertAuditLogs() + cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) + s.insertAuditLogs() server, apiCli := grpct.TestServer(testInstance, cfg.Handler) - t.grpcCli = apiCli + s.grpcCli = apiCli testInstance.T().Cleanup(func() { server.Shutdown() }) } -func (t *AuditSuite) Test_Events_DefaultEvents() { +func (s *AuditSuite) Test_Events_DefaultEvents() { response := make([]domain.AuditEvent, 0) - err := t.grpcCli. + err := s.grpcCli. Invoke("admin/log/events"). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) expectedEventList := map[string]string{ entity.EventSuccessLogin: "успешный вход", @@ -102,16 +101,16 @@ func (t *AuditSuite) Test_Events_DefaultEvents() { } for _, event := range response { name, found := expectedEventList[event.Event] - t.Require().Equal(found, event.Enabled) - t.Require().Equal(name, event.Name) + s.Require().Equal(found, event.Enabled) + s.Require().Equal(name, event.Name) delete(expectedEventList, event.Event) } - t.Require().Empty(expectedEventList) + s.Require().Empty(expectedEventList) } -func (t *AuditSuite) Test_Events_SortEvents() { - eventRep := repository.NewAuditEvent(t.db) - err := eventRep.Upsert(context.Background(), []entity.AuditEvent{ +func (s *AuditSuite) Test_Events_SortEvents() { + eventRep := repository.NewAuditEvent(s.db) + err := eventRep.Upsert(s.T().Context(), []entity.AuditEvent{ {Event: "новый#1", Enable: false}, {Event: entity.EventSuccessLogin, Enable: false}, {Event: entity.EventErrorLogin, Enable: true}, @@ -121,33 +120,33 @@ func (t *AuditSuite) Test_Events_SortEvents() { {Event: entity.EventUserBlocked, Enable: true}, {Event: "новый#2", Enable: false}, }) - t.Require().NoError(err) + s.Require().NoError(err) response := make([]domain.AuditEvent, 0) - err = t.grpcCli. + err = s.grpcCli. Invoke("admin/log/events"). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) expectedSort := []bool{ true, true, true, true, false, false, false, false, } - t.Require().Equal(len(expectedSort), len(response)) // nolint:testifylint + s.Require().Equal(len(expectedSort), len(response)) // nolint:testifylint for i, event := range response { - t.Require().Equal(expectedSort[i], event.Enabled) + s.Require().Equal(expectedSort[i], event.Enabled) } } -func (t *AuditSuite) Test_SetEvents_HappyPath() { - err := t.grpcCli. +func (s *AuditSuite) Test_SetEvents_HappyPath() { + err := s.grpcCli. Invoke("admin/log/set_events"). JsonRequestBody([]domain.SetAuditEvent{ {Event: entity.EventUserChanged, Enabled: true}, {Event: entity.EventRoleChanged, Enabled: false}, }). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) expectedEventList := map[string]bool{ entity.EventSuccessLogin: true, @@ -157,33 +156,32 @@ func (t *AuditSuite) Test_SetEvents_HappyPath() { entity.EventUserChanged: true, entity.EventUserBlocked: true, } - eventRep := repository.NewAuditEvent(t.db) - eventList, err := eventRep.All(context.Background()) - t.Require().NoError(err) + eventRep := repository.NewAuditEvent(s.db) + eventList, err := eventRep.All(s.T().Context()) + s.Require().NoError(err) for _, event := range eventList { enable, found := expectedEventList[event.Event] - t.Require().True(found) - t.Require().Equal(enable, event.Enable) + s.Require().True(found) + s.Require().Equal(enable, event.Enable) delete(expectedEventList, event.Event) } - t.Require().Empty(expectedEventList) + s.Require().Empty(expectedEventList) } -func (t *AuditSuite) Test_SetEvents_InvalidEvent() { - err := t.grpcCli. - Invoke("admin/log/set_events"). +func (s *AuditSuite) Test_SetEvents_InvalidEvent() { + err := s.grpcCli.Invoke("admin/log/set_events"). JsonRequestBody([]domain.SetAuditEvent{ {Event: entity.EventUserChanged, Enabled: true}, {Event: "новый#2", Enabled: false}, }). - Do(context.Background()) - t.Require().Error(err) - s, isStatus := status.FromError(err) - t.Require().True(isStatus) - t.Require().Equal(codes.InvalidArgument, s.Code()) + Do(s.T().Context()) + s.Require().Error(err) + status, isStatus := status.FromError(err) + s.Require().True(isStatus) + s.Require().Equal(codes.InvalidArgument, status.Code()) } -func (t *AuditSuite) Test_All_Logs() { +func (s *AuditSuite) Test_All_Logs() { request := domain.AuditPageRequest{ LimitOffestParams: domain.LimitOffestParams{ Limit: 3, @@ -196,17 +194,17 @@ func (t *AuditSuite) Test_All_Logs() { } var response *domain.AuditResponse - err := t.grpcCli. + err := s.grpcCli. Invoke("admin/log/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 3) - t.Require().EqualValues(5, response.Items[0].UserId) - t.Require().EqualValues(4, response.Items[1].UserId) - t.Require().EqualValues(3, response.Items[2].UserId) + s.Require().Len(response.Items, 3) + s.Require().EqualValues(5, response.Items[0].UserId) + s.Require().EqualValues(4, response.Items[1].UserId) + s.Require().EqualValues(3, response.Items[2].UserId) request.Query = &domain.AuditQuery{ Message: new("Выход"), @@ -214,25 +212,25 @@ func (t *AuditSuite) Test_All_Logs() { request.Limit = 10 request.Offset = 0 - err = t.grpcCli. + err = s.grpcCli. Invoke("admin/log/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 6) - t.Require().EqualValues(6, response.TotalCount) - t.Require().EqualValues(10, response.Items[0].UserId) - t.Require().EqualValues(9, response.Items[1].UserId) - t.Require().EqualValues(8, response.Items[2].UserId) - t.Require().EqualValues(7, response.Items[3].UserId) - t.Require().EqualValues(6, response.Items[4].UserId) - t.Require().EqualValues(5, response.Items[5].UserId) + s.Require().Len(response.Items, 6) + s.Require().EqualValues(6, response.TotalCount) + s.Require().EqualValues(10, response.Items[0].UserId) + s.Require().EqualValues(9, response.Items[1].UserId) + s.Require().EqualValues(8, response.Items[2].UserId) + s.Require().EqualValues(7, response.Items[3].UserId) + s.Require().EqualValues(6, response.Items[4].UserId) + s.Require().EqualValues(5, response.Items[5].UserId) } -func (t *AuditSuite) insertAuditLogs() { - t.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event) +func (s *AuditSuite) insertAuditLogs() { + s.db.Must().Exec(`INSERT INTO audit (user_id, message, created_at, event) VALUES (1, 'Успешный вход', NOW(), 'success_login'), (2, 'Успешный вход', NOW(), 'success_login'), (3, 'Неуспешный вход', NOW(), 'unsuccess_login'), diff --git a/tests/auth_test.go b/tests/auth_test.go index ca0a229..7ccbc01 100644 --- a/tests/auth_test.go +++ b/tests/auth_test.go @@ -1,7 +1,6 @@ package tests_test import ( - "context" "fmt" "net/http" "net/http/httptest" @@ -11,13 +10,14 @@ 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" "github.com/stretchr/testify/suite" @@ -40,27 +40,35 @@ func TestAuthTestSuite(t *testing.T) { type AuthTestSuite struct { suite.Suite - test *test.Test - db *dbt.TestDb - grpcCli *client.Client - httpCli *httpcli.Client + test *test.Test + db *dbt.TestDb + grpcCli *client.Client + 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.httpCli = httpcli.New() + s.oauthCli = httpcli.New() + s.oauthClientName = fake.It[string]() - mocksrv, host := s.initMockSudir() - sudirHost, _ := url.JoinPath(host, "/blitz/") + mocksrv, host := s.initMockOauth() + oauthHost, _ := url.JoinPath(host, "/blitz/") + s.oauthCli.GlobalRequestConfig().BaseUrl = oauthHost remote := conf.Remote{ - SudirAuth: &conf.SudirAuth{ - ClientId: "admin", - ClientSecret: "admin", - Host: sudirHost, - RedirectURI: "http://localhost", + Oauth: &conf.Oauth{ + Host: host, + Clients: []conf.OauthClientConfig{ + { + ClientName: s.oauthClientName, + ClientId: "admin", + ClientSecret: "admin", + RedirectURI: "http://localhost", + }, + }, }, ExpireSec: 3600, AntiBruteforce: conf.AntiBruteforce{ @@ -68,8 +76,10 @@ func (s *AuthTestSuite) SetupTest() { DelayLoginRequestInSec: 1, }, } - cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db). - Config(context.Background(), remote, time.Minute) + + cfg, err := assembly.NewLocator(testInstance.Logger(), s.oauthCli, s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) server, apiCli := grpct.TestServer(testInstance, cfg.Handler) s.grpcCli = apiCli @@ -95,7 +105,7 @@ func (s *AuthTestSuite) TestLoginHappyPath() { Password: "password", }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) tokenInfo := SelectTokenEntityByToken(s.db, response.Token) @@ -110,7 +120,7 @@ func (s *AuthTestSuite) TestLoginNotFound() { Email: "a1@a.ru", Password: "password", }). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -133,7 +143,7 @@ func (s *AuthTestSuite) TestBlockedUser() { Email: "a@a.ru", Password: "password", }). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -155,7 +165,7 @@ func (s *AuthTestSuite) TestLoginWrongPassword() { Email: "a@a.ru", Password: "WrongPassword", }). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -164,19 +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{ - AuthCode: "code", + err := s.grpcCli.Invoke("admin/auth/login_with_oauth"). + JsonRequestBody(domain.LoginOauthRequest{ + AuthCode: "code", + ClientName: s.oauthClientName, }). JsonResponseBody(&response). - Do(context.Background()) + 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) @@ -185,6 +196,22 @@ func (s *AuthTestSuite) TestSudirLoginHappyPath() { time.Sleep(1 * time.Second) // wait for go SaveAuditAsync() } +func (s *AuthTestSuite) TestOauthLogin_UnknownClient() { + response := domain.LoginResponse{} + + err := s.grpcCli.Invoke("admin/auth/login_with_oauth"). + JsonRequestBody(domain.LoginOauthRequest{ + AuthCode: "code", + ClientName: s.oauthClientName + fake.It[string](), + }). + JsonResponseBody(&response). + Do(s.T().Context()) + s.Require().Error(err) + st, ok := status.FromError(err) + s.Require().True(ok) + s.Require().Equal(codes.Unauthenticated, st.Code()) +} + func (s *AuthTestSuite) Test_Logout_HappyPath() { userId := InsertUser(s.db, entity.User{Email: "suslik@mail.ru"}) InsertTokenEntity(s.db, entity.Token{ @@ -196,7 +223,7 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() { }) err := s.grpcCli.Invoke("admin/auth/logout"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) tokenInfo := SelectTokenEntityByToken(s.db, "token-841297641213") @@ -208,12 +235,12 @@ func (s *AuthTestSuite) Test_Logout_HappyPath() { func (s *AuthTestSuite) Test_Logout_NotFound() { err := s.grpcCli.Invoke("admin/auth/logout"). AppendMetadata(domain.AdminAuthIdHeader, "0143218411981"). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) time.Sleep(time.Second) audit := repository.NewAudit(s.db) - auditList, err := audit.AllByRequest(context.Background(), domain.AuditPageRequest{ + auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{ LimitOffestParams: domain.LimitOffestParams{ Limit: 10, Offset: 0, @@ -241,7 +268,7 @@ func (s *AuthTestSuite) Test_Logout_AlreadyRevoke() { }) err := s.grpcCli.Invoke("admin/auth/logout"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(userId))). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) tokenInfo := SelectTokenEntityByToken(s.db, "token-148623719462") @@ -260,7 +287,7 @@ func (s *AuthTestSuite) TestBruteForceLogin() { tooManyRequestsErrorCount := &atomic.Int32{} unauthorizedErrorCount := &atomic.Int32{} - group, ctx := errgroup.WithContext(context.Background()) + group, ctx := errgroup.WithContext(s.T().Context()) for index := range 100 { group.Go(func() error { start := time.Now() @@ -298,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", } @@ -312,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", diff --git a/tests/customization_test.go b/tests/customization_test.go index 1c64130..a5a1d7e 100644 --- a/tests/customization_test.go +++ b/tests/customization_test.go @@ -1,18 +1,18 @@ package tests_test import ( - "context" "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) { @@ -40,8 +40,9 @@ func (s *CustomizationTestSuite) SetupTest() { }, ExpireSec: 0, } - cfg := assembly.NewLocator(testInstance.Logger(), nil, s.db). - Config(context.Background(), remote, time.Minute) + cfg, err := assembly.NewLocator(testInstance.Logger(), nil, s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) server, apiCli := grpct.TestServer(testInstance, cfg.Handler) s.grpcCli = apiCli @@ -57,7 +58,7 @@ func (s *CustomizationTestSuite) TestGetDesign() { Invoke("admin/user/get_design"). JsonRequestBody(struct{}{}). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) expected := conf.UIDesign{ Name: "test", diff --git a/tests/db_general_test.go b/tests/db_general_test.go index 980cb6f..dcb5389 100644 --- a/tests/db_general_test.go +++ b/tests/db_general_test.go @@ -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...) diff --git a/tests/inactive_test.go b/tests/inactive_test.go index c93788e..cd03a0e 100644 --- a/tests/inactive_test.go +++ b/tests/inactive_test.go @@ -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" @@ -27,16 +27,17 @@ func TestInactiveWorker(t *testing.T) { userId := InsertUser(db, entity.User{Email: "a@test", LastActiveAt: time.Now().UTC().Add(-5 * 24 * time.Hour)}) InsertUser(db, entity.User{Email: "b@test", LastActiveAt: time.Now().UTC()}) - config := assembly.NewLocator(test.Logger(), nil, db). + config, err := assembly.NewLocator(test.Logger(), nil, db). Config(t.Context(), conf.Remote{ BlockInactiveWorker: conf.BlockInactiveWorker{ DaysThreshold: 1, RunIntervalInMinutes: 1, }, }, 500*time.Millisecond) + require.NoError(err) bgjobCli := bgjobx.NewClient(db, test.Logger()) - err := inactive_worker.EnqueueSeedJob(t.Context(), bgjobCli) + err = inactive_worker.EnqueueSeedJob(t.Context(), bgjobCli) require.NoError(err) err = bgjobCli.Upgrade(t.Context(), config.BgJobCfg) require.NoError(err) diff --git a/tests/secure_test.go b/tests/secure_test.go index 0b5178f..b5b7360 100644 --- a/tests/secure_test.go +++ b/tests/secure_test.go @@ -1,10 +1,14 @@ package tests_test import ( - "context" "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" @@ -13,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) { @@ -40,8 +40,9 @@ func (s *SecureSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 3600, } - cfg := assembly.NewLocator(s.test.Logger(), httpCli, s.db). - Config(context.Background(), remote, time.Minute) + cfg, err := assembly.NewLocator(s.test.Logger(), httpCli, s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) server, apiCli := grpct.TestServer(s.test, cfg.Handler) s.test.T().Cleanup(func() { @@ -65,7 +66,7 @@ func (s *SecureSuite) Test_Authenticate_HappyPath() { Token: "happy_path", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: true, @@ -89,7 +90,7 @@ func (s *SecureSuite) Test_Authenticate_StatusRevoked() { Token: "revoked", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: false, @@ -113,7 +114,7 @@ func (s *SecureSuite) Test_Authenticate_Expired() { Token: "expired", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: false, @@ -129,7 +130,7 @@ func (s *SecureSuite) Test_Authenticate_NotFound() { Token: "not_found", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.Equal(domain.SecureAuthResponse{ Authenticated: false, @@ -170,7 +171,7 @@ func (s *SecureSuite) Test_Authorize_HappyPath() { Permission: "perm1", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.True(result.Authorized) @@ -181,7 +182,7 @@ func (s *SecureSuite) Test_Authorize_HappyPath() { Permission: "perm2", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.True(result.Authorized) @@ -192,7 +193,7 @@ func (s *SecureSuite) Test_Authorize_HappyPath() { Permission: "perm3", }). JsonResponseBody(&result). - Do(context.Background()) + Do(s.T().Context()) s.require.NoError(err) s.require.False(result.Authorized) } diff --git a/tests/session_test.go b/tests/session_test.go index c3a0d6d..374c887 100644 --- a/tests/session_test.go +++ b/tests/session_test.go @@ -1,16 +1,15 @@ package tests_test import ( - "context" "strconv" "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" @@ -36,10 +35,10 @@ type SessionSuite struct { grpcCli *client.Client } -func (t *SessionSuite) SetupTest() { - testInstance, _ := test.New(t.T()) - t.test = testInstance - t.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) +func (s *SessionSuite) SetupTest() { + testInstance, _ := test.New(s.T()) + s.test = testInstance + s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger())) remote := conf.Remote{ Audit: conf.Audit{ @@ -72,11 +71,14 @@ func (t *SessionSuite) SetupTest() { AuditTTl: conf.AuditTTlSetting{}, }, } - t.config = assembly.NewLocator(testInstance.Logger(), httpcli.New(), t.db). - Config(context.Background(), remote, 500*time.Millisecond) + config, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db). + Config(s.T().Context(), remote, 500*time.Millisecond) + s.Require().NoError(err) - server, apiCli := grpct.TestServer(testInstance, t.config.Handler) - t.grpcCli = apiCli + s.config = config + + server, apiCli := grpct.TestServer(testInstance, s.config.Handler) + s.grpcCli = apiCli testInstance.T().Cleanup(func() { server.Shutdown() @@ -84,11 +86,11 @@ func (t *SessionSuite) SetupTest() { } //nolint:funlen -func (t *SessionSuite) Test_All_Session() { - userId := InsertUser(t.db, entity.User{Email: "test_1@aa.ru"}) +func (s *SessionSuite) Test_All_Session() { + userId := InsertUser(s.db, entity.User{Email: "test_1@aa.ru"}) timeNow := time.Now().UTC() - InsertTokenEntity(t.db, entity.Token{ + InsertTokenEntity(s.db, entity.Token{ Token: "test_token_1", UserId: userId, Status: entity.TokenStatusAllowed, @@ -96,7 +98,7 @@ func (t *SessionSuite) Test_All_Session() { CreatedAt: timeNow.Add(-1 * time.Hour), UpdatedAt: timeNow, }) - InsertTokenEntity(t.db, entity.Token{ + InsertTokenEntity(s.db, entity.Token{ Token: "test_token_2", UserId: userId, Status: entity.TokenStatusRevoked, @@ -104,7 +106,7 @@ func (t *SessionSuite) Test_All_Session() { CreatedAt: timeNow.Add(-2 * time.Hour), UpdatedAt: timeNow, }) - InsertTokenEntity(t.db, entity.Token{ + InsertTokenEntity(s.db, entity.Token{ Token: "test_token_3", UserId: userId, Status: entity.TokenStatusExpired, @@ -122,17 +124,17 @@ func (t *SessionSuite) Test_All_Session() { } var response *domain.SessionResponse - err := t.grpcCli. + err := s.grpcCli. Invoke("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 2) - t.Require().EqualValues(3, response.TotalCount) - t.Require().EqualValues(2, response.Items[0].Id) - t.Require().EqualValues(3, response.Items[1].Id) + s.Require().Len(response.Items, 2) + s.Require().EqualValues(3, response.TotalCount) + s.Require().EqualValues(2, response.Items[0].Id) + s.Require().EqualValues(3, response.Items[1].Id) // Дефолт сортировка, поиск по expired_at request.Offset = 0 @@ -142,17 +144,17 @@ func (t *SessionSuite) Test_All_Session() { To: timeNow.Add(24 * time.Hour), }, } - err = t.grpcCli. + err = s.grpcCli. Invoke("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 2) - t.Require().EqualValues(2, response.TotalCount) - t.Require().EqualValues(1, response.Items[0].Id) - t.Require().EqualValues(2, response.Items[1].Id) + s.Require().Len(response.Items, 2) + s.Require().EqualValues(2, response.TotalCount) + s.Require().EqualValues(1, response.Items[0].Id) + s.Require().EqualValues(2, response.Items[1].Id) // Сортировка по статусу, пустой запрос request.Query = nil @@ -161,18 +163,18 @@ func (t *SessionSuite) Test_All_Session() { Type: "asc", } - err = t.grpcCli. + err = s.grpcCli. Invoke("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 3) - t.Require().EqualValues(3, response.TotalCount) - t.Require().EqualValues(1, response.Items[0].Id) - t.Require().EqualValues(3, response.Items[1].Id) - t.Require().EqualValues(2, response.Items[2].Id) + s.Require().Len(response.Items, 3) + s.Require().EqualValues(3, response.TotalCount) + s.Require().EqualValues(1, response.Items[0].Id) + s.Require().EqualValues(3, response.Items[1].Id) + s.Require().EqualValues(2, response.Items[2].Id) // Сортировка по статусу, поиск по userId & status resUserId := int(userId) @@ -181,21 +183,21 @@ func (t *SessionSuite) Test_All_Session() { Status: []string{entity.TokenStatusExpired}, } - err = t.grpcCli. + err = s.grpcCli. Invoke("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 1) - t.Require().EqualValues(1, response.TotalCount) - t.Require().EqualValues(3, response.Items[0].Id) + s.Require().Len(response.Items, 1) + s.Require().EqualValues(1, response.TotalCount) + s.Require().EqualValues(3, response.Items[0].Id) // Сортировка по id, поиск по id for i := range 20 { - userId = InsertUser(t.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"}) - InsertTokenEntity(t.db, entity.Token{ + userId = InsertUser(s.db, entity.User{Email: "test_11" + strconv.Itoa(i) + "@aa.ru"}) + InsertTokenEntity(s.db, entity.Token{ Token: "test_token_1" + strconv.Itoa(i), UserId: userId, Status: entity.TokenStatusAllowed, @@ -218,57 +220,57 @@ func (t *SessionSuite) Test_All_Session() { Id: new(2), }, } - err = t.grpcCli. + err = s.grpcCli. Invoke("admin/session/all"). JsonRequestBody(request). JsonResponseBody(&response). - Do(context.Background()) - t.Require().NoError(err) + Do(s.T().Context()) + s.Require().NoError(err) - t.Require().Len(response.Items, 5) - t.Require().EqualValues(6, response.TotalCount) - t.Require().EqualValues(23, response.Items[0].Id) - t.Require().EqualValues(22, response.Items[1].Id) - t.Require().EqualValues(21, response.Items[2].Id) - t.Require().EqualValues(20, response.Items[3].Id) - t.Require().EqualValues(12, response.Items[4].Id) + s.Require().Len(response.Items, 5) + s.Require().EqualValues(6, response.TotalCount) + s.Require().EqualValues(23, response.Items[0].Id) + s.Require().EqualValues(22, response.Items[1].Id) + s.Require().EqualValues(21, response.Items[2].Id) + s.Require().EqualValues(20, response.Items[3].Id) + s.Require().EqualValues(12, response.Items[4].Id) } -func (t *SessionSuite) Test_Session_Expired_Worker() { - userId := InsertUser(t.db, entity.User{Email: "a@test"}) +func (s *SessionSuite) Test_Session_Expired_Worker() { + userId := InsertUser(s.db, entity.User{Email: "a@test"}) - InsertTokenEntity(t.db, entity.Token{ + InsertTokenEntity(s.db, entity.Token{ Token: "token_allowed", UserId: userId, Status: entity.TokenStatusAllowed, ExpiredAt: time.Now().UTC().Add(24 * time.Hour)}) - InsertTokenEntity(t.db, entity.Token{ + InsertTokenEntity(s.db, entity.Token{ Token: "token_expired", UserId: userId, Status: entity.TokenStatusAllowed, ExpiredAt: time.Now().UTC().Add(-2 * time.Hour)}) - InsertTokenEntity(t.db, entity.Token{ + InsertTokenEntity(s.db, entity.Token{ Token: "token_expired2", UserId: userId, Status: entity.TokenStatusAllowed, ExpiredAt: time.Now().UTC().Add(-24 * time.Hour)}) - bgjobCli := bgjobx.NewClient(t.db, t.test.Logger()) + bgjobCli := bgjobx.NewClient(s.db, s.test.Logger()) - err := session_worker.EnqueueSeedJob(t.T().Context(), bgjobCli) - t.Require().NoError(err) + err := session_worker.EnqueueSeedJob(s.T().Context(), bgjobCli) + s.Require().NoError(err) - err = bgjobCli.Upgrade(t.T().Context(), t.config.BgJobCfg) - t.Require().NoError(err) + err = bgjobCli.Upgrade(s.T().Context(), s.config.BgJobCfg) + s.Require().NoError(err) time.Sleep(2 * time.Second) tokens := make([]entity.Token, 0) - t.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC") + s.db.Must().Select(&tokens, "SELECT * FROM tokens ORDER BY status ASC") - t.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status) - t.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status) - t.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status) + s.Require().EqualValues(entity.TokenStatusAllowed, tokens[0].Status) + s.Require().EqualValues(entity.TokenStatusExpired, tokens[1].Status) + s.Require().EqualValues(entity.TokenStatusExpired, tokens[2].Status) } diff --git a/tests/ui_settings_test.go b/tests/ui_settings_test.go new file mode 100644 index 0000000..8fca7fd --- /dev/null +++ b/tests/ui_settings_test.go @@ -0,0 +1,105 @@ +package tests_test + +import ( + "isp-admin-service/assembly" + "isp-admin-service/conf" + "isp-admin-service/domain" + "net/url" + "testing" + + "github.com/stretchr/testify/suite" + "github.com/txix-open/isp-kit/grpc/client" + "github.com/txix-open/isp-kit/test" + "github.com/txix-open/isp-kit/test/fake" + "github.com/txix-open/isp-kit/test/grpct" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type UiSettingsSuite struct { + suite.Suite + + test *test.Test + apiCli *client.Client + oauthClientSetting conf.OauthClientConfig + baseOauthUrl string +} + +func TestUiSettingsSuite(t *testing.T) { + t.Parallel() + suite.Run(t, &UiSettingsSuite{ + 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.UiOauthSetting{ + LoginEndpoint: "/login?someQueryParam=1&test=true", + LogoutEndpoint: "/logout?redirect=url", + }, + }, + }) +} + +func (s *UiSettingsSuite) SetupTest() { + s.test, _ = test.New(s.T()) + remote := conf.Remote{ + Oauth: &conf.Oauth{ + Host: s.baseOauthUrl, + Clients: []conf.OauthClientConfig{s.oauthClientSetting}, + }, + } + cfg, err := assembly.NewLocator(s.test.Logger(), nil, nil). + Config(s.T().Context(), remote, 0) + s.Require().NoError(err) + + _, s.apiCli = grpct.TestServer(s.test, cfg.Handler) +} + +func (s *UiSettingsSuite) Test_HappyPath() { + var resp domain.UiOauthSetting + + err := s.apiCli.Invoke("admin/ui_settings/oauth"). + JsonRequestBody(domain.ClientNameRequest{ + ClientName: s.oauthClientSetting.ClientName, + }). + JsonResponseBody(&resp). + Do(s.T().Context()) + s.Require().NoError(err) + + loginURL, err := url.Parse(resp.LoginUrl) + s.Require().NoError(err) + + s.Require().Equal( + "http://127.0.0.1/oauth/login", + loginURL.Scheme+"://"+loginURL.Host+loginURL.Path, + ) + + query := loginURL.Query() + 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")) + + logoutURL, err := url.Parse(resp.LogoutUrl) + s.Require().NoError(err) + + s.Require().Equal( + "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/oauth"). + JsonRequestBody(domain.ClientNameRequest{ + ClientName: s.oauthClientSetting.ClientName + fake.It[string](), + }). + Do(s.T().Context()) + s.Require().Error(err) + st, ok := status.FromError(err) + s.Require().True(ok) + s.Require().Equal(codes.Unauthenticated, st.Code()) +} diff --git a/tests/user_test.go b/tests/user_test.go index 1fc4e5d..8eba047 100644 --- a/tests/user_test.go +++ b/tests/user_test.go @@ -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" @@ -56,8 +56,9 @@ func (s *UserTestSuite) SetupTest() { remote := conf.Remote{ ExpireSec: 0, } - cfg := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db). - Config(context.Background(), remote, time.Minute) + cfg, err := assembly.NewLocator(testInstance.Logger(), s.httpCli, s.db). + Config(s.T().Context(), remote, time.Minute) + s.Require().NoError(err) server, apiCli := grpct.TestServer(testInstance, cfg.Handler) s.grpcCli = apiCli @@ -92,7 +93,7 @@ func (s *UserTestSuite) TestGetProfileHappyPath() { err := s.grpcCli.Invoke("admin/user/get_profile"). JsonResponseBody(&response). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) expected := domain.AdminUserShort{ FirstName: "name", @@ -118,16 +119,16 @@ func (s *UserTestSuite) TestGetProfileNotFound() { err := s.grpcCli.Invoke("admin/user/get_profile"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id+1))). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) 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", @@ -148,7 +149,7 @@ func (s *UserTestSuite) TestGetProfileSudir() { Invoke("admin/user/get_profile"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) expected := domain.AdminUserShort{ FirstName: "name", @@ -199,7 +200,7 @@ func (s *UserTestSuite) TestGetUsers() { }, }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) roles := []int{int(roleId1), int(roleId2)} @@ -227,7 +228,7 @@ func (s *UserTestSuite) TestGetUsers() { }, }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) s.Require().Empty(response.Items) } @@ -250,7 +251,7 @@ func (s *UserTestSuite) TestAllGetUsers() { InsertUserRole(s.db, entity.UserRole{RoleId: int(roleId2), UserId: int(userId2)}) response := domain.UsersResponse{} - err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(context.Background()) + err := s.grpcCli.Invoke("admin/user/get_all_users").JsonResponseBody(&response).Do(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 7) @@ -313,7 +314,7 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() { }, }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 2) @@ -346,7 +347,7 @@ func (s *UserTestSuite) TestGetUsersSortByName() { }, }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) s.Require().Len(response.Items, 4) @@ -373,7 +374,7 @@ func (s *UserTestSuite) TestCreateUserHappyPath() { Password: "password", }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) postCount := 0 @@ -383,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") @@ -401,7 +402,7 @@ func (s *UserTestSuite) TestCreateUserWithSameEmailSudirHappyPath() { Password: "password", }). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) postCount := 0 @@ -423,7 +424,7 @@ func (s *UserTestSuite) TestCreateUserAlreadyExist() { Email: "exists@a.ru", Password: "password", }). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -444,7 +445,7 @@ func (s *AuthTestSuite) TestUpdateUserHappyPath() { AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(req). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) expected := domain.UpdateUserRequest{ Id: response.Id, @@ -457,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. @@ -471,7 +472,7 @@ func (s *AuthTestSuite) TestUpdateSudirUserHappyPath() { AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(req). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) expected := domain.UpdateUserRequest{ Id: response.Id, @@ -498,19 +499,19 @@ func (s *AuthTestSuite) TestUpdateUserAlreadyExist() { Invoke("admin/user/update_user"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(req). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) 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", @@ -521,7 +522,7 @@ func (s *AuthTestSuite) TestUpdateUserWithSudirAlreadyExist() { Invoke("admin/user/update_user"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(req). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) st, ok := status.FromError(err) s.Require().True(ok) @@ -540,7 +541,7 @@ func (s *UserTestSuite) TestDeleteUsers() { AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(admin))). JsonRequestBody(domain.IdentitiesRequest{Ids: []int64{3, 4}}). JsonResponseBody(&response). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) s.Require().Equal(2, response.Deleted) @@ -569,14 +570,14 @@ func (s *UserTestSuite) TestBlockUser() { err := s.grpcCli.Invoke("admin/user/block_user"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(id))). JsonRequestBody(domain.IdRequest{UserId: int(id)}). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) - user, err := repository.NewUser(s.db).GetUserById(context.Background(), id) + user, err := repository.NewUser(s.db).GetUserById(s.T().Context(), id) s.Require().NoError(err) s.Require().True(user.Blocked) - t, err := repository.NewToken(s.db).Get(context.Background(), token) + t, err := repository.NewToken(s.db).Get(s.T().Context(), token) s.Require().NoError(err) s.EqualValues(entity.TokenStatusRevoked, t.Status) @@ -600,7 +601,7 @@ func (s *UserTestSuite) TestChangePasswordUser() { err := s.grpcCli.Invoke("admin/user/change_password"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). JsonRequestBody(invalidReq). - Do(context.Background()) + Do(s.T().Context()) s.Require().Error(err) err = apierrors.FromError(err) s.Require().Contains(err.Error(), strconv.Itoa(domain.ErrCodeInvalidPassword)) @@ -610,7 +611,7 @@ func (s *UserTestSuite) TestChangePasswordUser() { err = s.grpcCli.Invoke("admin/user/change_password"). AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(adminId))). JsonRequestBody(changePswReq). - Do(context.Background()) + Do(s.T().Context()) s.Require().NoError(err) diff --git a/transaction/manager.go b/transaction/manager.go index 5fab6a6..c41fa1d 100644 --- a/transaction/manager.go +++ b/transaction/manager.go @@ -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" ) diff --git a/vendor/github.com/Masterminds/squirrel/.gitignore b/vendor/github.com/Masterminds/squirrel/.gitignore new file mode 100644 index 0000000..4a0699f --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/.gitignore @@ -0,0 +1 @@ +squirrel.test \ No newline at end of file diff --git a/vendor/github.com/Masterminds/squirrel/.travis.yml b/vendor/github.com/Masterminds/squirrel/.travis.yml new file mode 100644 index 0000000..7bb6da4 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/.travis.yml @@ -0,0 +1,30 @@ +language: go + +go: + - 1.11.x + - 1.12.x + - 1.13.x + +services: + - mysql + - postgresql + +# Setting sudo access to false will let Travis CI use containers rather than +# VMs to run the tests. For more details see: +# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ +# - http://docs.travis-ci.com/user/workers/standard-infrastructure/ +sudo: false + +before_script: + - mysql -e 'CREATE DATABASE squirrel;' + - psql -c 'CREATE DATABASE squirrel;' -U postgres + +script: + - go test + - cd integration + - go test -args -driver sqlite3 + - go test -args -driver mysql -dataSource travis@/squirrel + - go test -args -driver postgres -dataSource 'postgres://postgres@localhost/squirrel?sslmode=disable' + +notifications: + irc: "irc.freenode.net#masterminds" diff --git a/vendor/github.com/Masterminds/squirrel/LICENSE b/vendor/github.com/Masterminds/squirrel/LICENSE new file mode 100644 index 0000000..b459007 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/LICENSE @@ -0,0 +1,23 @@ +MIT License + +Squirrel: The Masterminds +Copyright (c) 2014-2015, Lann Martin. Copyright (C) 2015-2016, Google. Copyright (C) 2015, Matt Farina and Matt Butcher. + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/Masterminds/squirrel/README.md b/vendor/github.com/Masterminds/squirrel/README.md new file mode 100644 index 0000000..1d37f28 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/README.md @@ -0,0 +1,142 @@ +[![Stability: Maintenance](https://masterminds.github.io/stability/maintenance.svg)](https://masterminds.github.io/stability/maintenance.html) +### Squirrel is "complete". +Bug fixes will still be merged (slowly). Bug reports are welcome, but I will not necessarily respond to them. If another fork (or substantially similar project) actively improves on what Squirrel does, let me know and I may link to it here. + + +# Squirrel - fluent SQL generator for Go + +```go +import "github.com/Masterminds/squirrel" +``` + + +[![GoDoc](https://godoc.org/github.com/Masterminds/squirrel?status.png)](https://godoc.org/github.com/Masterminds/squirrel) +[![Build Status](https://api.travis-ci.org/Masterminds/squirrel.svg?branch=master)](https://travis-ci.org/Masterminds/squirrel) + +**Squirrel is not an ORM.** For an application of Squirrel, check out +[structable, a table-struct mapper](https://github.com/Masterminds/structable) + + +Squirrel helps you build SQL queries from composable parts: + +```go +import sq "github.com/Masterminds/squirrel" + +users := sq.Select("*").From("users").Join("emails USING (email_id)") + +active := users.Where(sq.Eq{"deleted_at": nil}) + +sql, args, err := active.ToSql() + +sql == "SELECT * FROM users JOIN emails USING (email_id) WHERE deleted_at IS NULL" +``` + +```go +sql, args, err := sq. + Insert("users").Columns("name", "age"). + Values("moe", 13).Values("larry", sq.Expr("? + 5", 12)). + ToSql() + +sql == "INSERT INTO users (name,age) VALUES (?,?),(?,? + 5)" +``` + +Squirrel can also execute queries directly: + +```go +stooges := users.Where(sq.Eq{"username": []string{"moe", "larry", "curly", "shemp"}}) +three_stooges := stooges.Limit(3) +rows, err := three_stooges.RunWith(db).Query() + +// Behaves like: +rows, err := db.Query("SELECT * FROM users WHERE username IN (?,?,?,?) LIMIT 3", + "moe", "larry", "curly", "shemp") +``` + +Squirrel makes conditional query building a breeze: + +```go +if len(q) > 0 { + users = users.Where("name LIKE ?", fmt.Sprint("%", q, "%")) +} +``` + +Squirrel wants to make your life easier: + +```go +// StmtCache caches Prepared Stmts for you +dbCache := sq.NewStmtCache(db) + +// StatementBuilder keeps your syntax neat +mydb := sq.StatementBuilder.RunWith(dbCache) +select_users := mydb.Select("*").From("users") +``` + +Squirrel loves PostgreSQL: + +```go +psql := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) + +// You use question marks for placeholders... +sql, _, _ := psql.Select("*").From("elephants").Where("name IN (?,?)", "Dumbo", "Verna").ToSql() + +/// ...squirrel replaces them using PlaceholderFormat. +sql == "SELECT * FROM elephants WHERE name IN ($1,$2)" + + +/// You can retrieve id ... +query := sq.Insert("nodes"). + Columns("uuid", "type", "data"). + Values(node.Uuid, node.Type, node.Data). + Suffix("RETURNING \"id\""). + RunWith(m.db). + PlaceholderFormat(sq.Dollar) + +query.QueryRow().Scan(&node.id) +``` + +You can escape question marks by inserting two question marks: + +```sql +SELECT * FROM nodes WHERE meta->'format' ??| array[?,?] +``` + +will generate with the Dollar Placeholder: + +```sql +SELECT * FROM nodes WHERE meta->'format' ?| array[$1,$2] +``` + +## FAQ + +* **How can I build an IN query on composite keys / tuples, e.g. `WHERE (col1, col2) IN ((1,2),(3,4))`? ([#104](https://github.com/Masterminds/squirrel/issues/104))** + + Squirrel does not explicitly support tuples, but you can get the same effect with e.g.: + + ```go + sq.Or{ + sq.Eq{"col1": 1, "col2": 2}, + sq.Eq{"col1": 3, "col2": 4}} + ``` + + ```sql + WHERE (col1 = 1 AND col2 = 2) OR (col1 = 3 AND col2 = 4) + ``` + + (which should produce the same query plan as the tuple version) + +* **Why doesn't `Eq{"mynumber": []uint8{1,2,3}}` turn into an `IN` query? ([#114](https://github.com/Masterminds/squirrel/issues/114))** + + Values of type `[]byte` are handled specially by `database/sql`. In Go, [`byte` is just an alias of `uint8`](https://golang.org/pkg/builtin/#byte), so there is no way to distinguish `[]uint8` from `[]byte`. + +* **Some features are poorly documented!** + + This isn't a frequent complaints section! + +* **Some features are poorly documented?** + + Yes. The tests should be considered a part of the documentation; take a look at those for ideas on how to express more complex queries. + +## License + +Squirrel is released under the +[MIT License](http://www.opensource.org/licenses/MIT). diff --git a/vendor/github.com/Masterminds/squirrel/case.go b/vendor/github.com/Masterminds/squirrel/case.go new file mode 100644 index 0000000..299e14b --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/case.go @@ -0,0 +1,128 @@ +package squirrel + +import ( + "bytes" + "errors" + + "github.com/lann/builder" +) + +func init() { + builder.Register(CaseBuilder{}, caseData{}) +} + +// sqlizerBuffer is a helper that allows to write many Sqlizers one by one +// without constant checks for errors that may come from Sqlizer +type sqlizerBuffer struct { + bytes.Buffer + args []interface{} + err error +} + +// WriteSql converts Sqlizer to SQL strings and writes it to buffer +func (b *sqlizerBuffer) WriteSql(item Sqlizer) { + if b.err != nil { + return + } + + var str string + var args []interface{} + str, args, b.err = nestedToSql(item) + + if b.err != nil { + return + } + + b.WriteString(str) + b.WriteByte(' ') + b.args = append(b.args, args...) +} + +func (b *sqlizerBuffer) ToSql() (string, []interface{}, error) { + return b.String(), b.args, b.err +} + +// whenPart is a helper structure to describe SQLs "WHEN ... THEN ..." expression +type whenPart struct { + when Sqlizer + then Sqlizer +} + +func newWhenPart(when interface{}, then interface{}) whenPart { + return whenPart{newPart(when), newPart(then)} +} + +// caseData holds all the data required to build a CASE SQL construct +type caseData struct { + What Sqlizer + WhenParts []whenPart + Else Sqlizer +} + +// ToSql implements Sqlizer +func (d *caseData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.WhenParts) == 0 { + err = errors.New("case expression must contain at lease one WHEN clause") + + return + } + + sql := sqlizerBuffer{} + + sql.WriteString("CASE ") + if d.What != nil { + sql.WriteSql(d.What) + } + + for _, p := range d.WhenParts { + sql.WriteString("WHEN ") + sql.WriteSql(p.when) + sql.WriteString("THEN ") + sql.WriteSql(p.then) + } + + if d.Else != nil { + sql.WriteString("ELSE ") + sql.WriteSql(d.Else) + } + + sql.WriteString("END") + + return sql.ToSql() +} + +// CaseBuilder builds SQL CASE construct which could be used as parts of queries. +type CaseBuilder builder.Builder + +// ToSql builds the query into a SQL string and bound args. +func (b CaseBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(caseData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b CaseBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// what sets optional value for CASE construct "CASE [value] ..." +func (b CaseBuilder) what(expr interface{}) CaseBuilder { + return builder.Set(b, "What", newPart(expr)).(CaseBuilder) +} + +// When adds "WHEN ... THEN ..." part to CASE construct +func (b CaseBuilder) When(when interface{}, then interface{}) CaseBuilder { + // TODO: performance hint: replace slice of WhenPart with just slice of parts + // where even indices of the slice belong to "when"s and odd indices belong to "then"s + return builder.Append(b, "WhenParts", newWhenPart(when, then)).(CaseBuilder) +} + +// What sets optional "ELSE ..." part for CASE construct +func (b CaseBuilder) Else(expr interface{}) CaseBuilder { + return builder.Set(b, "Else", newPart(expr)).(CaseBuilder) +} diff --git a/vendor/github.com/Masterminds/squirrel/delete.go b/vendor/github.com/Masterminds/squirrel/delete.go new file mode 100644 index 0000000..f3f31e6 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/delete.go @@ -0,0 +1,191 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type deleteData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + From string + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *deleteData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *deleteData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.From) == 0 { + err = fmt.Errorf("delete statements must specify a From table") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("DELETE FROM ") + sql.WriteString(d.From) + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// DeleteBuilder builds SQL DELETE statements. +type DeleteBuilder builder.Builder + +func init() { + builder.Register(DeleteBuilder{}, deleteData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b DeleteBuilder) PlaceholderFormat(f PlaceholderFormat) DeleteBuilder { + return builder.Set(b, "PlaceholderFormat", f).(DeleteBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b DeleteBuilder) RunWith(runner BaseRunner) DeleteBuilder { + return setRunWith(b, runner).(DeleteBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b DeleteBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.Exec() +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b DeleteBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(deleteData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b DeleteBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b DeleteBuilder) PrefixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Prefixes", expr).(DeleteBuilder) +} + +// From sets the table to be deleted from. +func (b DeleteBuilder) From(from string) DeleteBuilder { + return builder.Set(b, "From", from).(DeleteBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b DeleteBuilder) Where(pred interface{}, args ...interface{}) DeleteBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(DeleteBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b DeleteBuilder) OrderBy(orderBys ...string) DeleteBuilder { + return builder.Extend(b, "OrderBys", orderBys).(DeleteBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b DeleteBuilder) Limit(limit uint64) DeleteBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(DeleteBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b DeleteBuilder) Offset(offset uint64) DeleteBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(DeleteBuilder) +} + +// Suffix adds an expression to the end of the query +func (b DeleteBuilder) Suffix(sql string, args ...interface{}) DeleteBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b DeleteBuilder) SuffixExpr(expr Sqlizer) DeleteBuilder { + return builder.Append(b, "Suffixes", expr).(DeleteBuilder) +} + +func (b DeleteBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.Query() +} + +func (d *deleteData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} diff --git a/vendor/github.com/Masterminds/squirrel/delete_ctx.go b/vendor/github.com/Masterminds/squirrel/delete_ctx.go new file mode 100644 index 0000000..de83c55 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/delete_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *deleteData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *deleteData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(deleteData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(deleteData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b DeleteBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(deleteData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b DeleteBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/vendor/github.com/Masterminds/squirrel/expr.go b/vendor/github.com/Masterminds/squirrel/expr.go new file mode 100644 index 0000000..eba1b45 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/expr.go @@ -0,0 +1,419 @@ +package squirrel + +import ( + "bytes" + "database/sql/driver" + "fmt" + "reflect" + "sort" + "strings" +) + +const ( + // Portable true/false literals. + sqlTrue = "(1=1)" + sqlFalse = "(1=0)" +) + +type expr struct { + sql string + args []interface{} +} + +// Expr builds an expression from a SQL fragment and arguments. +// +// Ex: +// Expr("FROM_UNIXTIME(?)", t) +func Expr(sql string, args ...interface{}) Sqlizer { + return expr{sql: sql, args: args} +} + +func (e expr) ToSql() (sql string, args []interface{}, err error) { + simple := true + for _, arg := range e.args { + if _, ok := arg.(Sqlizer); ok { + simple = false + } + } + if simple { + return e.sql, e.args, nil + } + + buf := &bytes.Buffer{} + ap := e.args + sp := e.sql + + var isql string + var iargs []interface{} + + for err == nil && len(ap) > 0 && len(sp) > 0 { + i := strings.Index(sp, "?") + if i < 0 { + // no more placeholders + break + } + if len(sp) > i+1 && sp[i+1:i+2] == "?" { + // escaped "??"; append it and step past + buf.WriteString(sp[:i+2]) + sp = sp[i+2:] + continue + } + + if as, ok := ap[0].(Sqlizer); ok { + // sqlizer argument; expand it and append the result + isql, iargs, err = as.ToSql() + buf.WriteString(sp[:i]) + buf.WriteString(isql) + args = append(args, iargs...) + } else { + // normal argument; append it and the placeholder + buf.WriteString(sp[:i+1]) + args = append(args, ap[0]) + } + + // step past the argument and placeholder + ap = ap[1:] + sp = sp[i+1:] + } + + // append the remaining sql and arguments + buf.WriteString(sp) + return buf.String(), append(args, ap...), err +} + +type concatExpr []interface{} + +func (ce concatExpr) ToSql() (sql string, args []interface{}, err error) { + for _, part := range ce { + switch p := part.(type) { + case string: + sql += p + case Sqlizer: + pSql, pArgs, err := p.ToSql() + if err != nil { + return "", nil, err + } + sql += pSql + args = append(args, pArgs...) + default: + return "", nil, fmt.Errorf("%#v is not a string or Sqlizer", part) + } + } + return +} + +// ConcatExpr builds an expression by concatenating strings and other expressions. +// +// Ex: +// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName) +// ConcatExpr("COALESCE(full_name,", name_expr, ")") +func ConcatExpr(parts ...interface{}) concatExpr { + return concatExpr(parts) +} + +// aliasExpr helps to alias part of SQL query generated with underlying "expr" +type aliasExpr struct { + expr Sqlizer + alias string +} + +// Alias allows to define alias for column in SelectBuilder. Useful when column is +// defined as complex expression like IF or CASE +// Ex: +// .Column(Alias(caseStmt, "case_column")) +func Alias(expr Sqlizer, alias string) aliasExpr { + return aliasExpr{expr, alias} +} + +func (e aliasExpr) ToSql() (sql string, args []interface{}, err error) { + sql, args, err = e.expr.ToSql() + if err == nil { + sql = fmt.Sprintf("(%s) AS %s", sql, e.alias) + } + return +} + +// Eq is syntactic sugar for use with Where/Having/Set methods. +type Eq map[string]interface{} + +func (eq Eq) toSQL(useNotOpr bool) (sql string, args []interface{}, err error) { + if len(eq) == 0 { + // Empty Sql{} evaluates to true. + sql = sqlTrue + return + } + + var ( + exprs []string + equalOpr = "=" + inOpr = "IN" + nullOpr = "IS" + inEmptyExpr = sqlFalse + ) + + if useNotOpr { + equalOpr = "<>" + inOpr = "NOT IN" + nullOpr = "IS NOT" + inEmptyExpr = sqlTrue + } + + sortedKeys := getSortedKeys(eq) + for _, key := range sortedKeys { + var expr string + val := eq[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + r := reflect.ValueOf(val) + if r.Kind() == reflect.Ptr { + if r.IsNil() { + val = nil + } else { + val = r.Elem().Interface() + } + } + + if val == nil { + expr = fmt.Sprintf("%s %s NULL", key, nullOpr) + } else { + if isListType(val) { + valVal := reflect.ValueOf(val) + if valVal.Len() == 0 { + expr = inEmptyExpr + if args == nil { + args = []interface{}{} + } + } else { + for i := 0; i < valVal.Len(); i++ { + args = append(args, valVal.Index(i).Interface()) + } + expr = fmt.Sprintf("%s %s (%s)", key, inOpr, Placeholders(valVal.Len())) + } + } else { + expr = fmt.Sprintf("%s %s ?", key, equalOpr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (eq Eq) ToSql() (sql string, args []interface{}, err error) { + return eq.toSQL(false) +} + +// NotEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(NotEq{"id": 1}) == "id <> 1" +type NotEq Eq + +func (neq NotEq) ToSql() (sql string, args []interface{}, err error) { + return Eq(neq).toSQL(true) +} + +// Like is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(Like{"name": "%irrel"}) +type Like map[string]interface{} + +func (lk Like) toSql(opr string) (sql string, args []interface{}, err error) { + var exprs []string + for key, val := range lk { + expr := "" + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with like operators") + return + } else { + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with like operators") + return + } else { + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + } + } + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lk Like) ToSql() (sql string, args []interface{}, err error) { + return lk.toSql("LIKE") +} + +// NotLike is syntactic sugar for use with LIKE conditions. +// Ex: +// .Where(NotLike{"name": "%irrel"}) +type NotLike Like + +func (nlk NotLike) ToSql() (sql string, args []interface{}, err error) { + return Like(nlk).toSql("NOT LIKE") +} + +// ILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(ILike{"name": "sq%"}) +type ILike Like + +func (ilk ILike) ToSql() (sql string, args []interface{}, err error) { + return Like(ilk).toSql("ILIKE") +} + +// NotILike is syntactic sugar for use with ILIKE conditions. +// Ex: +// .Where(NotILike{"name": "sq%"}) +type NotILike Like + +func (nilk NotILike) ToSql() (sql string, args []interface{}, err error) { + return Like(nilk).toSql("NOT ILIKE") +} + +// Lt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Lt{"id": 1}) +type Lt map[string]interface{} + +func (lt Lt) toSql(opposite, orEq bool) (sql string, args []interface{}, err error) { + var ( + exprs []string + opr = "<" + ) + + if opposite { + opr = ">" + } + + if orEq { + opr = fmt.Sprintf("%s%s", opr, "=") + } + + sortedKeys := getSortedKeys(lt) + for _, key := range sortedKeys { + var expr string + val := lt[key] + + switch v := val.(type) { + case driver.Valuer: + if val, err = v.Value(); err != nil { + return + } + } + + if val == nil { + err = fmt.Errorf("cannot use null with less than or greater than operators") + return + } + if isListType(val) { + err = fmt.Errorf("cannot use array or slice with less than or greater than operators") + return + } + expr = fmt.Sprintf("%s %s ?", key, opr) + args = append(args, val) + + exprs = append(exprs, expr) + } + sql = strings.Join(exprs, " AND ") + return +} + +func (lt Lt) ToSql() (sql string, args []interface{}, err error) { + return lt.toSql(false, false) +} + +// LtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(LtOrEq{"id": 1}) == "id <= 1" +type LtOrEq Lt + +func (ltOrEq LtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(ltOrEq).toSql(false, true) +} + +// Gt is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(Gt{"id": 1}) == "id > 1" +type Gt Lt + +func (gt Gt) ToSql() (sql string, args []interface{}, err error) { + return Lt(gt).toSql(true, false) +} + +// GtOrEq is syntactic sugar for use with Where/Having/Set methods. +// Ex: +// .Where(GtOrEq{"id": 1}) == "id >= 1" +type GtOrEq Lt + +func (gtOrEq GtOrEq) ToSql() (sql string, args []interface{}, err error) { + return Lt(gtOrEq).toSql(true, true) +} + +type conj []Sqlizer + +func (c conj) join(sep, defaultExpr string) (sql string, args []interface{}, err error) { + if len(c) == 0 { + return defaultExpr, []interface{}{}, nil + } + var sqlParts []string + for _, sqlizer := range c { + partSQL, partArgs, err := nestedToSql(sqlizer) + if err != nil { + return "", nil, err + } + if partSQL != "" { + sqlParts = append(sqlParts, partSQL) + args = append(args, partArgs...) + } + } + if len(sqlParts) > 0 { + sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep)) + } + return +} + +// And conjunction Sqlizers +type And conj + +func (a And) ToSql() (string, []interface{}, error) { + return conj(a).join(" AND ", sqlTrue) +} + +// Or conjunction Sqlizers +type Or conj + +func (o Or) ToSql() (string, []interface{}, error) { + return conj(o).join(" OR ", sqlFalse) +} + +func getSortedKeys(exp map[string]interface{}) []string { + sortedKeys := make([]string, 0, len(exp)) + for k := range exp { + sortedKeys = append(sortedKeys, k) + } + sort.Strings(sortedKeys) + return sortedKeys +} + +func isListType(val interface{}) bool { + if driver.IsValue(val) { + return false + } + valVal := reflect.ValueOf(val) + return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice +} diff --git a/vendor/github.com/Masterminds/squirrel/insert.go b/vendor/github.com/Masterminds/squirrel/insert.go new file mode 100644 index 0000000..c23a579 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/insert.go @@ -0,0 +1,298 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "io" + "sort" + "strings" + + "github.com/lann/builder" +) + +type insertData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + StatementKeyword string + Options []string + Into string + Columns []string + Values [][]interface{} + Suffixes []Sqlizer + Select *SelectBuilder +} + +func (d *insertData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *insertData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *insertData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *insertData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Into) == 0 { + err = errors.New("insert statements must specify a table") + return + } + if len(d.Values) == 0 && d.Select == nil { + err = errors.New("insert statements must have at least one set of values or select clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + if d.StatementKeyword == "" { + sql.WriteString("INSERT ") + } else { + sql.WriteString(d.StatementKeyword) + sql.WriteString(" ") + } + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + sql.WriteString("INTO ") + sql.WriteString(d.Into) + sql.WriteString(" ") + + if len(d.Columns) > 0 { + sql.WriteString("(") + sql.WriteString(strings.Join(d.Columns, ",")) + sql.WriteString(") ") + } + + if d.Select != nil { + args, err = d.appendSelectToSQL(sql, args) + } else { + args, err = d.appendValuesToSQL(sql, args) + } + if err != nil { + return + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +func (d *insertData) appendValuesToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if len(d.Values) == 0 { + return args, errors.New("values for insert statements are not set") + } + + io.WriteString(w, "VALUES ") + + valuesStrings := make([]string, len(d.Values)) + for r, row := range d.Values { + valueStrings := make([]string, len(row)) + for v, val := range row { + if vs, ok := val.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return nil, err + } + valueStrings[v] = vsql + args = append(args, vargs...) + } else { + valueStrings[v] = "?" + args = append(args, val) + } + } + valuesStrings[r] = fmt.Sprintf("(%s)", strings.Join(valueStrings, ",")) + } + + io.WriteString(w, strings.Join(valuesStrings, ",")) + + return args, nil +} + +func (d *insertData) appendSelectToSQL(w io.Writer, args []interface{}) ([]interface{}, error) { + if d.Select == nil { + return args, errors.New("select clause for insert statements are not set") + } + + selectClause, sArgs, err := d.Select.ToSql() + if err != nil { + return args, err + } + + io.WriteString(w, selectClause) + args = append(args, sArgs...) + + return args, nil +} + +// Builder + +// InsertBuilder builds SQL INSERT statements. +type InsertBuilder builder.Builder + +func init() { + builder.Register(InsertBuilder{}, insertData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b InsertBuilder) PlaceholderFormat(f PlaceholderFormat) InsertBuilder { + return builder.Set(b, "PlaceholderFormat", f).(InsertBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b InsertBuilder) RunWith(runner BaseRunner) InsertBuilder { + return setRunWith(b, runner).(InsertBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b InsertBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b InsertBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b InsertBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b InsertBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(insertData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b InsertBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b InsertBuilder) Prefix(sql string, args ...interface{}) InsertBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b InsertBuilder) PrefixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Prefixes", expr).(InsertBuilder) +} + +// Options adds keyword options before the INTO clause of the query. +func (b InsertBuilder) Options(options ...string) InsertBuilder { + return builder.Extend(b, "Options", options).(InsertBuilder) +} + +// Into sets the INTO clause of the query. +func (b InsertBuilder) Into(from string) InsertBuilder { + return builder.Set(b, "Into", from).(InsertBuilder) +} + +// Columns adds insert columns to the query. +func (b InsertBuilder) Columns(columns ...string) InsertBuilder { + return builder.Extend(b, "Columns", columns).(InsertBuilder) +} + +// Values adds a single row's values to the query. +func (b InsertBuilder) Values(values ...interface{}) InsertBuilder { + return builder.Append(b, "Values", values).(InsertBuilder) +} + +// Suffix adds an expression to the end of the query +func (b InsertBuilder) Suffix(sql string, args ...interface{}) InsertBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b InsertBuilder) SuffixExpr(expr Sqlizer) InsertBuilder { + return builder.Append(b, "Suffixes", expr).(InsertBuilder) +} + +// SetMap set columns and values for insert builder from a map of column name and value +// note that it will reset all previous columns and values was set if any +func (b InsertBuilder) SetMap(clauses map[string]interface{}) InsertBuilder { + // Keep the columns in a consistent order by sorting the column key string. + cols := make([]string, 0, len(clauses)) + for col := range clauses { + cols = append(cols, col) + } + sort.Strings(cols) + + vals := make([]interface{}, 0, len(clauses)) + for _, col := range cols { + vals = append(vals, clauses[col]) + } + + b = builder.Set(b, "Columns", cols).(InsertBuilder) + b = builder.Set(b, "Values", [][]interface{}{vals}).(InsertBuilder) + + return b +} + +// Select set Select clause for insert query +// If Values and Select are used, then Select has higher priority +func (b InsertBuilder) Select(sb SelectBuilder) InsertBuilder { + return builder.Set(b, "Select", &sb).(InsertBuilder) +} + +func (b InsertBuilder) statementKeyword(keyword string) InsertBuilder { + return builder.Set(b, "StatementKeyword", keyword).(InsertBuilder) +} diff --git a/vendor/github.com/Masterminds/squirrel/insert_ctx.go b/vendor/github.com/Masterminds/squirrel/insert_ctx.go new file mode 100644 index 0000000..4541c2f --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/insert_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *insertData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *insertData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b InsertBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(insertData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(insertData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b InsertBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(insertData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b InsertBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/vendor/github.com/Masterminds/squirrel/part.go b/vendor/github.com/Masterminds/squirrel/part.go new file mode 100644 index 0000000..c58f68f --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/part.go @@ -0,0 +1,63 @@ +package squirrel + +import ( + "fmt" + "io" +) + +type part struct { + pred interface{} + args []interface{} +} + +func newPart(pred interface{}, args ...interface{}) Sqlizer { + return &part{pred, args} +} + +func (p part) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case Sqlizer: + sql, args, err = nestedToSql(pred) + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string or Sqlizer, not %T", pred) + } + return +} + +func nestedToSql(s Sqlizer) (string, []interface{}, error) { + if raw, ok := s.(rawSqlizer); ok { + return raw.toSqlRaw() + } else { + return s.ToSql() + } +} + +func appendToSql(parts []Sqlizer, w io.Writer, sep string, args []interface{}) ([]interface{}, error) { + for i, p := range parts { + partSql, partArgs, err := nestedToSql(p) + if err != nil { + return nil, err + } else if len(partSql) == 0 { + continue + } + + if i > 0 { + _, err := io.WriteString(w, sep) + if err != nil { + return nil, err + } + } + + _, err = io.WriteString(w, partSql) + if err != nil { + return nil, err + } + args = append(args, partArgs...) + } + return args, nil +} diff --git a/vendor/github.com/Masterminds/squirrel/placeholder.go b/vendor/github.com/Masterminds/squirrel/placeholder.go new file mode 100644 index 0000000..8e97a6c --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/placeholder.go @@ -0,0 +1,114 @@ +package squirrel + +import ( + "bytes" + "fmt" + "strings" +) + +// PlaceholderFormat is the interface that wraps the ReplacePlaceholders method. +// +// ReplacePlaceholders takes a SQL statement and replaces each question mark +// placeholder with a (possibly different) SQL placeholder. +type PlaceholderFormat interface { + ReplacePlaceholders(sql string) (string, error) +} + +type placeholderDebugger interface { + debugPlaceholder() string +} + +var ( + // Question is a PlaceholderFormat instance that leaves placeholders as + // question marks. + Question = questionFormat{} + + // Dollar is a PlaceholderFormat instance that replaces placeholders with + // dollar-prefixed positional placeholders (e.g. $1, $2, $3). + Dollar = dollarFormat{} + + // Colon is a PlaceholderFormat instance that replaces placeholders with + // colon-prefixed positional placeholders (e.g. :1, :2, :3). + Colon = colonFormat{} + + // AtP is a PlaceholderFormat instance that replaces placeholders with + // "@p"-prefixed positional placeholders (e.g. @p1, @p2, @p3). + AtP = atpFormat{} +) + +type questionFormat struct{} + +func (questionFormat) ReplacePlaceholders(sql string) (string, error) { + return sql, nil +} + +func (questionFormat) debugPlaceholder() string { + return "?" +} + +type dollarFormat struct{} + +func (dollarFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "$") +} + +func (dollarFormat) debugPlaceholder() string { + return "$" +} + +type colonFormat struct{} + +func (colonFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, ":") +} + +func (colonFormat) debugPlaceholder() string { + return ":" +} + +type atpFormat struct{} + +func (atpFormat) ReplacePlaceholders(sql string) (string, error) { + return replacePositionalPlaceholders(sql, "@p") +} + +func (atpFormat) debugPlaceholder() string { + return "@p" +} + +// Placeholders returns a string with count ? placeholders joined with commas. +func Placeholders(count int) string { + if count < 1 { + return "" + } + + return strings.Repeat(",?", count)[1:] +} + +func replacePositionalPlaceholders(sql, prefix string) (string, error) { + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, "?") + if p == -1 { + break + } + + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + i++ + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "%s%d", prefix, i) + sql = sql[p+1:] + } + } + + buf.WriteString(sql) + return buf.String(), nil +} diff --git a/vendor/github.com/Masterminds/squirrel/row.go b/vendor/github.com/Masterminds/squirrel/row.go new file mode 100644 index 0000000..74ffda9 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/row.go @@ -0,0 +1,22 @@ +package squirrel + +// RowScanner is the interface that wraps the Scan method. +// +// Scan behaves like database/sql.Row.Scan. +type RowScanner interface { + Scan(...interface{}) error +} + +// Row wraps database/sql.Row to let squirrel return new errors on Scan. +type Row struct { + RowScanner + err error +} + +// Scan returns Row.err or calls RowScanner.Scan. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + return r.RowScanner.Scan(dest...) +} diff --git a/vendor/github.com/Masterminds/squirrel/select.go b/vendor/github.com/Masterminds/squirrel/select.go new file mode 100644 index 0000000..d55ce4c --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/select.go @@ -0,0 +1,403 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +type selectData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Options []string + Columns []Sqlizer + From Sqlizer + Joins []Sqlizer + WhereParts []Sqlizer + GroupBys []string + HavingParts []Sqlizer + OrderByParts []Sqlizer + Limit string + Offset string + Suffixes []Sqlizer +} + +func (d *selectData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *selectData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *selectData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *selectData) ToSql() (sqlStr string, args []interface{}, err error) { + sqlStr, args, err = d.toSqlRaw() + if err != nil { + return + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sqlStr) + return +} + +func (d *selectData) toSqlRaw() (sqlStr string, args []interface{}, err error) { + if len(d.Columns) == 0 { + err = fmt.Errorf("select statements must have at least one result column") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("SELECT ") + + if len(d.Options) > 0 { + sql.WriteString(strings.Join(d.Options, " ")) + sql.WriteString(" ") + } + + if len(d.Columns) > 0 { + args, err = appendToSql(d.Columns, sql, ", ", args) + if err != nil { + return + } + } + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.Joins) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Joins, sql, " ", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.GroupBys) > 0 { + sql.WriteString(" GROUP BY ") + sql.WriteString(strings.Join(d.GroupBys, ", ")) + } + + if len(d.HavingParts) > 0 { + sql.WriteString(" HAVING ") + args, err = appendToSql(d.HavingParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderByParts) > 0 { + sql.WriteString(" ORDER BY ") + args, err = appendToSql(d.OrderByParts, sql, ", ", args) + if err != nil { + return + } + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr = sql.String() + return +} + +// Builder + +// SelectBuilder builds SQL SELECT statements. +type SelectBuilder builder.Builder + +func init() { + builder.Register(SelectBuilder{}, selectData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b SelectBuilder) PlaceholderFormat(f PlaceholderFormat) SelectBuilder { + return builder.Set(b, "PlaceholderFormat", f).(SelectBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +// For most cases runner will be a database connection. +// +// Internally we use this to mock out the database connection for testing. +func (b SelectBuilder) RunWith(runner BaseRunner) SelectBuilder { + return setRunWith(b, runner).(SelectBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b SelectBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.Exec() +} + +// Query builds and Querys the query with the Runner set by RunWith. +func (b SelectBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.Query() +} + +// QueryRow builds and QueryRows the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRow() +} + +// Scan is a shortcut for QueryRow().Scan. +func (b SelectBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b SelectBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.ToSql() +} + +func (b SelectBuilder) toSqlRaw() (string, []interface{}, error) { + data := builder.GetStruct(b).(selectData) + return data.toSqlRaw() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b SelectBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b SelectBuilder) Prefix(sql string, args ...interface{}) SelectBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b SelectBuilder) PrefixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Prefixes", expr).(SelectBuilder) +} + +// Distinct adds a DISTINCT clause to the query. +func (b SelectBuilder) Distinct() SelectBuilder { + return b.Options("DISTINCT") +} + +// Options adds select option to the query +func (b SelectBuilder) Options(options ...string) SelectBuilder { + return builder.Extend(b, "Options", options).(SelectBuilder) +} + +// Columns adds result columns to the query. +func (b SelectBuilder) Columns(columns ...string) SelectBuilder { + parts := make([]interface{}, 0, len(columns)) + for _, str := range columns { + parts = append(parts, newPart(str)) + } + return builder.Extend(b, "Columns", parts).(SelectBuilder) +} + +// RemoveColumns remove all columns from query. +// Must add a new column with Column or Columns methods, otherwise +// return a error. +func (b SelectBuilder) RemoveColumns() SelectBuilder { + return builder.Delete(b, "Columns").(SelectBuilder) +} + +// Column adds a result column to the query. +// Unlike Columns, Column accepts args which will be bound to placeholders in +// the columns string, for example: +// Column("IF(col IN ("+squirrel.Placeholders(3)+"), 1, 0) as col", 1, 2, 3) +func (b SelectBuilder) Column(column interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Columns", newPart(column, args...)).(SelectBuilder) +} + +// From sets the FROM clause of the query. +func (b SelectBuilder) From(from string) SelectBuilder { + return builder.Set(b, "From", newPart(from)).(SelectBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b SelectBuilder) FromSelect(from SelectBuilder, alias string) SelectBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(SelectBuilder) +} + +// JoinClause adds a join clause to the query. +func (b SelectBuilder) JoinClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "Joins", newPart(pred, args...)).(SelectBuilder) +} + +// Join adds a JOIN clause to the query. +func (b SelectBuilder) Join(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("JOIN "+join, rest...) +} + +// LeftJoin adds a LEFT JOIN clause to the query. +func (b SelectBuilder) LeftJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("LEFT JOIN "+join, rest...) +} + +// RightJoin adds a RIGHT JOIN clause to the query. +func (b SelectBuilder) RightJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("RIGHT JOIN "+join, rest...) +} + +// InnerJoin adds a INNER JOIN clause to the query. +func (b SelectBuilder) InnerJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("INNER JOIN "+join, rest...) +} + +// CrossJoin adds a CROSS JOIN clause to the query. +func (b SelectBuilder) CrossJoin(join string, rest ...interface{}) SelectBuilder { + return b.JoinClause("CROSS JOIN "+join, rest...) +} + +// Where adds an expression to the WHERE clause of the query. +// +// Expressions are ANDed together in the generated SQL. +// +// Where accepts several types for its pred argument: +// +// nil OR "" - ignored. +// +// string - SQL expression. +// If the expression has SQL placeholders then a set of arguments must be passed +// as well, one for each placeholder. +// +// map[string]interface{} OR Eq - map of SQL expressions to values. Each key is +// transformed into an expression like " = ?", with the corresponding value +// bound to the placeholder. If the value is nil, the expression will be " +// IS NULL". If the value is an array or slice, the expression will be " IN +// (?,?,...)", with one placeholder for each item in the value. These expressions +// are ANDed together. +// +// Where will panic if pred isn't any of the above types. +func (b SelectBuilder) Where(pred interface{}, args ...interface{}) SelectBuilder { + if pred == nil || pred == "" { + return b + } + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(SelectBuilder) +} + +// GroupBy adds GROUP BY expressions to the query. +func (b SelectBuilder) GroupBy(groupBys ...string) SelectBuilder { + return builder.Extend(b, "GroupBys", groupBys).(SelectBuilder) +} + +// Having adds an expression to the HAVING clause of the query. +// +// See Where. +func (b SelectBuilder) Having(pred interface{}, rest ...interface{}) SelectBuilder { + return builder.Append(b, "HavingParts", newWherePart(pred, rest...)).(SelectBuilder) +} + +// OrderByClause adds ORDER BY clause to the query. +func (b SelectBuilder) OrderByClause(pred interface{}, args ...interface{}) SelectBuilder { + return builder.Append(b, "OrderByParts", newPart(pred, args...)).(SelectBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b SelectBuilder) OrderBy(orderBys ...string) SelectBuilder { + for _, orderBy := range orderBys { + b = b.OrderByClause(orderBy) + } + + return b +} + +// Limit sets a LIMIT clause on the query. +func (b SelectBuilder) Limit(limit uint64) SelectBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(SelectBuilder) +} + +// Limit ALL allows to access all records with limit +func (b SelectBuilder) RemoveLimit() SelectBuilder { + return builder.Delete(b, "Limit").(SelectBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b SelectBuilder) Offset(offset uint64) SelectBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(SelectBuilder) +} + +// RemoveOffset removes OFFSET clause. +func (b SelectBuilder) RemoveOffset() SelectBuilder { + return builder.Delete(b, "Offset").(SelectBuilder) +} + +// Suffix adds an expression to the end of the query +func (b SelectBuilder) Suffix(sql string, args ...interface{}) SelectBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b SelectBuilder) SuffixExpr(expr Sqlizer) SelectBuilder { + return builder.Append(b, "Suffixes", expr).(SelectBuilder) +} diff --git a/vendor/github.com/Masterminds/squirrel/select_ctx.go b/vendor/github.com/Masterminds/squirrel/select_ctx.go new file mode 100644 index 0000000..4c42c13 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/select_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *selectData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *selectData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b SelectBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(selectData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(selectData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b SelectBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(selectData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b SelectBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/vendor/github.com/Masterminds/squirrel/squirrel.go b/vendor/github.com/Masterminds/squirrel/squirrel.go new file mode 100644 index 0000000..46d456e --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/squirrel.go @@ -0,0 +1,183 @@ +// Package squirrel provides a fluent SQL generator. +// +// See https://github.com/Masterminds/squirrel for examples. +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "strings" + + "github.com/lann/builder" +) + +// Sqlizer is the interface that wraps the ToSql method. +// +// ToSql returns a SQL representation of the Sqlizer, along with a slice of args +// as passed to e.g. database/sql.Exec. It can also return an error. +type Sqlizer interface { + ToSql() (string, []interface{}, error) +} + +// rawSqlizer is expected to do what Sqlizer does, but without finalizing placeholders. +// This is useful for nested queries. +type rawSqlizer interface { + toSqlRaw() (string, []interface{}, error) +} + +// Execer is the interface that wraps the Exec method. +// +// Exec executes the given query as implemented by database/sql.Exec. +type Execer interface { + Exec(query string, args ...interface{}) (sql.Result, error) +} + +// Queryer is the interface that wraps the Query method. +// +// Query executes the given query as implemented by database/sql.Query. +type Queryer interface { + Query(query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRower is the interface that wraps the QueryRow method. +// +// QueryRow executes the given query as implemented by database/sql.QueryRow. +type QueryRower interface { + QueryRow(query string, args ...interface{}) RowScanner +} + +// BaseRunner groups the Execer and Queryer interfaces. +type BaseRunner interface { + Execer + Queryer +} + +// Runner groups the Execer, Queryer, and QueryRower interfaces. +type Runner interface { + Execer + Queryer + QueryRower +} + +// WrapStdSql wraps a type implementing the standard SQL interface with methods that +// squirrel expects. +func WrapStdSql(stdSql StdSql) Runner { + return &stdsqlRunner{stdSql} +} + +// StdSql encompasses the standard methods of the *sql.DB type, and other types that +// wrap these methods. +type StdSql interface { + Query(string, ...interface{}) (*sql.Rows, error) + QueryRow(string, ...interface{}) *sql.Row + Exec(string, ...interface{}) (sql.Result, error) +} + +type stdsqlRunner struct { + StdSql +} + +func (r *stdsqlRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSql.QueryRow(query, args...) +} + +func setRunWith(b interface{}, runner BaseRunner) interface{} { + switch r := runner.(type) { + case StdSqlCtx: + runner = WrapStdSqlCtx(r) + case StdSql: + runner = WrapStdSql(r) + } + return builder.Set(b, "RunWith", runner) +} + +// RunnerNotSet is returned by methods that need a Runner if it isn't set. +var RunnerNotSet = fmt.Errorf("cannot run; no Runner set (RunWith)") + +// RunnerNotQueryRunner is returned by QueryRow if the RunWith value doesn't implement QueryRower. +var RunnerNotQueryRunner = fmt.Errorf("cannot QueryRow; Runner is not a QueryRower") + +// ExecWith Execs the SQL returned by s with db. +func ExecWith(db Execer, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Exec(query, args...) +} + +// QueryWith Querys the SQL returned by s with db. +func QueryWith(db Queryer, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.Query(query, args...) +} + +// QueryRowWith QueryRows the SQL returned by s with db. +func QueryRowWith(db QueryRower, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRow(query, args...), err: err} +} + +// DebugSqlizer calls ToSql on s and shows the approximate SQL to be executed +// +// If ToSql returns an error, the result of this method will look like: +// "[ToSql error: %s]" or "[DebugSqlizer error: %s]" +// +// IMPORTANT: As its name suggests, this function should only be used for +// debugging. While the string result *might* be valid SQL, this function does +// not try very hard to ensure it. Additionally, executing the output of this +// function with any untrusted user input is certainly insecure. +func DebugSqlizer(s Sqlizer) string { + sql, args, err := s.ToSql() + if err != nil { + return fmt.Sprintf("[ToSql error: %s]", err) + } + + var placeholder string + downCast, ok := s.(placeholderDebugger) + if !ok { + placeholder = "?" + } else { + placeholder = downCast.debugPlaceholder() + } + // TODO: dedupe this with placeholder.go + buf := &bytes.Buffer{} + i := 0 + for { + p := strings.Index(sql, placeholder) + if p == -1 { + break + } + if len(sql[p:]) > 1 && sql[p:p+2] == "??" { // escape ?? => ? + buf.WriteString(sql[:p]) + buf.WriteString("?") + if len(sql[p:]) == 1 { + break + } + sql = sql[p+2:] + } else { + if i+1 > len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: too many placeholders in %#v for %d args]", + sql, len(args)) + } + buf.WriteString(sql[:p]) + fmt.Fprintf(buf, "'%v'", args[i]) + // advance our sql string "cursor" beyond the arg we placed + sql = sql[p+1:] + i++ + } + } + if i < len(args) { + return fmt.Sprintf( + "[DebugSqlizer error: not enough placeholders in %#v for %d args]", + sql, len(args)) + } + // "append" any remaning sql that won't need interpolating + buf.WriteString(sql) + return buf.String() +} diff --git a/vendor/github.com/Masterminds/squirrel/squirrel_ctx.go b/vendor/github.com/Masterminds/squirrel/squirrel_ctx.go new file mode 100644 index 0000000..c20148a --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/squirrel_ctx.go @@ -0,0 +1,93 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + "errors" +) + +// NoContextSupport is returned if a db doesn't support Context. +var NoContextSupport = errors.New("DB does not support Context") + +// ExecerContext is the interface that wraps the ExecContext method. +// +// Exec executes the given query as implemented by database/sql.ExecContext. +type ExecerContext interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) +} + +// QueryerContext is the interface that wraps the QueryContext method. +// +// QueryContext executes the given query as implemented by database/sql.QueryContext. +type QueryerContext interface { + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) +} + +// QueryRowerContext is the interface that wraps the QueryRowContext method. +// +// QueryRowContext executes the given query as implemented by database/sql.QueryRowContext. +type QueryRowerContext interface { + QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner +} + +// RunnerContext groups the Runner interface, along with the Context versions of each of +// its methods +type RunnerContext interface { + Runner + QueryerContext + QueryRowerContext + ExecerContext +} + +// WrapStdSqlCtx wraps a type implementing the standard SQL interface plus the context +// versions of the methods with methods that squirrel expects. +func WrapStdSqlCtx(stdSqlCtx StdSqlCtx) RunnerContext { + return &stdsqlCtxRunner{stdSqlCtx} +} + +// StdSqlCtx encompasses the standard methods of the *sql.DB type, along with the Context +// versions of those methods, and other types that wrap these methods. +type StdSqlCtx interface { + StdSql + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) +} + +type stdsqlCtxRunner struct { + StdSqlCtx +} + +func (r *stdsqlCtxRunner) QueryRow(query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRow(query, args...) +} + +func (r *stdsqlCtxRunner) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + return r.StdSqlCtx.QueryRowContext(ctx, query, args...) +} + +// ExecContextWith ExecContexts the SQL returned by s with db. +func ExecContextWith(ctx context.Context, db ExecerContext, s Sqlizer) (res sql.Result, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.ExecContext(ctx, query, args...) +} + +// QueryContextWith QueryContexts the SQL returned by s with db. +func QueryContextWith(ctx context.Context, db QueryerContext, s Sqlizer) (rows *sql.Rows, err error) { + query, args, err := s.ToSql() + if err != nil { + return + } + return db.QueryContext(ctx, query, args...) +} + +// QueryRowContextWith QueryRowContexts the SQL returned by s with db. +func QueryRowContextWith(ctx context.Context, db QueryRowerContext, s Sqlizer) RowScanner { + query, args, err := s.ToSql() + return &Row{RowScanner: db.QueryRowContext(ctx, query, args...), err: err} +} diff --git a/vendor/github.com/Masterminds/squirrel/statement.go b/vendor/github.com/Masterminds/squirrel/statement.go new file mode 100644 index 0000000..9420c67 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/statement.go @@ -0,0 +1,104 @@ +package squirrel + +import "github.com/lann/builder" + +// StatementBuilderType is the type of StatementBuilder. +type StatementBuilderType builder.Builder + +// Select returns a SelectBuilder for this StatementBuilderType. +func (b StatementBuilderType) Select(columns ...string) SelectBuilder { + return SelectBuilder(b).Columns(columns...) +} + +// Insert returns a InsertBuilder for this StatementBuilderType. +func (b StatementBuilderType) Insert(into string) InsertBuilder { + return InsertBuilder(b).Into(into) +} + +// Replace returns a InsertBuilder for this StatementBuilderType with the +// statement keyword set to "REPLACE". +func (b StatementBuilderType) Replace(into string) InsertBuilder { + return InsertBuilder(b).statementKeyword("REPLACE").Into(into) +} + +// Update returns a UpdateBuilder for this StatementBuilderType. +func (b StatementBuilderType) Update(table string) UpdateBuilder { + return UpdateBuilder(b).Table(table) +} + +// Delete returns a DeleteBuilder for this StatementBuilderType. +func (b StatementBuilderType) Delete(from string) DeleteBuilder { + return DeleteBuilder(b).From(from) +} + +// PlaceholderFormat sets the PlaceholderFormat field for any child builders. +func (b StatementBuilderType) PlaceholderFormat(f PlaceholderFormat) StatementBuilderType { + return builder.Set(b, "PlaceholderFormat", f).(StatementBuilderType) +} + +// RunWith sets the RunWith field for any child builders. +func (b StatementBuilderType) RunWith(runner BaseRunner) StatementBuilderType { + return setRunWith(b, runner).(StatementBuilderType) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b StatementBuilderType) Where(pred interface{}, args ...interface{}) StatementBuilderType { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(StatementBuilderType) +} + +// StatementBuilder is a parent builder for other builders, e.g. SelectBuilder. +var StatementBuilder = StatementBuilderType(builder.EmptyBuilder).PlaceholderFormat(Question) + +// Select returns a new SelectBuilder, optionally setting some result columns. +// +// See SelectBuilder.Columns. +func Select(columns ...string) SelectBuilder { + return StatementBuilder.Select(columns...) +} + +// Insert returns a new InsertBuilder with the given table name. +// +// See InsertBuilder.Into. +func Insert(into string) InsertBuilder { + return StatementBuilder.Insert(into) +} + +// Replace returns a new InsertBuilder with the statement keyword set to +// "REPLACE" and with the given table name. +// +// See InsertBuilder.Into. +func Replace(into string) InsertBuilder { + return StatementBuilder.Replace(into) +} + +// Update returns a new UpdateBuilder with the given table name. +// +// See UpdateBuilder.Table. +func Update(table string) UpdateBuilder { + return StatementBuilder.Update(table) +} + +// Delete returns a new DeleteBuilder with the given table name. +// +// See DeleteBuilder.Table. +func Delete(from string) DeleteBuilder { + return StatementBuilder.Delete(from) +} + +// Case returns a new CaseBuilder +// "what" represents case value +func Case(what ...interface{}) CaseBuilder { + b := CaseBuilder(builder.EmptyBuilder) + + switch len(what) { + case 0: + case 1: + b = b.what(what[0]) + default: + b = b.what(newPart(what[0], what[1:]...)) + + } + return b +} diff --git a/vendor/github.com/Masterminds/squirrel/stmtcacher.go b/vendor/github.com/Masterminds/squirrel/stmtcacher.go new file mode 100644 index 0000000..5bf267a --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/stmtcacher.go @@ -0,0 +1,121 @@ +package squirrel + +import ( + "database/sql" + "fmt" + "sync" +) + +// Prepareer is the interface that wraps the Prepare method. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +type Preparer interface { + Prepare(query string) (*sql.Stmt, error) +} + +// DBProxy groups the Execer, Queryer, QueryRower, and Preparer interfaces. +type DBProxy interface { + Execer + Queryer + QueryRower + Preparer +} + +// NOTE: NewStmtCache is defined in stmtcacher_ctx.go (Go >= 1.8) or stmtcacher_noctx.go (Go < 1.8). + +// StmtCache wraps and delegates down to a Preparer type +// +// It also automatically prepares all statements sent to the underlying Preparer calls +// for Exec, Query and QueryRow and caches the returns *sql.Stmt using the provided +// query as the key. So that it can be automatically re-used. +type StmtCache struct { + prep Preparer + cache map[string]*sql.Stmt + mu sync.Mutex +} + +// Prepare delegates down to the underlying Preparer and caches the result +// using the provided query as a key +func (sc *StmtCache) Prepare(query string) (*sql.Stmt, error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := sc.prep.Prepare(query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// Exec delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Exec(query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Exec(args...) +} + +// Query delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) Query(query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.Prepare(query) + if err != nil { + return + } + return stmt.Query(args...) +} + +// QueryRow delegates down to the underlying Preparer using a prepared statement +func (sc *StmtCache) QueryRow(query string, args ...interface{}) RowScanner { + stmt, err := sc.Prepare(query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRow(args...) +} + +// Clear removes and closes all the currently cached prepared statements +func (sc *StmtCache) Clear() (err error) { + sc.mu.Lock() + defer sc.mu.Unlock() + + for key, stmt := range sc.cache { + delete(sc.cache, key) + + if stmt == nil { + continue + } + + if cerr := stmt.Close(); cerr != nil { + err = cerr + } + } + + if err != nil { + return fmt.Errorf("one or more Stmt.Close failed; last error: %v", err) + } + + return +} + +type DBProxyBeginner interface { + DBProxy + Begin() (*sql.Tx, error) +} + +type stmtCacheProxy struct { + DBProxy + db *sql.DB +} + +func NewStmtCacheProxy(db *sql.DB) DBProxyBeginner { + return &stmtCacheProxy{DBProxy: NewStmtCache(db), db: db} +} + +func (sp *stmtCacheProxy) Begin() (*sql.Tx, error) { + return sp.db.Begin() +} diff --git a/vendor/github.com/Masterminds/squirrel/stmtcacher_ctx.go b/vendor/github.com/Masterminds/squirrel/stmtcacher_ctx.go new file mode 100644 index 0000000..53603cf --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/stmtcacher_ctx.go @@ -0,0 +1,86 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" +) + +// PrepareerContext is the interface that wraps the Prepare and PrepareContext methods. +// +// Prepare executes the given query as implemented by database/sql.Prepare. +// PrepareContext executes the given query as implemented by database/sql.PrepareContext. +type PreparerContext interface { + Preparer + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) +} + +// DBProxyContext groups the Execer, Queryer, QueryRower and PreparerContext interfaces. +type DBProxyContext interface { + Execer + Queryer + QueryRower + PreparerContext +} + +// NewStmtCache returns a *StmtCache wrapping a PreparerContext that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep PreparerContext) *StmtCache { + return &StmtCache{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep PreparerContext) DBProxyContext { + return NewStmtCache(prep) +} + +// PrepareContext delegates down to the underlying PreparerContext and caches the result +// using the provided query as a key +func (sc *StmtCache) PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) { + ctxPrep, ok := sc.prep.(PreparerContext) + if !ok { + return nil, NoContextSupport + } + sc.mu.Lock() + defer sc.mu.Unlock() + stmt, ok := sc.cache[query] + if ok { + return stmt, nil + } + stmt, err := ctxPrep.PrepareContext(ctx, query) + if err == nil { + sc.cache[query] = stmt + } + return stmt, err +} + +// ExecContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) ExecContext(ctx context.Context, query string, args ...interface{}) (res sql.Result, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.ExecContext(ctx, args...) +} + +// QueryContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryContext(ctx context.Context, query string, args ...interface{}) (rows *sql.Rows, err error) { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return + } + return stmt.QueryContext(ctx, args...) +} + +// QueryRowContext delegates down to the underlying PreparerContext using a prepared statement +func (sc *StmtCache) QueryRowContext(ctx context.Context, query string, args ...interface{}) RowScanner { + stmt, err := sc.PrepareContext(ctx, query) + if err != nil { + return &Row{err: err} + } + return stmt.QueryRowContext(ctx, args...) +} diff --git a/vendor/github.com/Masterminds/squirrel/stmtcacher_noctx.go b/vendor/github.com/Masterminds/squirrel/stmtcacher_noctx.go new file mode 100644 index 0000000..deac967 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/stmtcacher_noctx.go @@ -0,0 +1,21 @@ +// +build !go1.8 + +package squirrel + +import ( + "database/sql" +) + +// NewStmtCacher returns a DBProxy wrapping prep that caches Prepared Stmts. +// +// Stmts are cached based on the string value of their queries. +func NewStmtCache(prep Preparer) *StmtCache { + return &StmtCacher{prep: prep, cache: make(map[string]*sql.Stmt)} +} + +// NewStmtCacher is deprecated +// +// Use NewStmtCache instead +func NewStmtCacher(prep Preparer) DBProxy { + return NewStmtCache(prep) +} diff --git a/vendor/github.com/Masterminds/squirrel/update.go b/vendor/github.com/Masterminds/squirrel/update.go new file mode 100644 index 0000000..eb2a9c4 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/update.go @@ -0,0 +1,288 @@ +package squirrel + +import ( + "bytes" + "database/sql" + "fmt" + "sort" + "strings" + + "github.com/lann/builder" +) + +type updateData struct { + PlaceholderFormat PlaceholderFormat + RunWith BaseRunner + Prefixes []Sqlizer + Table string + SetClauses []setClause + From Sqlizer + WhereParts []Sqlizer + OrderBys []string + Limit string + Offset string + Suffixes []Sqlizer +} + +type setClause struct { + column string + value interface{} +} + +func (d *updateData) Exec() (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return ExecWith(d.RunWith, d) +} + +func (d *updateData) Query() (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + return QueryWith(d.RunWith, d) +} + +func (d *updateData) QueryRow() RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRower) + if !ok { + return &Row{err: RunnerNotQueryRunner} + } + return QueryRowWith(queryRower, d) +} + +func (d *updateData) ToSql() (sqlStr string, args []interface{}, err error) { + if len(d.Table) == 0 { + err = fmt.Errorf("update statements must specify a table") + return + } + if len(d.SetClauses) == 0 { + err = fmt.Errorf("update statements must have at least one Set clause") + return + } + + sql := &bytes.Buffer{} + + if len(d.Prefixes) > 0 { + args, err = appendToSql(d.Prefixes, sql, " ", args) + if err != nil { + return + } + + sql.WriteString(" ") + } + + sql.WriteString("UPDATE ") + sql.WriteString(d.Table) + + sql.WriteString(" SET ") + setSqls := make([]string, len(d.SetClauses)) + for i, setClause := range d.SetClauses { + var valSql string + if vs, ok := setClause.value.(Sqlizer); ok { + vsql, vargs, err := vs.ToSql() + if err != nil { + return "", nil, err + } + if _, ok := vs.(SelectBuilder); ok { + valSql = fmt.Sprintf("(%s)", vsql) + } else { + valSql = vsql + } + args = append(args, vargs...) + } else { + valSql = "?" + args = append(args, setClause.value) + } + setSqls[i] = fmt.Sprintf("%s = %s", setClause.column, valSql) + } + sql.WriteString(strings.Join(setSqls, ", ")) + + if d.From != nil { + sql.WriteString(" FROM ") + args, err = appendToSql([]Sqlizer{d.From}, sql, "", args) + if err != nil { + return + } + } + + if len(d.WhereParts) > 0 { + sql.WriteString(" WHERE ") + args, err = appendToSql(d.WhereParts, sql, " AND ", args) + if err != nil { + return + } + } + + if len(d.OrderBys) > 0 { + sql.WriteString(" ORDER BY ") + sql.WriteString(strings.Join(d.OrderBys, ", ")) + } + + if len(d.Limit) > 0 { + sql.WriteString(" LIMIT ") + sql.WriteString(d.Limit) + } + + if len(d.Offset) > 0 { + sql.WriteString(" OFFSET ") + sql.WriteString(d.Offset) + } + + if len(d.Suffixes) > 0 { + sql.WriteString(" ") + args, err = appendToSql(d.Suffixes, sql, " ", args) + if err != nil { + return + } + } + + sqlStr, err = d.PlaceholderFormat.ReplacePlaceholders(sql.String()) + return +} + +// Builder + +// UpdateBuilder builds SQL UPDATE statements. +type UpdateBuilder builder.Builder + +func init() { + builder.Register(UpdateBuilder{}, updateData{}) +} + +// Format methods + +// PlaceholderFormat sets PlaceholderFormat (e.g. Question or Dollar) for the +// query. +func (b UpdateBuilder) PlaceholderFormat(f PlaceholderFormat) UpdateBuilder { + return builder.Set(b, "PlaceholderFormat", f).(UpdateBuilder) +} + +// Runner methods + +// RunWith sets a Runner (like database/sql.DB) to be used with e.g. Exec. +func (b UpdateBuilder) RunWith(runner BaseRunner) UpdateBuilder { + return setRunWith(b, runner).(UpdateBuilder) +} + +// Exec builds and Execs the query with the Runner set by RunWith. +func (b UpdateBuilder) Exec() (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.Exec() +} + +func (b UpdateBuilder) Query() (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.Query() +} + +func (b UpdateBuilder) QueryRow() RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRow() +} + +func (b UpdateBuilder) Scan(dest ...interface{}) error { + return b.QueryRow().Scan(dest...) +} + +// SQL methods + +// ToSql builds the query into a SQL string and bound args. +func (b UpdateBuilder) ToSql() (string, []interface{}, error) { + data := builder.GetStruct(b).(updateData) + return data.ToSql() +} + +// MustSql builds the query into a SQL string and bound args. +// It panics if there are any errors. +func (b UpdateBuilder) MustSql() (string, []interface{}) { + sql, args, err := b.ToSql() + if err != nil { + panic(err) + } + return sql, args +} + +// Prefix adds an expression to the beginning of the query +func (b UpdateBuilder) Prefix(sql string, args ...interface{}) UpdateBuilder { + return b.PrefixExpr(Expr(sql, args...)) +} + +// PrefixExpr adds an expression to the very beginning of the query +func (b UpdateBuilder) PrefixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Prefixes", expr).(UpdateBuilder) +} + +// Table sets the table to be updated. +func (b UpdateBuilder) Table(table string) UpdateBuilder { + return builder.Set(b, "Table", table).(UpdateBuilder) +} + +// Set adds SET clauses to the query. +func (b UpdateBuilder) Set(column string, value interface{}) UpdateBuilder { + return builder.Append(b, "SetClauses", setClause{column: column, value: value}).(UpdateBuilder) +} + +// SetMap is a convenience method which calls .Set for each key/value pair in clauses. +func (b UpdateBuilder) SetMap(clauses map[string]interface{}) UpdateBuilder { + keys := make([]string, len(clauses)) + i := 0 + for key := range clauses { + keys[i] = key + i++ + } + sort.Strings(keys) + for _, key := range keys { + val, _ := clauses[key] + b = b.Set(key, val) + } + return b +} + +// From adds FROM clause to the query +// FROM is valid construct in postgresql only. +func (b UpdateBuilder) From(from string) UpdateBuilder { + return builder.Set(b, "From", newPart(from)).(UpdateBuilder) +} + +// FromSelect sets a subquery into the FROM clause of the query. +func (b UpdateBuilder) FromSelect(from SelectBuilder, alias string) UpdateBuilder { + // Prevent misnumbered parameters in nested selects (#183). + from = from.PlaceholderFormat(Question) + return builder.Set(b, "From", Alias(from, alias)).(UpdateBuilder) +} + +// Where adds WHERE expressions to the query. +// +// See SelectBuilder.Where for more information. +func (b UpdateBuilder) Where(pred interface{}, args ...interface{}) UpdateBuilder { + return builder.Append(b, "WhereParts", newWherePart(pred, args...)).(UpdateBuilder) +} + +// OrderBy adds ORDER BY expressions to the query. +func (b UpdateBuilder) OrderBy(orderBys ...string) UpdateBuilder { + return builder.Extend(b, "OrderBys", orderBys).(UpdateBuilder) +} + +// Limit sets a LIMIT clause on the query. +func (b UpdateBuilder) Limit(limit uint64) UpdateBuilder { + return builder.Set(b, "Limit", fmt.Sprintf("%d", limit)).(UpdateBuilder) +} + +// Offset sets a OFFSET clause on the query. +func (b UpdateBuilder) Offset(offset uint64) UpdateBuilder { + return builder.Set(b, "Offset", fmt.Sprintf("%d", offset)).(UpdateBuilder) +} + +// Suffix adds an expression to the end of the query +func (b UpdateBuilder) Suffix(sql string, args ...interface{}) UpdateBuilder { + return b.SuffixExpr(Expr(sql, args...)) +} + +// SuffixExpr adds an expression to the end of the query +func (b UpdateBuilder) SuffixExpr(expr Sqlizer) UpdateBuilder { + return builder.Append(b, "Suffixes", expr).(UpdateBuilder) +} diff --git a/vendor/github.com/Masterminds/squirrel/update_ctx.go b/vendor/github.com/Masterminds/squirrel/update_ctx.go new file mode 100644 index 0000000..ad479f9 --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/update_ctx.go @@ -0,0 +1,69 @@ +// +build go1.8 + +package squirrel + +import ( + "context" + "database/sql" + + "github.com/lann/builder" +) + +func (d *updateData) ExecContext(ctx context.Context) (sql.Result, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(ExecerContext) + if !ok { + return nil, NoContextSupport + } + return ExecContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryContext(ctx context.Context) (*sql.Rows, error) { + if d.RunWith == nil { + return nil, RunnerNotSet + } + ctxRunner, ok := d.RunWith.(QueryerContext) + if !ok { + return nil, NoContextSupport + } + return QueryContextWith(ctx, ctxRunner, d) +} + +func (d *updateData) QueryRowContext(ctx context.Context) RowScanner { + if d.RunWith == nil { + return &Row{err: RunnerNotSet} + } + queryRower, ok := d.RunWith.(QueryRowerContext) + if !ok { + if _, ok := d.RunWith.(QueryerContext); !ok { + return &Row{err: RunnerNotQueryRunner} + } + return &Row{err: NoContextSupport} + } + return QueryRowContextWith(ctx, queryRower, d) +} + +// ExecContext builds and ExecContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) ExecContext(ctx context.Context) (sql.Result, error) { + data := builder.GetStruct(b).(updateData) + return data.ExecContext(ctx) +} + +// QueryContext builds and QueryContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryContext(ctx context.Context) (*sql.Rows, error) { + data := builder.GetStruct(b).(updateData) + return data.QueryContext(ctx) +} + +// QueryRowContext builds and QueryRowContexts the query with the Runner set by RunWith. +func (b UpdateBuilder) QueryRowContext(ctx context.Context) RowScanner { + data := builder.GetStruct(b).(updateData) + return data.QueryRowContext(ctx) +} + +// ScanContext is a shortcut for QueryRowContext().Scan. +func (b UpdateBuilder) ScanContext(ctx context.Context, dest ...interface{}) error { + return b.QueryRowContext(ctx).Scan(dest...) +} diff --git a/vendor/github.com/Masterminds/squirrel/where.go b/vendor/github.com/Masterminds/squirrel/where.go new file mode 100644 index 0000000..976b63a --- /dev/null +++ b/vendor/github.com/Masterminds/squirrel/where.go @@ -0,0 +1,30 @@ +package squirrel + +import ( + "fmt" +) + +type wherePart part + +func newWherePart(pred interface{}, args ...interface{}) Sqlizer { + return &wherePart{pred: pred, args: args} +} + +func (p wherePart) ToSql() (sql string, args []interface{}, err error) { + switch pred := p.pred.(type) { + case nil: + // no-op + case rawSqlizer: + return pred.toSqlRaw() + case Sqlizer: + return pred.ToSql() + case map[string]interface{}: + return Eq(pred).ToSql() + case string: + sql = pred + args = p.args + default: + err = fmt.Errorf("expected string-keyed map or string, not %T", pred) + } + return +} diff --git a/vendor/github.com/bahlo/generic-list-go/LICENSE b/vendor/github.com/bahlo/generic-list-go/LICENSE new file mode 100644 index 0000000..6a66aea --- /dev/null +++ b/vendor/github.com/bahlo/generic-list-go/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009 The Go Authors. 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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/bahlo/generic-list-go/README.md b/vendor/github.com/bahlo/generic-list-go/README.md new file mode 100644 index 0000000..68bbce9 --- /dev/null +++ b/vendor/github.com/bahlo/generic-list-go/README.md @@ -0,0 +1,5 @@ +# generic-list-go [![CI](https://github.com/bahlo/generic-list-go/actions/workflows/ci.yml/badge.svg)](https://github.com/bahlo/generic-list-go/actions/workflows/ci.yml) + +Go [container/list](https://pkg.go.dev/container/list) but with generics. + +The code is based on `container/list` in `go1.18beta2`. diff --git a/vendor/github.com/bahlo/generic-list-go/list.go b/vendor/github.com/bahlo/generic-list-go/list.go new file mode 100644 index 0000000..a06a7c6 --- /dev/null +++ b/vendor/github.com/bahlo/generic-list-go/list.go @@ -0,0 +1,235 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package list implements a doubly linked list. +// +// To iterate over a list (where l is a *List): +// for e := l.Front(); e != nil; e = e.Next() { +// // do something with e.Value +// } +// +package list + +// Element is an element of a linked list. +type Element[T any] struct { + // Next and previous pointers in the doubly-linked list of elements. + // To simplify the implementation, internally a list l is implemented + // as a ring, such that &l.root is both the next element of the last + // list element (l.Back()) and the previous element of the first list + // element (l.Front()). + next, prev *Element[T] + + // The list to which this element belongs. + list *List[T] + + // The value stored with this element. + Value T +} + +// Next returns the next list element or nil. +func (e *Element[T]) Next() *Element[T] { + if p := e.next; e.list != nil && p != &e.list.root { + return p + } + return nil +} + +// Prev returns the previous list element or nil. +func (e *Element[T]) Prev() *Element[T] { + if p := e.prev; e.list != nil && p != &e.list.root { + return p + } + return nil +} + +// List represents a doubly linked list. +// The zero value for List is an empty list ready to use. +type List[T any] struct { + root Element[T] // sentinel list element, only &root, root.prev, and root.next are used + len int // current list length excluding (this) sentinel element +} + +// Init initializes or clears list l. +func (l *List[T]) Init() *List[T] { + l.root.next = &l.root + l.root.prev = &l.root + l.len = 0 + return l +} + +// New returns an initialized list. +func New[T any]() *List[T] { return new(List[T]).Init() } + +// Len returns the number of elements of list l. +// The complexity is O(1). +func (l *List[T]) Len() int { return l.len } + +// Front returns the first element of list l or nil if the list is empty. +func (l *List[T]) Front() *Element[T] { + if l.len == 0 { + return nil + } + return l.root.next +} + +// Back returns the last element of list l or nil if the list is empty. +func (l *List[T]) Back() *Element[T] { + if l.len == 0 { + return nil + } + return l.root.prev +} + +// lazyInit lazily initializes a zero List value. +func (l *List[T]) lazyInit() { + if l.root.next == nil { + l.Init() + } +} + +// insert inserts e after at, increments l.len, and returns e. +func (l *List[T]) insert(e, at *Element[T]) *Element[T] { + e.prev = at + e.next = at.next + e.prev.next = e + e.next.prev = e + e.list = l + l.len++ + return e +} + +// insertValue is a convenience wrapper for insert(&Element{Value: v}, at). +func (l *List[T]) insertValue(v T, at *Element[T]) *Element[T] { + return l.insert(&Element[T]{Value: v}, at) +} + +// remove removes e from its list, decrements l.len +func (l *List[T]) remove(e *Element[T]) { + e.prev.next = e.next + e.next.prev = e.prev + e.next = nil // avoid memory leaks + e.prev = nil // avoid memory leaks + e.list = nil + l.len-- +} + +// move moves e to next to at. +func (l *List[T]) move(e, at *Element[T]) { + if e == at { + return + } + e.prev.next = e.next + e.next.prev = e.prev + + e.prev = at + e.next = at.next + e.prev.next = e + e.next.prev = e +} + +// Remove removes e from l if e is an element of list l. +// It returns the element value e.Value. +// The element must not be nil. +func (l *List[T]) Remove(e *Element[T]) T { + if e.list == l { + // if e.list == l, l must have been initialized when e was inserted + // in l or l == nil (e is a zero Element) and l.remove will crash + l.remove(e) + } + return e.Value +} + +// PushFront inserts a new element e with value v at the front of list l and returns e. +func (l *List[T]) PushFront(v T) *Element[T] { + l.lazyInit() + return l.insertValue(v, &l.root) +} + +// PushBack inserts a new element e with value v at the back of list l and returns e. +func (l *List[T]) PushBack(v T) *Element[T] { + l.lazyInit() + return l.insertValue(v, l.root.prev) +} + +// InsertBefore inserts a new element e with value v immediately before mark and returns e. +// If mark is not an element of l, the list is not modified. +// The mark must not be nil. +func (l *List[T]) InsertBefore(v T, mark *Element[T]) *Element[T] { + if mark.list != l { + return nil + } + // see comment in List.Remove about initialization of l + return l.insertValue(v, mark.prev) +} + +// InsertAfter inserts a new element e with value v immediately after mark and returns e. +// If mark is not an element of l, the list is not modified. +// The mark must not be nil. +func (l *List[T]) InsertAfter(v T, mark *Element[T]) *Element[T] { + if mark.list != l { + return nil + } + // see comment in List.Remove about initialization of l + return l.insertValue(v, mark) +} + +// MoveToFront moves element e to the front of list l. +// If e is not an element of l, the list is not modified. +// The element must not be nil. +func (l *List[T]) MoveToFront(e *Element[T]) { + if e.list != l || l.root.next == e { + return + } + // see comment in List.Remove about initialization of l + l.move(e, &l.root) +} + +// MoveToBack moves element e to the back of list l. +// If e is not an element of l, the list is not modified. +// The element must not be nil. +func (l *List[T]) MoveToBack(e *Element[T]) { + if e.list != l || l.root.prev == e { + return + } + // see comment in List.Remove about initialization of l + l.move(e, l.root.prev) +} + +// MoveBefore moves element e to its new position before mark. +// If e or mark is not an element of l, or e == mark, the list is not modified. +// The element and mark must not be nil. +func (l *List[T]) MoveBefore(e, mark *Element[T]) { + if e.list != l || e == mark || mark.list != l { + return + } + l.move(e, mark.prev) +} + +// MoveAfter moves element e to its new position after mark. +// If e or mark is not an element of l, or e == mark, the list is not modified. +// The element and mark must not be nil. +func (l *List[T]) MoveAfter(e, mark *Element[T]) { + if e.list != l || e == mark || mark.list != l { + return + } + l.move(e, mark) +} + +// PushBackList inserts a copy of another list at the back of list l. +// The lists l and other may be the same. They must not be nil. +func (l *List[T]) PushBackList(other *List[T]) { + l.lazyInit() + for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { + l.insertValue(e.Value, l.root.prev) + } +} + +// PushFrontList inserts a copy of another list at the front of list l. +// The lists l and other may be the same. They must not be nil. +func (l *List[T]) PushFrontList(other *List[T]) { + l.lazyInit() + for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { + l.insertValue(e.Value, &l.root) + } +} diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE new file mode 100644 index 0000000..339177b --- /dev/null +++ b/vendor/github.com/beorn7/perks/LICENSE @@ -0,0 +1,20 @@ +Copyright (C) 2013 Blake Mizerany + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/beorn7/perks/quantile/exampledata.txt b/vendor/github.com/beorn7/perks/quantile/exampledata.txt new file mode 100644 index 0000000..1602287 --- /dev/null +++ b/vendor/github.com/beorn7/perks/quantile/exampledata.txt @@ -0,0 +1,2388 @@ +8 +5 +26 +12 +5 +235 +13 +6 +28 +30 +3 +3 +3 +3 +5 +2 +33 +7 +2 +4 +7 +12 +14 +5 +8 +3 +10 +4 +5 +3 +6 +6 +209 +20 +3 +10 +14 +3 +4 +6 +8 +5 +11 +7 +3 +2 +3 +3 +212 +5 +222 +4 +10 +10 +5 +6 +3 +8 +3 +10 +254 +220 +2 +3 +5 +24 +5 +4 +222 +7 +3 +3 +223 +8 +15 +12 +14 +14 +3 +2 +2 +3 +13 +3 +11 +4 +4 +6 +5 +7 +13 +5 +3 +5 +2 +5 +3 +5 +2 +7 +15 +17 +14 +3 +6 +6 +3 +17 +5 +4 +7 +6 +4 +4 +8 +6 +8 +3 +9 +3 +6 +3 +4 +5 +3 +3 +660 +4 +6 +10 +3 +6 +3 +2 +5 +13 +2 +4 +4 +10 +4 +8 +4 +3 +7 +9 +9 +3 +10 +37 +3 +13 +4 +12 +3 +6 +10 +8 +5 +21 +2 +3 +8 +3 +2 +3 +3 +4 +12 +2 +4 +8 +8 +4 +3 +2 +20 +1 +6 +32 +2 +11 +6 +18 +3 +8 +11 +3 +212 +3 +4 +2 +6 +7 +12 +11 +3 +2 +16 +10 +6 +4 +6 +3 +2 +7 +3 +2 +2 +2 +2 +5 +6 +4 +3 +10 +3 +4 +6 +5 +3 +4 +4 +5 +6 +4 +3 +4 +4 +5 +7 +5 +5 +3 +2 +7 +2 +4 +12 +4 +5 +6 +2 +4 +4 +8 +4 +15 +13 +7 +16 +5 +3 +23 +5 +5 +7 +3 +2 +9 +8 +7 +5 +8 +11 +4 +10 +76 +4 +47 +4 +3 +2 +7 +4 +2 +3 +37 +10 +4 +2 +20 +5 +4 +4 +10 +10 +4 +3 +7 +23 +240 +7 +13 +5 +5 +3 +3 +2 +5 +4 +2 +8 +7 +19 +2 +23 +8 +7 +2 +5 +3 +8 +3 +8 +13 +5 +5 +5 +2 +3 +23 +4 +9 +8 +4 +3 +3 +5 +220 +2 +3 +4 +6 +14 +3 +53 +6 +2 +5 +18 +6 +3 +219 +6 +5 +2 +5 +3 +6 +5 +15 +4 +3 +17 +3 +2 +4 +7 +2 +3 +3 +4 +4 +3 +2 +664 +6 +3 +23 +5 +5 +16 +5 +8 +2 +4 +2 +24 +12 +3 +2 +3 +5 +8 +3 +5 +4 +3 +14 +3 +5 +8 +2 +3 +7 +9 +4 +2 +3 +6 +8 +4 +3 +4 +6 +5 +3 +3 +6 +3 +19 +4 +4 +6 +3 +6 +3 +5 +22 +5 +4 +4 +3 +8 +11 +4 +9 +7 +6 +13 +4 +4 +4 +6 +17 +9 +3 +3 +3 +4 +3 +221 +5 +11 +3 +4 +2 +12 +6 +3 +5 +7 +5 +7 +4 +9 +7 +14 +37 +19 +217 +16 +3 +5 +2 +2 +7 +19 +7 +6 +7 +4 +24 +5 +11 +4 +7 +7 +9 +13 +3 +4 +3 +6 +28 +4 +4 +5 +5 +2 +5 +6 +4 +4 +6 +10 +5 +4 +3 +2 +3 +3 +6 +5 +5 +4 +3 +2 +3 +7 +4 +6 +18 +16 +8 +16 +4 +5 +8 +6 +9 +13 +1545 +6 +215 +6 +5 +6 +3 +45 +31 +5 +2 +2 +4 +3 +3 +2 +5 +4 +3 +5 +7 +7 +4 +5 +8 +5 +4 +749 +2 +31 +9 +11 +2 +11 +5 +4 +4 +7 +9 +11 +4 +5 +4 +7 +3 +4 +6 +2 +15 +3 +4 +3 +4 +3 +5 +2 +13 +5 +5 +3 +3 +23 +4 +4 +5 +7 +4 +13 +2 +4 +3 +4 +2 +6 +2 +7 +3 +5 +5 +3 +29 +5 +4 +4 +3 +10 +2 +3 +79 +16 +6 +6 +7 +7 +3 +5 +5 +7 +4 +3 +7 +9 +5 +6 +5 +9 +6 +3 +6 +4 +17 +2 +10 +9 +3 +6 +2 +3 +21 +22 +5 +11 +4 +2 +17 +2 +224 +2 +14 +3 +4 +4 +2 +4 +4 +4 +4 +5 +3 +4 +4 +10 +2 +6 +3 +3 +5 +7 +2 +7 +5 +6 +3 +218 +2 +2 +5 +2 +6 +3 +5 +222 +14 +6 +33 +3 +2 +5 +3 +3 +3 +9 +5 +3 +3 +2 +7 +4 +3 +4 +3 +5 +6 +5 +26 +4 +13 +9 +7 +3 +221 +3 +3 +4 +4 +4 +4 +2 +18 +5 +3 +7 +9 +6 +8 +3 +10 +3 +11 +9 +5 +4 +17 +5 +5 +6 +6 +3 +2 +4 +12 +17 +6 +7 +218 +4 +2 +4 +10 +3 +5 +15 +3 +9 +4 +3 +3 +6 +29 +3 +3 +4 +5 +5 +3 +8 +5 +6 +6 +7 +5 +3 +5 +3 +29 +2 +31 +5 +15 +24 +16 +5 +207 +4 +3 +3 +2 +15 +4 +4 +13 +5 +5 +4 +6 +10 +2 +7 +8 +4 +6 +20 +5 +3 +4 +3 +12 +12 +5 +17 +7 +3 +3 +3 +6 +10 +3 +5 +25 +80 +4 +9 +3 +2 +11 +3 +3 +2 +3 +8 +7 +5 +5 +19 +5 +3 +3 +12 +11 +2 +6 +5 +5 +5 +3 +3 +3 +4 +209 +14 +3 +2 +5 +19 +4 +4 +3 +4 +14 +5 +6 +4 +13 +9 +7 +4 +7 +10 +2 +9 +5 +7 +2 +8 +4 +6 +5 +5 +222 +8 +7 +12 +5 +216 +3 +4 +4 +6 +3 +14 +8 +7 +13 +4 +3 +3 +3 +3 +17 +5 +4 +3 +33 +6 +6 +33 +7 +5 +3 +8 +7 +5 +2 +9 +4 +2 +233 +24 +7 +4 +8 +10 +3 +4 +15 +2 +16 +3 +3 +13 +12 +7 +5 +4 +207 +4 +2 +4 +27 +15 +2 +5 +2 +25 +6 +5 +5 +6 +13 +6 +18 +6 +4 +12 +225 +10 +7 +5 +2 +2 +11 +4 +14 +21 +8 +10 +3 +5 +4 +232 +2 +5 +5 +3 +7 +17 +11 +6 +6 +23 +4 +6 +3 +5 +4 +2 +17 +3 +6 +5 +8 +3 +2 +2 +14 +9 +4 +4 +2 +5 +5 +3 +7 +6 +12 +6 +10 +3 +6 +2 +2 +19 +5 +4 +4 +9 +2 +4 +13 +3 +5 +6 +3 +6 +5 +4 +9 +6 +3 +5 +7 +3 +6 +6 +4 +3 +10 +6 +3 +221 +3 +5 +3 +6 +4 +8 +5 +3 +6 +4 +4 +2 +54 +5 +6 +11 +3 +3 +4 +4 +4 +3 +7 +3 +11 +11 +7 +10 +6 +13 +223 +213 +15 +231 +7 +3 +7 +228 +2 +3 +4 +4 +5 +6 +7 +4 +13 +3 +4 +5 +3 +6 +4 +6 +7 +2 +4 +3 +4 +3 +3 +6 +3 +7 +3 +5 +18 +5 +6 +8 +10 +3 +3 +3 +2 +4 +2 +4 +4 +5 +6 +6 +4 +10 +13 +3 +12 +5 +12 +16 +8 +4 +19 +11 +2 +4 +5 +6 +8 +5 +6 +4 +18 +10 +4 +2 +216 +6 +6 +6 +2 +4 +12 +8 +3 +11 +5 +6 +14 +5 +3 +13 +4 +5 +4 +5 +3 +28 +6 +3 +7 +219 +3 +9 +7 +3 +10 +6 +3 +4 +19 +5 +7 +11 +6 +15 +19 +4 +13 +11 +3 +7 +5 +10 +2 +8 +11 +2 +6 +4 +6 +24 +6 +3 +3 +3 +3 +6 +18 +4 +11 +4 +2 +5 +10 +8 +3 +9 +5 +3 +4 +5 +6 +2 +5 +7 +4 +4 +14 +6 +4 +4 +5 +5 +7 +2 +4 +3 +7 +3 +3 +6 +4 +5 +4 +4 +4 +3 +3 +3 +3 +8 +14 +2 +3 +5 +3 +2 +4 +5 +3 +7 +3 +3 +18 +3 +4 +4 +5 +7 +3 +3 +3 +13 +5 +4 +8 +211 +5 +5 +3 +5 +2 +5 +4 +2 +655 +6 +3 +5 +11 +2 +5 +3 +12 +9 +15 +11 +5 +12 +217 +2 +6 +17 +3 +3 +207 +5 +5 +4 +5 +9 +3 +2 +8 +5 +4 +3 +2 +5 +12 +4 +14 +5 +4 +2 +13 +5 +8 +4 +225 +4 +3 +4 +5 +4 +3 +3 +6 +23 +9 +2 +6 +7 +233 +4 +4 +6 +18 +3 +4 +6 +3 +4 +4 +2 +3 +7 +4 +13 +227 +4 +3 +5 +4 +2 +12 +9 +17 +3 +7 +14 +6 +4 +5 +21 +4 +8 +9 +2 +9 +25 +16 +3 +6 +4 +7 +8 +5 +2 +3 +5 +4 +3 +3 +5 +3 +3 +3 +2 +3 +19 +2 +4 +3 +4 +2 +3 +4 +4 +2 +4 +3 +3 +3 +2 +6 +3 +17 +5 +6 +4 +3 +13 +5 +3 +3 +3 +4 +9 +4 +2 +14 +12 +4 +5 +24 +4 +3 +37 +12 +11 +21 +3 +4 +3 +13 +4 +2 +3 +15 +4 +11 +4 +4 +3 +8 +3 +4 +4 +12 +8 +5 +3 +3 +4 +2 +220 +3 +5 +223 +3 +3 +3 +10 +3 +15 +4 +241 +9 +7 +3 +6 +6 +23 +4 +13 +7 +3 +4 +7 +4 +9 +3 +3 +4 +10 +5 +5 +1 +5 +24 +2 +4 +5 +5 +6 +14 +3 +8 +2 +3 +5 +13 +13 +3 +5 +2 +3 +15 +3 +4 +2 +10 +4 +4 +4 +5 +5 +3 +5 +3 +4 +7 +4 +27 +3 +6 +4 +15 +3 +5 +6 +6 +5 +4 +8 +3 +9 +2 +6 +3 +4 +3 +7 +4 +18 +3 +11 +3 +3 +8 +9 +7 +24 +3 +219 +7 +10 +4 +5 +9 +12 +2 +5 +4 +4 +4 +3 +3 +19 +5 +8 +16 +8 +6 +22 +3 +23 +3 +242 +9 +4 +3 +3 +5 +7 +3 +3 +5 +8 +3 +7 +5 +14 +8 +10 +3 +4 +3 +7 +4 +6 +7 +4 +10 +4 +3 +11 +3 +7 +10 +3 +13 +6 +8 +12 +10 +5 +7 +9 +3 +4 +7 +7 +10 +8 +30 +9 +19 +4 +3 +19 +15 +4 +13 +3 +215 +223 +4 +7 +4 +8 +17 +16 +3 +7 +6 +5 +5 +4 +12 +3 +7 +4 +4 +13 +4 +5 +2 +5 +6 +5 +6 +6 +7 +10 +18 +23 +9 +3 +3 +6 +5 +2 +4 +2 +7 +3 +3 +2 +5 +5 +14 +10 +224 +6 +3 +4 +3 +7 +5 +9 +3 +6 +4 +2 +5 +11 +4 +3 +3 +2 +8 +4 +7 +4 +10 +7 +3 +3 +18 +18 +17 +3 +3 +3 +4 +5 +3 +3 +4 +12 +7 +3 +11 +13 +5 +4 +7 +13 +5 +4 +11 +3 +12 +3 +6 +4 +4 +21 +4 +6 +9 +5 +3 +10 +8 +4 +6 +4 +4 +6 +5 +4 +8 +6 +4 +6 +4 +4 +5 +9 +6 +3 +4 +2 +9 +3 +18 +2 +4 +3 +13 +3 +6 +6 +8 +7 +9 +3 +2 +16 +3 +4 +6 +3 +2 +33 +22 +14 +4 +9 +12 +4 +5 +6 +3 +23 +9 +4 +3 +5 +5 +3 +4 +5 +3 +5 +3 +10 +4 +5 +5 +8 +4 +4 +6 +8 +5 +4 +3 +4 +6 +3 +3 +3 +5 +9 +12 +6 +5 +9 +3 +5 +3 +2 +2 +2 +18 +3 +2 +21 +2 +5 +4 +6 +4 +5 +10 +3 +9 +3 +2 +10 +7 +3 +6 +6 +4 +4 +8 +12 +7 +3 +7 +3 +3 +9 +3 +4 +5 +4 +4 +5 +5 +10 +15 +4 +4 +14 +6 +227 +3 +14 +5 +216 +22 +5 +4 +2 +2 +6 +3 +4 +2 +9 +9 +4 +3 +28 +13 +11 +4 +5 +3 +3 +2 +3 +3 +5 +3 +4 +3 +5 +23 +26 +3 +4 +5 +6 +4 +6 +3 +5 +5 +3 +4 +3 +2 +2 +2 +7 +14 +3 +6 +7 +17 +2 +2 +15 +14 +16 +4 +6 +7 +13 +6 +4 +5 +6 +16 +3 +3 +28 +3 +6 +15 +3 +9 +2 +4 +6 +3 +3 +22 +4 +12 +6 +7 +2 +5 +4 +10 +3 +16 +6 +9 +2 +5 +12 +7 +5 +5 +5 +5 +2 +11 +9 +17 +4 +3 +11 +7 +3 +5 +15 +4 +3 +4 +211 +8 +7 +5 +4 +7 +6 +7 +6 +3 +6 +5 +6 +5 +3 +4 +4 +26 +4 +6 +10 +4 +4 +3 +2 +3 +3 +4 +5 +9 +3 +9 +4 +4 +5 +5 +8 +2 +4 +2 +3 +8 +4 +11 +19 +5 +8 +6 +3 +5 +6 +12 +3 +2 +4 +16 +12 +3 +4 +4 +8 +6 +5 +6 +6 +219 +8 +222 +6 +16 +3 +13 +19 +5 +4 +3 +11 +6 +10 +4 +7 +7 +12 +5 +3 +3 +5 +6 +10 +3 +8 +2 +5 +4 +7 +2 +4 +4 +2 +12 +9 +6 +4 +2 +40 +2 +4 +10 +4 +223 +4 +2 +20 +6 +7 +24 +5 +4 +5 +2 +20 +16 +6 +5 +13 +2 +3 +3 +19 +3 +2 +4 +5 +6 +7 +11 +12 +5 +6 +7 +7 +3 +5 +3 +5 +3 +14 +3 +4 +4 +2 +11 +1 +7 +3 +9 +6 +11 +12 +5 +8 +6 +221 +4 +2 +12 +4 +3 +15 +4 +5 +226 +7 +218 +7 +5 +4 +5 +18 +4 +5 +9 +4 +4 +2 +9 +18 +18 +9 +5 +6 +6 +3 +3 +7 +3 +5 +4 +4 +4 +12 +3 +6 +31 +5 +4 +7 +3 +6 +5 +6 +5 +11 +2 +2 +11 +11 +6 +7 +5 +8 +7 +10 +5 +23 +7 +4 +3 +5 +34 +2 +5 +23 +7 +3 +6 +8 +4 +4 +4 +2 +5 +3 +8 +5 +4 +8 +25 +2 +3 +17 +8 +3 +4 +8 +7 +3 +15 +6 +5 +7 +21 +9 +5 +6 +6 +5 +3 +2 +3 +10 +3 +6 +3 +14 +7 +4 +4 +8 +7 +8 +2 +6 +12 +4 +213 +6 +5 +21 +8 +2 +5 +23 +3 +11 +2 +3 +6 +25 +2 +3 +6 +7 +6 +6 +4 +4 +6 +3 +17 +9 +7 +6 +4 +3 +10 +7 +2 +3 +3 +3 +11 +8 +3 +7 +6 +4 +14 +36 +3 +4 +3 +3 +22 +13 +21 +4 +2 +7 +4 +4 +17 +15 +3 +7 +11 +2 +4 +7 +6 +209 +6 +3 +2 +2 +24 +4 +9 +4 +3 +3 +3 +29 +2 +2 +4 +3 +3 +5 +4 +6 +3 +3 +2 +4 diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go new file mode 100644 index 0000000..d7d14f8 --- /dev/null +++ b/vendor/github.com/beorn7/perks/quantile/stream.go @@ -0,0 +1,316 @@ +// Package quantile computes approximate quantiles over an unbounded data +// stream within low memory and CPU bounds. +// +// A small amount of accuracy is traded to achieve the above properties. +// +// Multiple streams can be merged before calling Query to generate a single set +// of results. This is meaningful when the streams represent the same type of +// data. See Merge and Samples. +// +// For more detailed information about the algorithm used, see: +// +// Effective Computation of Biased Quantiles over Data Streams +// +// http://www.cs.rutgers.edu/~muthu/bquant.pdf +package quantile + +import ( + "math" + "sort" +) + +// Sample holds an observed value and meta information for compression. JSON +// tags have been added for convenience. +type Sample struct { + Value float64 `json:",string"` + Width float64 `json:",string"` + Delta float64 `json:",string"` +} + +// Samples represents a slice of samples. It implements sort.Interface. +type Samples []Sample + +func (a Samples) Len() int { return len(a) } +func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value } +func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] } + +type invariant func(s *stream, r float64) float64 + +// NewLowBiased returns an initialized Stream for low-biased quantiles +// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but +// error guarantees can still be given even for the lower ranks of the data +// distribution. +// +// The provided epsilon is a relative error, i.e. the true quantile of a value +// returned by a query is guaranteed to be within (1±Epsilon)*Quantile. +// +// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error +// properties. +func NewLowBiased(epsilon float64) *Stream { + ƒ := func(s *stream, r float64) float64 { + return 2 * epsilon * r + } + return newStream(ƒ) +} + +// NewHighBiased returns an initialized Stream for high-biased quantiles +// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but +// error guarantees can still be given even for the higher ranks of the data +// distribution. +// +// The provided epsilon is a relative error, i.e. the true quantile of a value +// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). +// +// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error +// properties. +func NewHighBiased(epsilon float64) *Stream { + ƒ := func(s *stream, r float64) float64 { + return 2 * epsilon * (s.n - r) + } + return newStream(ƒ) +} + +// NewTargeted returns an initialized Stream concerned with a particular set of +// quantile values that are supplied a priori. Knowing these a priori reduces +// space and computation time. The targets map maps the desired quantiles to +// their absolute errors, i.e. the true quantile of a value returned by a query +// is guaranteed to be within (Quantile±Epsilon). +// +// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. +func NewTargeted(targetMap map[float64]float64) *Stream { + // Convert map to slice to avoid slow iterations on a map. + // ƒ is called on the hot path, so converting the map to a slice + // beforehand results in significant CPU savings. + targets := targetMapToSlice(targetMap) + + ƒ := func(s *stream, r float64) float64 { + var m = math.MaxFloat64 + var f float64 + for _, t := range targets { + if t.quantile*s.n <= r { + f = (2 * t.epsilon * r) / t.quantile + } else { + f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile) + } + if f < m { + m = f + } + } + return m + } + return newStream(ƒ) +} + +type target struct { + quantile float64 + epsilon float64 +} + +func targetMapToSlice(targetMap map[float64]float64) []target { + targets := make([]target, 0, len(targetMap)) + + for quantile, epsilon := range targetMap { + t := target{ + quantile: quantile, + epsilon: epsilon, + } + targets = append(targets, t) + } + + return targets +} + +// Stream computes quantiles for a stream of float64s. It is not thread-safe by +// design. Take care when using across multiple goroutines. +type Stream struct { + *stream + b Samples + sorted bool +} + +func newStream(ƒ invariant) *Stream { + x := &stream{ƒ: ƒ} + return &Stream{x, make(Samples, 0, 500), true} +} + +// Insert inserts v into the stream. +func (s *Stream) Insert(v float64) { + s.insert(Sample{Value: v, Width: 1}) +} + +func (s *Stream) insert(sample Sample) { + s.b = append(s.b, sample) + s.sorted = false + if len(s.b) == cap(s.b) { + s.flush() + } +} + +// Query returns the computed qth percentiles value. If s was created with +// NewTargeted, and q is not in the set of quantiles provided a priori, Query +// will return an unspecified result. +func (s *Stream) Query(q float64) float64 { + if !s.flushed() { + // Fast path when there hasn't been enough data for a flush; + // this also yields better accuracy for small sets of data. + l := len(s.b) + if l == 0 { + return 0 + } + i := int(math.Ceil(float64(l) * q)) + if i > 0 { + i -= 1 + } + s.maybeSort() + return s.b[i].Value + } + s.flush() + return s.stream.query(q) +} + +// Merge merges samples into the underlying streams samples. This is handy when +// merging multiple streams from separate threads, database shards, etc. +// +// ATTENTION: This method is broken and does not yield correct results. The +// underlying algorithm is not capable of merging streams correctly. +func (s *Stream) Merge(samples Samples) { + sort.Sort(samples) + s.stream.merge(samples) +} + +// Reset reinitializes and clears the list reusing the samples buffer memory. +func (s *Stream) Reset() { + s.stream.reset() + s.b = s.b[:0] +} + +// Samples returns stream samples held by s. +func (s *Stream) Samples() Samples { + if !s.flushed() { + return s.b + } + s.flush() + return s.stream.samples() +} + +// Count returns the total number of samples observed in the stream +// since initialization. +func (s *Stream) Count() int { + return len(s.b) + s.stream.count() +} + +func (s *Stream) flush() { + s.maybeSort() + s.stream.merge(s.b) + s.b = s.b[:0] +} + +func (s *Stream) maybeSort() { + if !s.sorted { + s.sorted = true + sort.Sort(s.b) + } +} + +func (s *Stream) flushed() bool { + return len(s.stream.l) > 0 +} + +type stream struct { + n float64 + l []Sample + ƒ invariant +} + +func (s *stream) reset() { + s.l = s.l[:0] + s.n = 0 +} + +func (s *stream) insert(v float64) { + s.merge(Samples{{v, 1, 0}}) +} + +func (s *stream) merge(samples Samples) { + // TODO(beorn7): This tries to merge not only individual samples, but + // whole summaries. The paper doesn't mention merging summaries at + // all. Unittests show that the merging is inaccurate. Find out how to + // do merges properly. + var r float64 + i := 0 + for _, sample := range samples { + for ; i < len(s.l); i++ { + c := s.l[i] + if c.Value > sample.Value { + // Insert at position i. + s.l = append(s.l, Sample{}) + copy(s.l[i+1:], s.l[i:]) + s.l[i] = Sample{ + sample.Value, + sample.Width, + math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1), + // TODO(beorn7): How to calculate delta correctly? + } + i++ + goto inserted + } + r += c.Width + } + s.l = append(s.l, Sample{sample.Value, sample.Width, 0}) + i++ + inserted: + s.n += sample.Width + r += sample.Width + } + s.compress() +} + +func (s *stream) count() int { + return int(s.n) +} + +func (s *stream) query(q float64) float64 { + t := math.Ceil(q * s.n) + t += math.Ceil(s.ƒ(s, t) / 2) + p := s.l[0] + var r float64 + for _, c := range s.l[1:] { + r += p.Width + if r+c.Width+c.Delta > t { + return p.Value + } + p = c + } + return p.Value +} + +func (s *stream) compress() { + if len(s.l) < 2 { + return + } + x := s.l[len(s.l)-1] + xi := len(s.l) - 1 + r := s.n - 1 - x.Width + + for i := len(s.l) - 2; i >= 0; i-- { + c := s.l[i] + if c.Width+x.Width+x.Delta <= s.ƒ(s, r) { + x.Width += c.Width + s.l[xi] = x + // Remove element at i. + copy(s.l[i:], s.l[i+1:]) + s.l = s.l[:len(s.l)-1] + xi -= 1 + } else { + x = c + xi = i + } + r -= c.Width + } +} + +func (s *stream) samples() Samples { + samples := make(Samples, len(s.l)) + copy(samples, s.l) + return samples +} diff --git a/vendor/github.com/buger/jsonparser/.gitignore b/vendor/github.com/buger/jsonparser/.gitignore new file mode 100644 index 0000000..0584d83 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/.gitignore @@ -0,0 +1,20 @@ + +*.test + +*.out + +*.mprof + +.idea + +vendor/github.com/buger/goterm/ +prof.cpu +prof.mem +.proof/ +tests/ +PROOF_*.md +REQPROOF_*.md +proof-ux-log.md +PROOF_UNDER_MODELED_REQUIREMENTS_PROPOSAL.md +fuzz_results/ +testdata/fuzz/ diff --git a/vendor/github.com/buger/jsonparser/.travis.yml b/vendor/github.com/buger/jsonparser/.travis.yml new file mode 100644 index 0000000..56f9c9c --- /dev/null +++ b/vendor/github.com/buger/jsonparser/.travis.yml @@ -0,0 +1,12 @@ +language: go +arch: + - amd64 + - ppc64le +go: + - 1.13.x + - 1.14.x + - 1.15.x + - 1.16.x + - 1.17.x + - 1.18.x +script: go test -v ./. diff --git a/vendor/github.com/buger/jsonparser/CHANGELOG.md b/vendor/github.com/buger/jsonparser/CHANGELOG.md new file mode 100644 index 0000000..37b258a --- /dev/null +++ b/vendor/github.com/buger/jsonparser/CHANGELOG.md @@ -0,0 +1,272 @@ +# 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) + +### New API — `Append` + +```go +// Append to an array without knowing its length +data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items") +``` + +- **`Append(data, value, keys...)`** — appends `value` to the end of the JSON array addressed by `keys`. Addresses the top-level value when `keys` is empty; auto-vivifies a missing keyed path as a single-element array. Returns `MalformedArrayError` when the addressed value is not an array. Traced to SYS-REQ-009, SYS-REQ-110. + +### Known issues — all resolved (zero open) + +- **KI-2 fixed** — `ParseInt("-")` now returns an error instead of `(0, nil)`. One-line sign-only guard in `bytes.go:parseInt` (after stripping the sign byte, an empty remainder returns `(0, false, false)`). +- **KI-3 fixed** — `Set` with an array-index path component under an object parent (and vice-versa) now auto-coerces the container type instead of emitting malformed JSON. (Disposition already set to `fixed` in v1.5.x.) +- **KI-4 fixed** — `Set` on a top-level array-index beyond length now appends at the array's end (matching nested-array behavior under SYS-REQ-110) instead of returning `KeyPathNotFoundError`. Also cleans up trailing commas in malformed arrays. + +**Zero open known issues.** Every previously shipped known issue is now resolved and covered by ReqProof L3 Assurance. + +--- + +## [v1.5.1] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance (123 requirements, 0 errors, 0 warnings) + +### Performance — 6.1x large-payload speedup + +- **Fix stringEnd unbounded backslash scan** — `stringEndConfig` was scanning the ENTIRE remaining parent document for backslashes (`bytes.IndexByte(data, '\\')`) instead of just the string body. On a 24kb large payload this walked tens of KB per string. Now bounded to `data[:firstQuote]` (the string body only). **128µs → 22µs (5.8x).** +- **SWAR string scan** — replaced two separate `bytes.IndexByte` calls (quote + backslash) with a single inline 8-byte SWAR (SIMD-Within-A-Register) loop that checks for both characters simultaneously. **22µs → 21µs (additional 8%).** +- **Benchmark suite updated** — all comparison libraries (gabs, easyjson, ffjson, etc.) updated to latest versions. Benchmark methodology documented (Apple M4 Max, Go 1.26.3, median of 5 runs). The `encoding/json` benchmark no longer uses ffjson-generated methods (the #126 ffjson measurement bug was fixed in v1.3.1). +- **README benchmarks refreshed** — all numbers now reflect real measurements on modern hardware with current library versions. + +### Updated benchmark results (Apple M4 Max, Go 1.26.3, median of 5 runs) + +| Payload | jsonparser | encoding/json | easyjson | Speedup vs encoding/json | +|---|---|---|---|---| +| Small (190B, Get) | 382 ns | 1,335 ns | 312 ns | 3.5x | +| Small (190B, EachKey) | 241 ns | — | — | 5.5x | +| Medium (2.4kB, Get) | 3,894 ns | 10,564 ns | 2,444 ns | 2.7x | +| Medium (2.4kB, EachKey) | 1,923 ns | — | — | 5.5x | +| Large (24kB) | 20,788 ns | 134,123 ns | 32,765 ns | **6.4x** | + +All jsonparser results: **0 bytes allocated, 0 allocations**. + +--- + +## [v1.5.0] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance + +v1.5.0 extends the formal-verification coverage to **123 requirements** (0 errors, 0 warnings) across all new APIs. Every new function is traced via source annotations, tested with MC/DC witnesses, and covered by the structure-aware fuzzer. + +### Config struct — opt-in lenient parsing (#160, #115) + +```go +var Lenient = jsonparser.Config{AllowSingleQuotes: true, AllowUnknownEscapes: true} +Lenient.Get(data, "key") // parses {'key':'value'} and unknown escapes +``` + +- **`AllowSingleQuotes`** — accept `'key':'value'` alongside `"key":"value"` (JavaScript/Python-style). The same escape rules apply inside single-quoted strings. +- **`AllowUnknownEscapes`** — pass through unknown escape sequences (`` \` ``, `\x`) literally instead of erroring. +- The default Config is strict (RFC 8259 only). Package-level functions are unchanged. +- Config methods mirror the full API: `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, `ObjectEach`. + +### Streaming ReaderParser (#132, #257) + +```go +rp := jsonparser.NewReaderParser(file) // any io.Reader +rp.Get("users", "[0]", "name") // path-based access from a stream +``` + +- Path-based access to JSON data from an `io.Reader` — **no need to load the entire document into memory**. +- Buffers data incrementally in 64KB chunks; memory is bounded by the largest value, not the document size. +- Enables parsing **10GB+ JSON files** without OOM. +- Methods: `Get`, `GetString`, `ArrayEach`. + +### Name aliases (#66) + +Canonical `EachXxx` pattern added alongside existing `XxxEach` names: + +| New (canonical) | Old (kept for compat) | +|---|---| +| `EachArray` | `ArrayEach` | +| `EachObject` | `ObjectEach` | +| `EachArrayErr` | `ArrayEachErr` | +| `EachArrayWildcard` | `ArrayEachWildcard` | + +`EachKey`, `EachKeyErr`, `EachKeyWildcard` already matched the pattern. All old names remain functional. + +### Proof + +- 2 new SYS-REQs: 115 (Config/lenient parsing), 116 (streaming ReaderParser) +- **123 requirements, 0 errors, 0 warnings, 279/279 functions traced** + +--- + +## [v1.4.0] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance + +v1.4.0 adds 9 new backward-compatible APIs, each traced to a formal requirement and verified with MC/DC coverage. **121 requirements, 0 errors, 0 warnings.** + +### New APIs + +**Iteration with error/break control** — resolves #53, #129, #176, #230, #255, #262 +- `ArrayEachErr` — callback returns `error` to stop early (`io.EOF` = graceful stop) +- `EachKeyErr` — same pattern for EachKey + +**Safe string handling** — resolves #144, #158, #218, #270 +- `Escape(s string) []byte` — RFC 8259 string escaping (inverse of `Unescape`) +- `SetString(data, val, keys...)` — Set with auto-quoted value + +**Container accessors** — resolves #175, #261, #271 +- `GetArrayLen` / `GetObjectLen` — count elements without a callback +- `GetUint64` — uint64 variant of `GetInt` + +**Delete found signal** — resolves #229 +- `DeleteFound(data, keys...) ([]byte, bool)` — returns whether the key was found + +**Wildcard paths** — resolves #112 +- `EachKeyWildcard`, `ArrayEachWildcard`, `SetWildcard` — `[*]` path component + +**JSONPath compiled paths** — resolves #234, #251 +- `ParsePath("$.users[0].name")` → `[]string` path +- `CompilePath` + `CompiledPath` — pre-compile and reuse with Get/Set/Delete + +### Fixes +- EachKey no longer panics with >64 key components (#56) +- Set pre-allocates output buffer, reducing allocations from 6 to 1 (#107) + +### Proof +- 3 new SYS-REQs: 112 (container length), 113 (wildcard paths), 114 (compiled paths) +- **121 requirements, 384 MC/DC witness rows, 0 uncovered** + +--- + +## [v1.3.1] — 2026-07-28 + +### Covered by [ReqProof](https://reqproof.com) — L3 Assurance + +v1.3.1 fixes 3 bugs that escaped the initial proof review, with new proof gates to prevent recurrence. + +### Bug fixes + +- **Fix Set/Delete input-buffer aliasing** (#209, #141) — `Set` and `Delete` no longer corrupt the caller's input `[]byte` when the slice has spare capacity. All mutation paths now allocate a fresh buffer. +- **Fix EachKey array-index inconsistency** (#232) — `EachKey` now descends into terminal array-index paths consistently with `Get`. +- **Fix benchmark measuring ffjson, not encoding/json** (#126) — benchmark payload types stripped of generated methods. + +### Proof strengthening + +| Bug | Proof gap | New gate | +|---|---|---| +| #209/#141 Set aliasing | No obligation said "Set must not mutate the input buffer" | New obligation `no_input_mutation` + `assertInputUnchanged` gate | +| #232 EachKey ≠ Get | No cross-API consistency obligation | New obligation `api_consistency` + differential gate | +| #126 benchmark ffjson | Proof didn't cover benchmarks | Benchmark honesty lint | + +--- + +## [v1.3.0] — 2026-07-27 + +### Formally verified by [ReqProof](https://reqproof.com) + +jsonparser v1.3.0 is the **first Go library proven to L3 assurance** by [ReqProof](https://reqproof.com), a git-native requirements-engineering and formal-verification platform. The entire codebase is now covered by: + +- **118 formal requirements** (7 stakeholder + 111 system-level), each traced to code via source annotations and verified with FRETish formalization. +- **100% Modified Condition/Decision Coverage (MC/DC)** — both code-level (every decision/condition branch exercised) and requirement-side (377/377 truth-table rows witnessed). +- **A custom structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) generating grammar-valid mutations at 250k inputs/sec, plus path-mutation and `encoding/json` differential harnesses. +- **L3 strict audit posture**: 0 errors, 0 warnings, all checks enabled. + +The proof review found and fixed **7 real bugs** that years of community use, OSS-Fuzz, and standard fuzzing had missed. [Read the root-cause analysis →](docs/proof-gap-root-cause.md) + +jsonparser serves as the **reference case study** for ReqProof — [learn more at reqproof.com](https://reqproof.com). + +### Security / bug fixes + +- **Fix Delete panic on malformed input with leading comma** (OSS-Fuzz 4649128545288192) + `Delete` panicked with `index out of range [-1]` on inputs like `,{"test":1{}`. + The `data[prevTok]` dereference is now guarded. + +- **Fix empty-string key-component panics** (8 sites) + `Get`, `GetString`, `GetInt`, `GetFloat`, `GetBoolean`, `GetUnsafeString`, `Set`, + `Delete`, `EachKey` panicked with `index out of range [0]` when a key path contained + an empty string (`""`). All 8 unguarded `keys[i][0]` dereference sites are now guarded + with `len(...) > 0`. Found by the structure-aware hazard sweep. + Reported by @c-tonneslan (#284). + +- **Fix Set data loss on scalar arrays** (#267) + `Set` on an array-index path beyond the current length silently overwrote the array + instead of appending. `Set({"a":[1,2,3]}, 99, "a", "[9]")` now returns `{"a":[1,2,3,99]}` + instead of `{"a":[99]}`. Reported by @Solaris-star (#286). + +- **Fix Set malformed-JSON output on cross-type paths** + `Set` with an array-index path component under an object parent (e.g. `Set({}, 9, "[5]")`) + produced invalid JSON (`{[9]}`). Set now auto-coerces the container type to match the + path, always producing valid JSON output. + +- **Fix Delete trailing-comma malformation** + `Delete` left a dangling trailing comma in the output when the deleted element was + followed by JSON whitespace (space/tab/LF/CR) and a comma. Found by the structure-aware + path-mutation fuzzer. + +- **Fix ArrayEach spurious callback on non-array root** + `ArrayEach` on a non-array root value (e.g. `ArrayEach({"a":1}, cb)`) invoked the + callback with a spurious element before returning an error. The callback is no longer + invoked; a clean error is returned immediately. + +- **Fix lone-Unicode-surrogate mishandling in Unescape** + `ParseString` on a string containing a lone high surrogate (e.g. `\uDB29` without a + following low surrogate) synthesized a bogus non-BMP code point from the following + literal bytes. Now substitutes U+FFFD (matching `encoding/json` behavior). + +### Performance + +- **parseInt fast-path for short numbers** — 22–37% faster on typical 1–10 digit integers. + Numbers with ≤18 digits use direct int64 accumulation, bypassing the overflow-checked + uint64 slow path. Contributed by @trevorprater (#285). + +- **stringEnd SIMD fast path** — 12× faster on no-escape strings, 4.5× faster end-to-end + on `Get` for string values. Uses `bytes.IndexByte` for the common case (no `\` before + the closing `"`). + +### Acknowledgments + +- @c-tonneslan (#284) — reported the empty-string key-component panic +- @Solaris-star (#286) — reported the Set array-index data-loss bug (#267) +- @trevorprater (#285) — contributed the parseInt performance optimization +- OSS-Fuzz (issue 4649128545288192) — the original Delete leading-comma panic +- The [probelabs/json-fuzz](https://github.com/probelabs/json-fuzz) structure-aware fuzzer diff --git a/vendor/github.com/buger/jsonparser/Dockerfile b/vendor/github.com/buger/jsonparser/Dockerfile new file mode 100644 index 0000000..4d58977 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/Dockerfile @@ -0,0 +1,12 @@ +FROM golang:1.25 + +WORKDIR /go/src/github.com/buger/jsonparser +ADD . /go/src/github.com/buger/jsonparser + +RUN go get github.com/Jeffail/gabs +RUN go get github.com/bitly/go-simplejson +RUN go get github.com/pquerna/ffjson +RUN go get github.com/antonholmquist/jason +RUN go get github.com/mreiferson/go-ujson +RUN go get -tags=unsafe -u github.com/ugorji/go/codec +RUN go get github.com/mailru/easyjson diff --git a/vendor/github.com/buger/jsonparser/LICENSE b/vendor/github.com/buger/jsonparser/LICENSE new file mode 100644 index 0000000..ac25aeb --- /dev/null +++ b/vendor/github.com/buger/jsonparser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Leonid Bugaev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/buger/jsonparser/Makefile b/vendor/github.com/buger/jsonparser/Makefile new file mode 100644 index 0000000..e06ffa3 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/Makefile @@ -0,0 +1,47 @@ +SOURCE = parser.go +CONTAINER = jsonparser +SOURCE_PATH = /go/src/github.com/buger/jsonparser +BENCHMARK = JsonParser +BENCHTIME = 5s +TEST = . +DRUN = docker run -v `pwd`:$(SOURCE_PATH) -i -t $(CONTAINER) + +build: + docker build -t $(CONTAINER) . + +race: + $(DRUN) --env GORACE="halt_on_error=1" go test ./. $(ARGS) -v -race -timeout 15s + +bench: + $(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -benchtime $(BENCHTIME) -v + +bench_local: + $(DRUN) go test $(LDFLAGS) -test.benchmem -bench . $(ARGS) -benchtime $(BENCHTIME) -v + +profile: + $(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -memprofile mem.mprof -v + $(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -cpuprofile cpu.out -v + $(DRUN) go test $(LDFLAGS) -test.benchmem -bench $(BENCHMARK) ./benchmark/ $(ARGS) -c + +test: + $(DRUN) go test $(LDFLAGS) ./ -run $(TEST) -timeout 10s $(ARGS) -v + +# Full test suite including the heavy iteration-count suites that the standard +# `proof audit` skips (property-based, reference-oracle, fuzz-harness coverage). +# Run this in the dedicated CI fuzz job or locally before a release. +test-full: + go test ./... -count=1 -race -timeout 5m + +# Structure-aware JSON fuzzer (grammar-based, far faster than generic +# libFuzzer for finding parser-specific defects). See json_fuzz_test.go. +fuzz-json: + go test -run='^$$' -fuzz=FuzzJSONStructureAware -fuzztime=$(FUZZTIME) ./... + +fmt: + $(DRUN) go fmt ./... + +vet: + $(DRUN) go vet ./. + +bash: + $(DRUN) /bin/bash \ No newline at end of file diff --git a/vendor/github.com/buger/jsonparser/README.md b/vendor/github.com/buger/jsonparser/README.md new file mode 100644 index 0000000..b6683dc --- /dev/null +++ b/vendor/github.com/buger/jsonparser/README.md @@ -0,0 +1,454 @@ +[![Go Report Card](https://goreportcard.com/badge/github.com/buger/jsonparser)](https://goreportcard.com/report/github.com/buger/jsonparser) [![Audit](https://img.shields.io/badge/ReqProof-L3%20Assurance-success)](https://reqproof.com) ![License](https://img.shields.io/dub/l/vibe-d.svg) +# 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 **6.5x faster** than standard `encoding/json` package (depending on payload size and usage), **allocates no memory**. See benchmarks below. + +--- + +## 🔒 Formally Verified — the first Go library proven to L3 assurance by [ReqProof](https://reqproof.com) + +jsonparser is the **reference case study** for [ReqProof](https://reqproof.com) — a git-native requirements-engineering and formal-verification platform. Every public API is traced to a formal requirement, every requirement is tested with **100% Modified Condition/Decision Coverage (MC/DC)**, and the entire parser is fuzzed by a custom **structure-aware JSON fuzzer** ([github.com/probelabs/json-fuzz](https://github.com/probelabs/json-fuzz)) that generates grammar-valid mutations at 250,000 inputs/second. + +| Metric | Value | +|---|---| +| Requirements traced | 118 (7 stakeholder + 111 system) | +| Proof audit | **0 errors, 0 warnings** (L3 strict) | +| Code-level MC/DC | **100% decisions, 100% conditions** | +| Requirement-side MC/DC | **377/377 witness rows covered** | +| Fuzz executions | 16M+ (structure-aware + path-mutation + encoding/json differential) | +| Bugs found & fixed by the proof review | 7 (4 panics, 2 data-corruption, 1 encoding bug) | + +The proof review caught bugs that years of community use, OSS-Fuzz, and standard fuzzing had missed — including a panic class across 8 unchecked-dereference sites, a silent data-loss bug in `Set`, and a malformed-output bug in `Delete`. [Read the full root-cause analysis →](docs/proof-gap-root-cause.md) + +--- + +## Rationale +Originally I made this for a project that relies on a lot of 3rd party APIs that can be unpredictable and complex. +I love simplicity and prefer to avoid external dependecies. `encoding/json` requires you to know exactly your data structures, or if you prefer to use `map[string]interface{}` instead, it will be very slow and hard to manage. +I investigated what's on the market and found that most libraries are just wrappers around `encoding/json`, there is few options with own parsers (`ffjson`, `easyjson`), but they still requires you to create data structures. + + +Goal of this project is to push JSON parser to the performance limits and not sacrifice with compliance and developer user experience. + +## Example +For the given JSON our goal is to extract the user's full name, number of github followers and avatar. + +```go +import "github.com/buger/jsonparser" + +... + +data := []byte(`{ + "person": { + "name": { + "first": "Leonid", + "last": "Bugaev", + "fullName": "Leonid Bugaev" + }, + "github": { + "handle": "buger", + "followers": 109 + }, + "avatars": [ + { "url": "https://avatars1.githubusercontent.com/u/14009?v=3&s=460", "type": "thumbnail" } + ] + }, + "company": { + "name": "Acme" + } +}`) + +// You can specify key path by providing arguments to Get function +jsonparser.Get(data, "person", "name", "fullName") + +// There is `GetInt` and `GetBoolean` helpers if you exactly know key data type +jsonparser.GetInt(data, "person", "github", "followers") + +// When you try to get object, it will return you []byte slice pointer to data containing it +// In `company` it will be `{"name": "Acme"}` +jsonparser.Get(data, "company") + +// If the key doesn't exist it will throw an error +var size int64 +if value, err := jsonparser.GetInt(data, "company", "size"); err == nil { + size = value +} + +// You can use `EachArray` helper to iterate items [item1, item2 .... itemN] +jsonparser.EachArray(data, func(value []byte, dataType jsonparser.ValueType, offset int, err error) { + fmt.Println(jsonparser.Get(value, "url")) +}, "person", "avatars") + +// Or use can access fields by index! +jsonparser.GetString(data, "person", "avatars", "[0]", "url") + +// You can use `EachObject` helper to iterate objects { "key1":object1, "key2":object2, .... "keyN":objectN } +jsonparser.EachObject(data, func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { + fmt.Printf("Key: '%s'\n Value: '%s'\n Type: %s\n", string(key), string(value), dataType) + return nil +}, "person", "name") + +// The most efficient way to extract multiple keys is `EachKey` + +paths := [][]string{ + []string{"person", "name", "fullName"}, + []string{"person", "avatars", "[0]", "url"}, + []string{"company", "url"}, +} +jsonparser.EachKey(data, func(idx int, value []byte, vt jsonparser.ValueType, err error){ + switch idx { + case 0: // []string{"person", "name", "fullName"} + ... + case 1: // []string{"person", "avatars", "[0]", "url"} + ... + case 2: // []string{"company", "url"}, + ... + } +}, paths...) + +// For more information see docs below +``` + +## Lenient Parsing + +The package-level functions remain strict RFC 8259 parsers. For inputs that use +single-quoted strings or non-standard escapes, use a `Config` explicitly: + +```go +data := []byte(`{'name':'Ada','role':'engineer'}`) + +name, err := jsonparser.Lenient.GetString(data, "name") +// name == "Ada" +``` + +`Lenient` enables both compatibility options. You can also enable only the +extension your input requires: + +```go +config := jsonparser.Config{AllowUnknownEscapes: true} +data := []byte("{\"path\":\"docs\\`draft\\x\"}") + +path, err := config.GetString(data, "path") +// path == "docs`draftx" +``` + +The config-aware `Get`, `GetString`, `Set`, `Delete`, `ArrayEach`, and +`ObjectEach` methods share the same signatures and behavior as their +package-level counterparts apart from the enabled parsing extensions. +`jsonparser.DefaultConfig` is strict; `jsonparser.Lenient` enables +`AllowSingleQuotes` and `AllowUnknownEscapes`. + +## Streaming + +`ReaderParser` provides the same path-based lookup model for JSON read from an +`io.Reader`, so a large document does not need to be loaded into a single byte +slice: + +```go +file, err := os.Open("large.json") +if err != nil { + log.Fatal(err) +} +defer file.Close() + +parser := jsonparser.NewReaderParser(file) +name, err := parser.GetString("person", "name") +``` + +To process a root array incrementally, use `ArrayEach`. Each callback value is +valid for the duration of the callback; copy it if it must be retained: + +```go +parser := jsonparser.NewReaderParser(file) +err := parser.ArrayEach(func(value []byte, valueType jsonparser.ValueType, err error) { + if err != nil { + return + } + process(value, valueType) +}) +``` + +The parser reads in 64 KiB chunks and discards completed prefixes. Its default +sliding-window target is 64 MiB; customize it with +`jsonparser.Config{MaxBufferSize: size}`. A single returned value or array +element may exceed that target because its complete bytes are supplied to the +caller. Create a new `ReaderParser` for each lookup or array traversal. +`ReaderParser` also honors `AllowSingleQuotes` and `AllowUnknownEscapes`. + +## Reference + +Library API is really simple. You just need the `Get` method to perform any operation. The rest is just helpers around it. + +You also can view API at [godoc.org](https://godoc.org/github.com/buger/jsonparser) + + +### **`Get`** +```go +func Get(data []byte, keys ...string) (value []byte, dataType jsonparser.ValueType, offset int, err error) +``` +Receives data structure, and key path to extract value from. + +Returns: +* `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error +* `dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null` +* `offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper. +* `err` - If the key is not found or any other parsing issue, it should return error. If key not found it also sets `dataType` to `NotExist` + +Accepts multiple keys to specify path to JSON value (in case of quering nested structures). +If no keys are provided it will try to extract the closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation. + +Note that keys can be an array indexes: `jsonparser.GetInt("person", "avatars", "[0]", "url")`, pretty cool, yeah? + +### **`GetString`** +```go +func GetString(data []byte, keys ...string) (val string, err error) +``` +Returns strings properly handing escaped and unicode characters. Note that this will cause additional memory allocations. + +### **`GetUnsafeString`** +If you need string in your app, and ready to sacrifice with support of escaped symbols in favor of speed. It returns string mapped to existing byte slice memory, without any allocations: +```go +s, _, := jsonparser.GetUnsafeString(data, "person", "name", "title") +switch s { + case 'CEO': + ... + case 'Engineer' + ... + ... +} +``` +Note that `unsafe` here means that your string will exist until GC will free underlying byte slice, for most of cases it means that you can use this string only in current context, and should not pass it anywhere externally: through channels or any other way. + + +### **`GetBoolean`**, **`GetInt`** and **`GetFloat`** +```go +func GetBoolean(data []byte, keys ...string) (val bool, err error) + +func GetFloat(data []byte, keys ...string) (val float64, err error) + +func GetInt(data []byte, keys ...string) (val int64, err error) +``` +If you know the key type, you can use the helpers above. +If key data type do not match, it will return error. + +### **`EachArray`** +```go +func EachArray(data []byte, cb func(value []byte, dataType jsonparser.ValueType, offset int, err error), keys ...string) +``` +Needed for iterating arrays, accepts a callback function with the same return arguments as `Get`. +`ArrayEach` remains available as a backward-compatible alias. +The error-returning and wildcard variants follow the same naming convention: +use `EachArrayErr` and `EachArrayWildcard`; `ArrayEachErr` and +`ArrayEachWildcard` remain available for backward compatibility. + +### **`EachObject`** +```go +func EachObject(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) +``` +Needed for iterating object, accepts a callback function. Example: +```go +var handler func([]byte, []byte, jsonparser.ValueType, int) error +handler = func(key []byte, value []byte, dataType jsonparser.ValueType, offset int) error { + //do stuff here +} +jsonparser.EachObject(myJson, handler) +``` +`ObjectEach` remains available as a backward-compatible alias. + + +### **`EachKey`** +```go +func EachKey(data []byte, cb func(idx int, value []byte, dataType jsonparser.ValueType, err error), paths ...[]string) +``` +When you need to read multiple keys, and you do not afraid of low-level API `EachKey` is your friend. It read payload only single time, and calls callback function once path is found. For example when you call multiple times `Get`, it has to process payload multiple times, each time you call it. Depending on payload `EachKey` can be multiple times faster than `Get`. Path can use nested keys as well! + +```go +paths := [][]string{ + []string{"uuid"}, + []string{"tz"}, + []string{"ua"}, + []string{"st"}, +} +var data SmallPayload + +jsonparser.EachKey(smallFixture, func(idx int, value []byte, vt jsonparser.ValueType, err error){ + switch idx { + case 0: + data.Uuid, _ = value + case 1: + v, _ := jsonparser.ParseInt(value) + data.Tz = int(v) + case 2: + data.Ua, _ = value + case 3: + v, _ := jsonparser.ParseInt(value) + data.St = int(v) + } +}, paths...) +``` + +### **`Set`** +```go +func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) +``` +Receives existing data structure, key path to set, and value to set at that key. *This functionality is experimental.* + +Returns: +* `value` - Pointer to original data structure with updated or added key value. +* `err` - If any parsing issue, it should return error. + +Accepts multiple keys to specify path to JSON value (in case of updating or creating nested structures). + +Note that keys can be an array indexes: `jsonparser.Set(data, []byte("http://github.com"), "person", "avatars", "[0]", "url")` + +### **`Delete`** +```go +func Delete(data []byte, keys ...string) value []byte +``` +Receives existing data structure, and key path to delete. *This functionality is experimental.* + +Returns: +* `value` - Pointer to original data structure with key path deleted if it can be found. If there is no key path, then the whole data structure is deleted. + +Accepts multiple keys to specify path to JSON value (in case of updating or creating nested structures). + +Note that keys can be an array indexes: `jsonparser.Delete(data, "person", "avatars", "[0]", "url")` + +### **`Append`** +```go +func Append(data []byte, value []byte, keys ...string) ([]byte, error) +``` +Appends `value` to the end of the JSON array addressed by `keys`. When `keys` is +empty, `Append` addresses the top-level value. If a keyed path does not exist, +`Append` creates it as a single-element array using `Set`'s auto-vivification +behavior. Returns `MalformedArrayError` if the addressed value is not an array. + +```go +// Append to an array without knowing its length +data, _ = jsonparser.Append(data, []byte(`"new_item"`), "items") +``` + + +## What makes it so fast? +* It does not rely on `encoding/json`, `reflection` or `interface{}`, the only real package dependency is `bytes`. +* Operates with JSON payload on byte level, providing you pointers to the original data structure: no memory allocation. +* No automatic type conversions, by default everything is a []byte, but it provides you value type, so you can convert by yourself (there is few helpers included). +* Does not parse full record, only keys you specified + + +## Benchmarks + +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-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/pquerna/ffjson +* https://github.com/mailru/easyjson +* https://github.com/buger/jsonparser + +#### TLDR + +`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 + +Each test processes 190 bytes of http log as a JSON record. +It should read multiple fields. +https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_small_payload_test.go + +| Library | time/op | bytes/op | allocs/op | +| ------ | ------- | -------- | ------- | +| 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 + +Each test processes a 2.4kb JSON record (based on Clearbit API). +It should read multiple nested fields and 1 array. + +https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_medium_payload_test.go + +| Library | time/op | bytes/op | allocs/op | +| ------- | ------- | -------- | --------- | +| 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 every competitor on medium payloads while remaining zero-allocation. + +#### Large payload + +Each test processes a 24kb JSON record (based on Discourse API). +It should read 2 arrays, and for each item in array get a few fields. +Basically it means processing a full JSON file. + +https://github.com/buger/jsonparser/blob/master/benchmark/benchmark_large_payload_test.go + +| Library | time/op | bytes/op | allocs/op | +| --- | --- | --- | --- | +| 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.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 + + + +This project uses [ReqProof](https://reqproof.com) for formal requirements verification, achieving: + +- **92 formally specified requirements** covering all public API behavior including edge cases, malformed input, boundary values, and error propagation +- **100% MC/DC coverage** (Modified Condition/Decision Coverage) — every boolean decision in the code is independently proven exercised +- **Kind2 model checking** — mathematical proof that the specification is realizable and consistent +- **Z3 SMT proofs** — data-level properties verified for all possible inputs, not just test samples + +ReqProof found **2 real bugs** during the verification process ([see PR #281](https://github.com/buger/jsonparser/pull/281)): +1. `Delete` panic on truncated JSON input — bounds check missing after internal sentinel value +2. `ArrayEach` callback silently swallowing parse errors — the callback's `err` parameter was always nil + +It also identified and safely removed **7 dead code blocks** that MC/DC analysis proved unreachable from any input. + +The verification runs on every PR via [probelabs/proof-action](https://github.com/probelabs/proof-action). + +## Questions and support + +All bug-reports and suggestions should go though Github Issues. + +## Contributing + +1. Fork it +2. Create your feature branch (git checkout -b my-new-feature) +3. Commit your changes (git commit -am 'Added some feature') +4. Push to the branch (git push origin my-new-feature) +5. Create new Pull Request + +## Development + +All my development happens using Docker, and repo include some Make tasks to simplify development. + +* `make build` - builds docker image, usually can be called only once +* `make test` - run tests +* `make fmt` - run go fmt +* `make bench` - run benchmarks (if you need to run only single benchmark modify `BENCHMARK` variable in make file) +* `make profile` - runs benchmark and generate 3 files- `cpu.out`, `mem.mprof` and `benchmark.test` binary, which can be used for `go tool pprof` +* `make bash` - enter container (i use it for running `go tool pprof` above) diff --git a/vendor/github.com/buger/jsonparser/aliases.go b/vendor/github.com/buger/jsonparser/aliases.go new file mode 100644 index 0000000..c78a553 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/aliases.go @@ -0,0 +1,25 @@ +package jsonparser + +// SYS-REQ-006, SYS-REQ-028, SYS-REQ-029, SYS-REQ-052, SYS-REQ-053, SYS-REQ-055, SYS-REQ-083 +// EachArray is the canonical name; ArrayEach is kept for backward compatibility. +func EachArray(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) { + ArrayEach(data, cb, keys...) +} + +// SYS-REQ-007, SYS-REQ-030, SYS-REQ-031, SYS-REQ-032, SYS-REQ-054, SYS-REQ-084 +// EachObject is the canonical name; ObjectEach is kept for backward compatibility. +func EachObject(data []byte, cb func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) error { + return ObjectEach(data, cb, keys...) +} + +// SYS-REQ-004 +// EachArrayErr is the canonical name; ArrayEachErr is kept for backward compatibility. +func EachArrayErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (int, error) { + return ArrayEachErr(data, cb, keys...) +} + +// SYS-REQ-113 +// EachArrayWildcard is the canonical name; ArrayEachWildcard is kept for backward compatibility. +func EachArrayWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) { + return ArrayEachWildcard(data, cb, keys...) +} diff --git a/vendor/github.com/buger/jsonparser/append.go b/vendor/github.com/buger/jsonparser/append.go new file mode 100644 index 0000000..8e7d71a --- /dev/null +++ b/vendor/github.com/buger/jsonparser/append.go @@ -0,0 +1,49 @@ +package jsonparser + +// Append adds value to the end of the JSON array addressed by keys. +// +// When keys is empty, Append addresses the top-level value. If a keyed path +// does not exist, Append creates it as a single-element array using Set's +// auto-vivification behavior. +// +// SYS-REQ-009, SYS-REQ-110 +func Append(data []byte, value []byte, keys ...string) ([]byte, error) { + _, dataType, startOffset, endOffset, err := internalGet(data, keys...) + if err != nil { + if err != KeyPathNotFoundError || len(keys) == 0 { + return nil, err + } + + arrayValue := make([]byte, len(value)+2) + offset := WriteToBuffer(arrayValue, "[") + offset += copy(arrayValue[offset:], value) + WriteToBuffer(arrayValue[offset:], "]") + + return Set(data, arrayValue, keys...) + } + + if dataType != Array { + return nil, MalformedArrayError + } + + closeOffset := endOffset - 1 + if closeOffset <= startOffset || closeOffset >= len(data) || data[closeOffset] != ']' { + return nil, MalformedArrayError + } + + hasElements := nextToken(data[startOffset+1:closeOffset]) != -1 + extraSpace := len(value) + if hasElements { + extraSpace++ + } + + result := make([]byte, len(data)+extraSpace) + offset := copy(result, data[:closeOffset]) + if hasElements { + offset += WriteToBuffer(result[offset:], ",") + } + offset += copy(result[offset:], value) + copy(result[offset:], data[closeOffset:]) + + return result, nil +} diff --git a/vendor/github.com/buger/jsonparser/bytes.go b/vendor/github.com/buger/jsonparser/bytes.go new file mode 100644 index 0000000..1f30d2e --- /dev/null +++ b/vendor/github.com/buger/jsonparser/bytes.go @@ -0,0 +1,72 @@ +// SYS-REQ-015, SYS-REQ-058, SYS-REQ-059, SYS-REQ-064: integer parsing internals +package jsonparser + +const absMinInt64 = 1 << 63 +const maxInt64 = 1<<63 - 1 +const maxUint64 = 1<<64 - 1 + +// About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON +func parseInt(bytes []byte) (v int64, ok bool, overflow bool) { + l := len(bytes) + if l == 0 { + return 0, false, false + } + + var neg bool = false + i := 0 + if bytes[0] == '-' { + neg = true + i = 1 + } + if i == l { + return 0, false, false + } + + if l-i < 19 { + for ; i < l; i++ { + d := bytes[i] - '0' + if d > 9 { + return 0, false, false + } + v = 10*v + int64(d) + } + + if neg { + return -v, true, false + } + return v, true, false + } + + if neg { + bytes = bytes[1:] + } + + var n uint64 = 0 + for _, c := range bytes { + if c < '0' || c > '9' { + return 0, false, false + } + if n > maxUint64/10 { + return 0, false, true + } + n *= 10 + n1 := n + uint64(c-'0') + if n1 < n { + return 0, false, true + } + n = n1 + } + + if n > maxInt64 { + if neg && n == absMinInt64 { + return -absMinInt64, true, false + } + return 0, false, true + } + + if neg { + return -int64(n), true, false + } else { + return int64(n), true, false + } +} diff --git a/vendor/github.com/buger/jsonparser/bytes_safe.go b/vendor/github.com/buger/jsonparser/bytes_safe.go new file mode 100644 index 0000000..7aa73c4 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/bytes_safe.go @@ -0,0 +1,26 @@ +// +build appengine appenginevm tinygo + +// SYS-REQ-001, SYS-REQ-013, SYS-REQ-014: safe build-tag byte utilities +package jsonparser + +import ( + "strconv" +) + +// See fastbytes_unsafe.go for explanation on why *[]byte is used (signatures must be consistent with those in that file) + +func equalStr(b *[]byte, s string) bool { + return string(*b) == s +} + +func parseFloat(b *[]byte) (float64, error) { + return strconv.ParseFloat(string(*b), 64) +} + +func bytesToString(b *[]byte) string { + return string(*b) +} + +func StringToBytes(s string) []byte { + return []byte(s) +} diff --git a/vendor/github.com/buger/jsonparser/bytes_unsafe.go b/vendor/github.com/buger/jsonparser/bytes_unsafe.go new file mode 100644 index 0000000..8a44d72 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/bytes_unsafe.go @@ -0,0 +1,45 @@ +// +build !appengine,!appenginevm, !tinygo + +// SYS-REQ-001, SYS-REQ-013, SYS-REQ-014: unsafe build-tag byte utilities +package jsonparser + +import ( + "reflect" + "strconv" + "unsafe" + "runtime" +) + +// +// The reason for using *[]byte rather than []byte in parameters is an optimization. As of Go 1.6, +// the compiler cannot perfectly inline the function when using a non-pointer slice. That is, +// the non-pointer []byte parameter version is slower than if its function body is manually +// inlined, whereas the pointer []byte version is equally fast to the manually inlined +// version. Instruction count in assembly taken from "go tool compile" confirms this difference. +// +// TODO: Remove hack after Go 1.7 release +// +func equalStr(b *[]byte, s string) bool { + return *(*string)(unsafe.Pointer(b)) == s +} + +func parseFloat(b *[]byte) (float64, error) { + return strconv.ParseFloat(*(*string)(unsafe.Pointer(b)), 64) +} + +// A hack until issue golang/go#2632 is fixed. +// See: https://github.com/golang/go/issues/2632 +func bytesToString(b *[]byte) string { + return *(*string)(unsafe.Pointer(b)) +} + +func StringToBytes(s string) []byte { + b := make([]byte, 0, 0) + bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) + sh := (*reflect.StringHeader)(unsafe.Pointer(&s)) + bh.Data = sh.Data + bh.Cap = sh.Len + bh.Len = sh.Len + runtime.KeepAlive(s) + return b +} diff --git a/vendor/github.com/buger/jsonparser/config.go b/vendor/github.com/buger/jsonparser/config.go new file mode 100644 index 0000000..66dfc15 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/config.go @@ -0,0 +1,87 @@ +package jsonparser + +import ( + "bytes" + "fmt" +) + +// Config controls opt-in parsing extensions. The zero value is strict and +// accepts only RFC 8259 JSON strings and escapes. +// SYS-REQ-115 +type Config struct { + AllowSingleQuotes bool // #160: accept 'key':'value' alongside "key":"value" + AllowUnknownEscapes bool // #115: accept unknown escape sequences instead of erroring + MaxBufferSize int // ReaderParser sliding-window target; zero uses the 64 MiB default +} + +// DefaultConfig is the strict parser configuration used by package-level +// functions. +// SYS-REQ-115 +var DefaultConfig = Config{} + +// Lenient accepts single-quoted strings and unknown escape sequences. +// SYS-REQ-115 +var Lenient = Config{ + AllowSingleQuotes: true, + AllowUnknownEscapes: true, +} + +// Get returns the value addressed by keys using c's parsing options. +// SYS-REQ-115 +func (c Config) Get(data []byte, keys ...string) ([]byte, ValueType, int, error) { + value, dataType, _, endOffset, err := internalGetConfig(c, data, keys...) + return value, dataType, endOffset, err +} + +// GetString returns the decoded string addressed by keys using c's parsing +// options. +// SYS-REQ-115 +func (c Config) GetString(data []byte, keys ...string) (string, error) { + value, dataType, _, err := c.Get(data, keys...) + if err != nil { + return "", err + } + + if dataType != String { + if dataType == Null { + return "", NullValueError + } + return "", fmt.Errorf("Value is not a string: %s", string(value)) + } + + if bytes.IndexByte(value, '\\') == -1 { + return string(value), nil + } + + var stackbuf [unescapeStackBufSize]byte + unescaped, err := unescapeConfig(c, value, stackbuf[:]) + if err != nil { + return "", MalformedValueError + } + return string(unescaped), nil +} + +// Set replaces the value addressed by keys using c's parsing options. +// SYS-REQ-115 +func (c Config) Set(data []byte, value []byte, keys ...string) ([]byte, error) { + return setConfig(c, data, value, keys...) +} + +// Delete removes the value addressed by keys using c's parsing options. +// SYS-REQ-115 +func (c Config) Delete(data []byte, keys ...string) []byte { + result, _ := deleteFoundConfig(c, data, keys...) + return result +} + +// ArrayEach iterates over the addressed array using c's parsing options. +// SYS-REQ-115 +func (c Config) ArrayEach(data []byte, cb func([]byte, ValueType, int, error), keys ...string) (int, error) { + return arrayEachConfig(c, data, cb, keys...) +} + +// ObjectEach iterates over the addressed object using c's parsing options. +// SYS-REQ-115 +func (c Config) ObjectEach(data []byte, cb func([]byte, []byte, ValueType, int) error, keys ...string) error { + return objectEachConfig(c, data, cb, keys...) +} diff --git a/vendor/github.com/buger/jsonparser/escape.go b/vendor/github.com/buger/jsonparser/escape.go new file mode 100644 index 0000000..992b2f5 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/escape.go @@ -0,0 +1,336 @@ +// SYS-REQ-014, SYS-REQ-060, SYS-REQ-061, SYS-REQ-062, SYS-REQ-063: string escape and Unicode handling +package jsonparser + +import ( + "bytes" + "unicode/utf8" +) + +// JSON Unicode stuff: see https://tools.ietf.org/html/rfc7159#section-7 + +const supplementalPlanesOffset = 0x10000 +const highSurrogateOffset = 0xD800 +const lowSurrogateOffset = 0xDC00 + +const basicMultilingualPlaneReservedOffset = 0xDFFF +const basicMultilingualPlaneOffset = 0xFFFF + +// NOTE: combineUTF16Surrogates is blocked by an unsupported `<<` shift op +// in the translator (Phase T.* gap, beyond #1/#2/#5). Even though Fix #6 +// resolves the package-const references in this body, the shift remains +// untranslated, so no lemma is attached here. +func combineUTF16Surrogates(high, low rune) rune { + return supplementalPlanesOffset + (high-highSurrogateOffset)<<10 + (low - lowSurrogateOffset) +} + +const badHex = -1 + +// reqproof:lemma h2I_range func(c byte) bool { +// r := h2I(c) +// return r == -1 || (r >= 0 && r <= 15) +// } +// +// reqproof:lemma h2I_decimal_digit func(c byte) bool { +// if c < '0' || c > '9' { return true } +// r := h2I(c) +// return r >= 0 && r <= 9 +// } +// +// reqproof:lemma h2I_uppercase_hex func(c byte) bool { +// if c < 'A' || c > 'F' { return true } +// r := h2I(c) +// return r >= 10 && r <= 15 +// } +// +// reqproof:lemma h2I_lowercase_hex func(c byte) bool { +// if c < 'a' || c > 'f' { return true } +// r := h2I(c) +// return r >= 10 && r <= 15 +// } +// +// reqproof:lemma h2I_nondigit_is_badhex func(c byte) bool { +// if c >= '0' && c <= '9' { return true } +// if c >= 'A' && c <= 'F' { return true } +// if c >= 'a' && c <= 'f' { return true } +// return h2I(c) == badHex +// } +// +// reqproof:lemma h2I_nonneg_implies_le_15 func(c byte) bool { +// r := h2I(c) +// if r >= 0 { +// return r <= 15 +// } +// return true +// } +func h2I(c byte) int { + if c >= 48 && c <= 57 { // '0'..'9' + return int(c - 48) + } + if c >= 65 && c <= 70 { // 'A'..'F' + return int(c-65) + 10 + } + if c >= 97 && c <= 102 { // 'a'..'f' + return int(c-97) + 10 + } + return badHex +} + +// decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and +// is not checked. +// In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together. +// This function only handles one; decodeUnicodeEscape handles this more complex case. +func decodeSingleUnicodeEscape(in []byte) (rune, bool) { + // We need at least 6 characters total + if len(in) < 6 { + return utf8.RuneError, false + } + + // Convert hex to decimal + h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5]) + if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex { + return utf8.RuneError, false + } + + // Compose the hex digits + return rune(h1<<12 + h2<<8 + h3<<4 + h4), true +} + +// isUTF16EncodedRune checks if a rune is in the range for non-BMP characters, +// which is used to describe UTF16 chars. +// Source: https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane +// +// reqproof:lemma isUTF16EncodedRune_low_excluded func(r rune) bool { +// return !(r < 0xD800) || !isUTF16EncodedRune(r) +// } +// +// reqproof:lemma isUTF16EncodedRune_const_high_bound func(r rune) bool { +// // Fix #6: package-level const highSurrogateOffset (= 0xD800) now +// // resolves at translation time. Below the high surrogate offset +// // means definitely outside the UTF-16 surrogate range. +// return !(r < highSurrogateOffset) || !isUTF16EncodedRune(r) +// } +// +// reqproof:lemma isUTF16EncodedRune_const_bmp_bound func(r rune) bool { +// // Fix #6: package-level const basicMultilingualPlaneReservedOffset (= 0xDFFF). +// // Above the BMP-reserved offset means outside the UTF-16 surrogate range. +// return !(r > basicMultilingualPlaneReservedOffset) || !isUTF16EncodedRune(r) +// } +func isUTF16EncodedRune(r rune) bool { + return 0xD800 <= r && r <= 0xDFFF +} + +// SYS-REQ-115 +func decodeUnicodeEscape(in []byte) (rune, int) { + if r, ok := decodeSingleUnicodeEscape(in); !ok { + // Invalid Unicode escape + return utf8.RuneError, -1 + } else if !isUTF16EncodedRune(r) { + // Valid Unicode escape in Basic Multilingual Plane. + // Note: a single \uXXXX escape produces r in [0, 0xFFFF], so r is always + // within the BMP. The former r <= basicMultilingualPlaneOffset guard was + // tautological and has been removed — the real discriminator is whether r + // falls in the UTF-16 surrogate range. + return r, 6 + } else if r >= lowSurrogateOffset { + // Lone low surrogate (0xDC00-0xDFFF) with no preceding high surrogate. + // Per RFC 8259/WHATWG a lone surrogate in a JSON string is malformed; + // match encoding/json by substituting U+FFFD and consuming only the 6 + // bytes of this escape. + return utf8.RuneError, 6 + } else if len(in) < 8 || in[6] != '\\' || in[7] != 'u' { + // Lone high surrogate (0xD800-0xDBFF): the high-surrogate escape is not + // followed by a "\u" low-surrogate escape. decodeSingleUnicodeEscape + // assumes the \u prefix and reads hex at fixed offsets, so without this + // guard it would misread whatever bytes follow (e.g. the literal "A7FA" + // after "\uDB29") as a low surrogate and synthesize a bogus code point + // (DEFECT-260727-SNGT). Substitute U+FFFD and consume only the 6 bytes + // of the high surrogate, matching encoding/json. + return utf8.RuneError, 6 + } else if r2, ok := decodeSingleUnicodeEscape(in[6:]); !ok { + // A "\u" follows the high surrogate but the low-surrogate escape is + // itself malformed (truncated / bad hex) — the whole escape is broken. + return utf8.RuneError, -1 + } else if r2 < lowSurrogateOffset || r2 > basicMultilingualPlaneReservedOffset { + // The following "\uXXXX" is not a valid low surrogate (0xDC00-0xDFFF): + // e.g. a BMP codepoint or another high surrogate. Treat the first escape + // as a lone high surrogate → U+FFFD, consuming 6 bytes; the following + // escape is reprocessed by the caller. + return utf8.RuneError, 6 + } else { + // Valid UTF16 surrogate pair + return combineUTF16Surrogates(r, r2), 12 + } +} + +// backslashCharEscapeTable: when '\X' is found for some byte X, it is to be replaced with backslashCharEscapeTable[X] +var backslashCharEscapeTable = [...]byte{ + '"': '"', + '\\': '\\', + '/': '/', + 'b': '\b', + 'f': '\f', + 'n': '\n', + 'r': '\r', + 't': '\t', +} + +// unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns +// how many characters were consumed from 'in' and emitted into 'out'. +// If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error. +func unescapeToUTF8(in, out []byte) (inLen int, outLen int) { + return unescapeToUTF8Config(DefaultConfig, in, out) +} + +// SYS-REQ-115 +func unescapeToUTF8Config(config Config, in, out []byte) (inLen int, outLen int) { + if len(in) < 2 || in[0] != '\\' { + // Invalid escape due to insufficient characters for any escape or no initial backslash + return -1, -1 + } + + // https://tools.ietf.org/html/rfc7159#section-7 + switch e := in[1]; e { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + // Valid basic 2-character escapes (use lookup table) + out[0] = backslashCharEscapeTable[e] + return 2, 1 + case '\'': + if config.AllowSingleQuotes { + out[0] = e + return 2, 1 + } + case 'u': + // Unicode escape + if r, inLen := decodeUnicodeEscape(in); inLen == -1 { + // Invalid Unicode escape + return -1, -1 + } else { + // Valid Unicode escape; re-encode as UTF8 + outLen := utf8.EncodeRune(out, r) + return inLen, outLen + } + } + + if config.AllowUnknownEscapes { + // Lenient mode treats the escaped byte as a literal and discards the + // escape marker. A trailing '\' and malformed \u escape remain errors: + // they are truncated/invalid encodings, not unknown escape names. + out[0] = in[1] + return 2, 1 + } + + return -1, -1 +} + +const lowerHex = "0123456789abcdef" + +// Escape returns in as a JSON string literal, including the surrounding +// quotation marks. +// SYS-REQ-014 +func Escape(in string) []byte { + var stackbuf [unescapeStackBufSize]byte + out := stackbuf[:0] + out = append(out, '"') + + start := 0 + for i := 0; i < len(in); i++ { + c := in[i] + if c >= 0x20 && c != '"' && c != '\\' { + continue + } + + out = append(out, in[start:i]...) + switch c { + case '"', '\\': + out = append(out, '\\', c) + case '\b': + out = append(out, '\\', 'b') + case '\f': + out = append(out, '\\', 'f') + case '\n': + out = append(out, '\\', 'n') + case '\r': + out = append(out, '\\', 'r') + case '\t': + out = append(out, '\\', 't') + default: + out = append(out, '\\', 'u', '0', '0', lowerHex[c>>4], lowerHex[c&0x0f]) + } + start = i + 1 + } + + out = append(out, in[start:]...) + return append(out, '"') +} + +// SetString replaces the value at keys with val encoded as a JSON string. +// SYS-REQ-009 +func SetString(data []byte, val string, keys ...string) ([]byte, error) { + return Set(data, Escape(val), keys...) +} + +// unescape unescapes the string contained in 'in' and returns it as a slice. +// If 'in' contains no escaped characters: +// +// Returns 'in'. +// +// Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)): +// +// 'out' is used to build the unescaped string and is returned with no extra allocation +// +// Else: +// +// A new slice is allocated and returned. +func Unescape(in, out []byte) ([]byte, error) { + return unescapeConfig(DefaultConfig, in, out) +} + +// SYS-REQ-115 +func unescapeConfig(config Config, in, out []byte) ([]byte, error) { + firstBackslash := bytes.IndexByte(in, '\\') + if firstBackslash == -1 { + return in, nil + } + + // Get a buffer of sufficient size (allocate if needed) + if cap(out) < len(in) { + out = make([]byte, len(in)) + } else { + out = out[0:len(in)] + } + + // Copy the first sequence of unescaped bytes to the output and obtain a buffer pointer (subslice) + copy(out, in[:firstBackslash]) + in = in[firstBackslash:] + buf := out[firstBackslash:] + + // The loop always exits via break: either on error (MalformedStringEscapeError) + // or after copying the final non-escaped tail. The former `for len(in) > 0` + // guard was structurally always true on re-entry since the else branch always + // leaves at least the backslash character in `in`. + for { + // Unescape the next escaped character + inLen, bufLen := unescapeToUTF8Config(config, in, buf) + if inLen == -1 { + return nil, MalformedStringEscapeError + } + + in = in[inLen:] + buf = buf[bufLen:] + + // Copy everything up until the next backslash + nextBackslash := bytes.IndexByte(in, '\\') + if nextBackslash == -1 { + copy(buf, in) + buf = buf[len(in):] + break + } else { + copy(buf, in[:nextBackslash]) + buf = buf[nextBackslash:] + in = in[nextBackslash:] + } + } + + // Trim the out buffer to the amount that was actually emitted + return out[:len(out)-len(buf)], nil +} diff --git a/vendor/github.com/buger/jsonparser/fuzz.go b/vendor/github.com/buger/jsonparser/fuzz.go new file mode 100644 index 0000000..75bbedb --- /dev/null +++ b/vendor/github.com/buger/jsonparser/fuzz.go @@ -0,0 +1,131 @@ +package jsonparser + +// SYS-REQ-014 +func FuzzParseString(data []byte) int { + r, err := ParseString(data) + if err != nil || r == "" { + return 0 + } + return 1 +} + +// SYS-REQ-008 +func FuzzEachKey(data []byte) int { + paths := [][]string{ + {"name"}, + {"order"}, + {"nested", "a"}, + {"nested", "b"}, + {"nested2", "a"}, + {"nested", "nested3", "b"}, + {"arr", "[1]", "b"}, + {"arrInt", "[3]"}, + {"arrInt", "[5]"}, + {"nested"}, + {"arr", "["}, + {"a\n", "b\n"}, + } + EachKey(data, func(idx int, value []byte, vt ValueType, err error) {}, paths...) + return 1 +} + +// SYS-REQ-010 +func FuzzDelete(data []byte) int { + Delete(data, "test") + return 1 +} + +// SYS-REQ-009 +func FuzzSet(data []byte) int { + _, err := Set(data, []byte(`"new value"`), "test") + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-007 +func FuzzObjectEach(data []byte) int { + _ = ObjectEach(data, func(key, value []byte, valueType ValueType, off int) error { + return nil + }) + return 1 +} + +// SYS-REQ-013 +func FuzzParseFloat(data []byte) int { + _, err := ParseFloat(data) + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-015 +func FuzzParseInt(data []byte) int { + _, err := ParseInt(data) + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-012 +func FuzzParseBool(data []byte) int { + _, err := ParseBoolean(data) + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-001 +func FuzzTokenStart(data []byte) int { + _ = tokenStart(data) + return 1 +} + +// SYS-REQ-002 +func FuzzGetString(data []byte) int { + _, err := GetString(data, "test") + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-004 +func FuzzGetFloat(data []byte) int { + _, err := GetFloat(data, "test") + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-003 +func FuzzGetInt(data []byte) int { + _, err := GetInt(data, "test") + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-005 +func FuzzGetBoolean(data []byte) int { + _, err := GetBoolean(data, "test") + if err != nil { + return 0 + } + return 1 +} + +// SYS-REQ-011 +func FuzzGetUnsafeString(data []byte) int { + _, err := GetUnsafeString(data, "test") + if err != nil { + return 0 + } + return 1 +} diff --git a/vendor/github.com/buger/jsonparser/oss-fuzz-build.sh b/vendor/github.com/buger/jsonparser/oss-fuzz-build.sh new file mode 100644 index 0000000..c573b0e --- /dev/null +++ b/vendor/github.com/buger/jsonparser/oss-fuzz-build.sh @@ -0,0 +1,47 @@ +#!/bin/bash -eu + +git clone https://github.com/dvyukov/go-fuzz-corpus +zip corpus.zip go-fuzz-corpus/json/corpus/* + +cp corpus.zip $OUT/fuzzparsestring_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzParseString fuzzparsestring + +cp corpus.zip $OUT/fuzzeachkey_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzEachKey fuzzeachkey + +cp corpus.zip $OUT/fuzzdelete_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzDelete fuzzdelete + +cp corpus.zip $OUT/fuzzset_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzSet fuzzset + +cp corpus.zip $OUT/fuzzobjecteach_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzObjectEach fuzzobjecteach + +cp corpus.zip $OUT/fuzzparsefloat_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzParseFloat fuzzparsefloat + +cp corpus.zip $OUT/fuzzparseint_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzParseInt fuzzparseint + +cp corpus.zip $OUT/fuzzparsebool_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzParseBool fuzzparsebool + +cp corpus.zip $OUT/fuzztokenstart_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzTokenStart fuzztokenstart + +cp corpus.zip $OUT/fuzzgetstring_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzGetString fuzzgetstring + +cp corpus.zip $OUT/fuzzgetfloat_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzGetFloat fuzzgetfloat + +cp corpus.zip $OUT/fuzzgetint_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzGetInt fuzzgetint + +cp corpus.zip $OUT/fuzzgetboolean_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzGetBoolean fuzzgetboolean + +cp corpus.zip $OUT/fuzzgetunsafestring_seed_corpus.zip +compile_go_fuzzer github.com/buger/jsonparser FuzzGetUnsafeString fuzzgetunsafestring + diff --git a/vendor/github.com/buger/jsonparser/parser.go b/vendor/github.com/buger/jsonparser/parser.go new file mode 100644 index 0000000..cdbe09e --- /dev/null +++ b/vendor/github.com/buger/jsonparser/parser.go @@ -0,0 +1,2535 @@ +package jsonparser + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "strconv" +) + +// Errors +var ( + KeyPathNotFoundError = errors.New("Key path not found") + UnknownValueTypeError = errors.New("Unknown value type") + MalformedJsonError = errors.New("Malformed JSON error") + MalformedStringError = errors.New("Value is string, but can't find closing '\"' symbol") + MalformedArrayError = errors.New("Value is array, but can't find closing ']' symbol") + MalformedObjectError = errors.New("Value looks like object, but can't find closing '}' symbol") + MalformedValueError = errors.New("Value looks like Number/Boolean/None, but can't find its end: ',' or '}' symbol") + OverflowIntegerError = errors.New("Value is number, but overflowed while parsing") + MalformedStringEscapeError = errors.New("Encountered an invalid escape sequence in a string") + NullValueError = errors.New("Value is null") +) + +// How much stack space to allocate for unescaping JSON strings; if a string longer +// than this needs to be escaped, it will result in a heap allocation +const unescapeStackBufSize = 64 + +// SYS-REQ-044 +// +// reqproof:lemma tokenEnd_in_range func(data []byte) bool { +// r := tokenEnd(data) +// return r >= 0 && r <= len(data) +// } +// +// reqproof:lemma tokenEnd_nonneg func(data []byte) bool { +// // tokenEnd never signals via a negative sentinel — the empty-input +// // path returns len(data)==0 (still nonneg), and any hit returns the +// // loop index (also nonneg). +// return tokenEnd(data) >= 0 +// } +// +// reqproof:lemma tokenEnd_empty_zero func(data []byte) bool { +// return !(len(data) == 0) || tokenEnd(data) == 0 +// } +// +// reqproof:lemma tokenEnd_path_indexable_implies_nonneg func(data []byte) bool { +// r := tokenEnd(data) +// if r < len(data) { +// return r >= 0 +// } +// return true +// } +func tokenEnd(data []byte) int { + for i, c := range data { + // reqproof:invariant 0 <= i + // reqproof:invariant i <= len(data) + if c != 32 && c != 10 && c != 13 && c != 9 && c != 44 && c != 125 && c != 93 { + continue + } + return i + } + + return len(data) +} + +// isJSONWhitespace reports whether b is one of the four JSON whitespace bytes +// (space 0x20, tab 0x09, LF 0x0A, CR 0x0D) per RFC 8259 §2. Used by Delete's +// trailing-comma cleanup to decide whether the byte at endOffset+tokEnd is +// whitespace preceding a comma, so the cleanup advances past both. The byte +// set mirrors tokenEnd's whitespace classification above. +// SYS-REQ-010, SYS-REQ-034, SYS-REQ-035 +func isJSONWhitespace(b byte) bool { + return b == ' ' || b == '\t' || b == '\n' || b == '\r' +} + +// SYS-REQ-001 +// NOTE: findTokenStart's two-conditional-return body shape exposes +// the translator's __early_val scoping bug; we leave it without an +// in-range lemma. (Documented as a Phase S.2c.4 follow-up.) +func findTokenStart(data []byte, token byte) int { + for i := len(data) - 1; i >= 0; i-- { + switch data[i] { + case token: + return i + case '[', '{': + return 0 + } + } + + return 0 +} + +// SYS-REQ-001, SYS-REQ-020, SYS-REQ-024 +func findKeyStart(data []byte, key string) (int, error) { + return findKeyStartConfig(DefaultConfig, data, key) +} + +// SYS-REQ-115 +func findKeyStartConfig(config Config, data []byte, key string) (int, error) { + i := nextTokenConfig(config, data) + if i == -1 { + return i, KeyPathNotFoundError + } + ln := len(data) + // Note: nextToken returning non-negative (checked above) guarantees ln > 0, + // so the former ln > 0 guard was tautological and has been removed. + if data[i] == '{' || data[i] == '[' { + i += 1 + } + var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings + + if ku, err := unescapeConfig(config, StringToBytes(key), stackbuf[:]); err == nil { + key = bytesToString(&ku) + } + + for i < ln { + switch data[i] { + case '"', '\'': + quote := data[i] + if quote == '\'' && !config.AllowSingleQuotes { + break + } + i++ + keyBegin := i + + strEnd, keyEscaped := stringEndConfig(config, data[i:], quote) + if strEnd == -1 { + break + } + i += strEnd + keyEnd := i - 1 + + valueOffset := nextTokenConfig(config, data[i:]) + if valueOffset == -1 { + break + } + + i += valueOffset + + // if string is a key, and key level match + k := data[keyBegin:keyEnd] + // for unescape: if there are no escape sequences, this is cheap; if there are, it is a + // bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize + if keyEscaped { + if ku, err := unescapeConfig(config, k, stackbuf[:]); err != nil { + break + } else { + k = ku + } + } + + if data[i] == ':' && len(key) == len(k) && bytesToString(&k) == key { + return keyBegin - 1, nil + } + + case '[': + end := blockEndConfig(config, data[i:], data[i], ']') + if end != -1 { + i = i + end + } + case '{': + end := blockEndConfig(config, data[i:], data[i], '}') + if end != -1 { + i = i + end + } + } + i++ + } + + return -1, KeyPathNotFoundError +} + +// SYS-REQ-001 +// +// reqproof:lemma tokenStart_in_range func(data []byte) bool { +// r := tokenStart(data) +// return r >= 0 && r <= len(data) +// } +// +// reqproof:lemma tokenStart_nonneg func(data []byte) bool { +// return tokenStart(data) >= 0 +// } +// +// reqproof:lemma tokenStart_empty_zero func(data []byte) bool { +// return !(len(data) == 0) || tokenStart(data) == 0 +// } +// +// reqproof:lemma tokenStart_path_indexable_when_nonempty func(data []byte) bool { +// r := tokenStart(data) +// if len(data) > 0 { +// return r >= 0 && r < len(data) +// } +// return r == 0 +// } +func tokenStart(data []byte) int { + for i := len(data) - 1; i >= 0; i-- { + // reqproof:invariant -1 <= i + // reqproof:invariant i < len(data) + c := data[i] + if c != 10 && c != 13 && c != 9 && c != 44 && c != 123 && c != 91 { + continue + } + return i + } + + return 0 +} + +// SYS-REQ-001 +// Find position of next character which is not whitespace +// +// reqproof:lemma nextToken_in_range func(data []byte) bool { +// r := nextToken(data) +// return r >= -1 && r < len(data) +// } +// +// reqproof:lemma nextToken_empty_neg func(data []byte) bool { +// return !(len(data) == 0) || nextToken(data) == -1 +// } +// +// reqproof:lemma nextToken_signed_disjoint func(data []byte) bool { +// r := nextToken(data) +// // Result is either -1 (sentinel) or a non-negative index — never -2 or below +// return r == -1 || r >= 0 +// } +// +// reqproof:lemma nextToken_path_indexable_implies_lt_len func(data []byte) bool { +// r := nextToken(data) +// if r >= 0 { +// return r < len(data) +// } +// return true +// } +func nextToken(data []byte) int { + return nextTokenConfig(DefaultConfig, data) +} + +// SYS-REQ-115 +func nextTokenConfig(_ Config, data []byte) int { + for i, c := range data { + // reqproof:invariant 0 <= i + // reqproof:invariant i <= len(data) + if c == ' ' || c == '\n' || c == '\r' || c == '\t' { + continue + } + return i + } + + return -1 +} + +// SYS-REQ-001 +// Find position of last character which is not whitespace +// +// reqproof:lemma lastToken_in_range func(data []byte) bool { +// r := lastToken(data) +// return r >= -1 && r < len(data) +// } +// +// reqproof:lemma lastToken_empty_neg func(data []byte) bool { +// return !(len(data) == 0) || lastToken(data) == -1 +// } +// +// reqproof:lemma lastToken_signed_disjoint func(data []byte) bool { +// r := lastToken(data) +// // Result is either -1 (sentinel) or a non-negative index — never -2 or below +// return r == -1 || r >= 0 +// } +// +// reqproof:lemma lastToken_path_indexable_implies_lt_len func(data []byte) bool { +// r := lastToken(data) +// if r >= 0 { +// return r < len(data) +// } +// return true +// } +func lastToken(data []byte) int { + for i := len(data) - 1; i >= 0; i-- { + // reqproof:invariant -1 <= i + // reqproof:invariant i < len(data) + c := data[i] + if c == ' ' || c == '\n' || c == '\r' || c == '\t' { + continue + } + return i + } + + return -1 +} + +// SYS-REQ-045 +// Tries to find the end of string +// Support if string contains escaped quote symbols. +func stringEnd(data []byte) (int, bool) { + return stringEndConfig(DefaultConfig, data, '"') +} + +// SYS-REQ-115 +func stringEndConfig(_ Config, data []byte, quote byte) (int, bool) { + // SWAR (SIMD-Within-A-Register) fast path: scan 8 bytes at a time for + // either the closing quote or a backslash, then a per-byte tail that + // counts the run of '\\' before each quote candidate. + // + // Investigation: easyjson's jlexer.findStringLen + // (mailru/easyjson@v0.9.2/jlexer/lexer.go:247) uses a single SIMD + // bytes.IndexByte('"') plus a backward backslash-run count, deferring the + // separate backslash scan to unescapeStringToken. That style was ported + // and benchmarked here as "single IndexByte for the quote + a bounded + // bytes.IndexByte(data[:firstQuote], '\\') for the escape flag". On + // arm64 (Apple M4 Max, NEON) the two IndexByte *function calls* cost more + // than this inline 8-byte SWAR loop, because jsonparser must compute the + // escape flag inline (its callers gate unescapeConfig on it), so the + // second scan cannot be deferred the way easyjson defers it. + // + // Measured on M4 Max (BenchmarkJsonParserLarge, median of 5): + // SWAR (this): ~21000 ns/op + // two-IndexByte port: ~22600 ns/op (-7%) + // For reference easyjson itself is ~33200 ns/op here, so jsonparser + // already leads; the easyjson technique is not beneficial on arm64. + const swarLsb = 0x0101010101010101 + const swarMsb = 0x8080808080808080 + broadcastQuote := uint64(quote) * swarLsb + broadcastBackslash := uint64('\\') * swarLsb + + i := 0 + n := len(data) + for i+8 <= n { + w := binary.LittleEndian.Uint64(data[i:]) + xq := w ^ broadcastQuote + xb := w ^ broadcastBackslash + quoteHit := (xq - swarLsb) & ^xq & swarMsb + bsHit := (xb - swarLsb) & ^xb & swarMsb + if quoteHit|bsHit == 0 { + i += 8 + continue + } + break + } + 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 { + return i + 1, false + } + j := i - 1 + for { + if j < 0 || data[j] != '\\' { + return i + 1, true // even run of backslashes + } + j-- + if j < 0 || data[j] != '\\' { + break // odd run of backslashes -> quote is escaped + } + j-- + } + } else if c == '\\' { + escaped = true + } + } + return -1, escaped +} + +// SYS-REQ-046 +// Find end of the data structure, array or object. +// For array openSym and closeSym will be '[' and ']', for object '{' and '}' +func blockEnd(data []byte, openSym byte, closeSym byte) int { + return blockEndConfig(DefaultConfig, data, openSym, closeSym) +} + +// SYS-REQ-115 +func blockEndConfig(config Config, data []byte, openSym byte, closeSym byte) int { + level := 0 + i := 0 + 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] + if quote == '\'' && !config.AllowSingleQuotes { + break + } + se, _ := stringEndConfig(config, data[i+1:], quote) + if se == -1 { + return -1 + } + i += se + case openSym: // If open symbol, increase level + level++ + case closeSym: // If close symbol, increase level + level-- + + // If we have returned to the original level, we're done + if level == 0 { + return i + 1 + } + } + i++ + } + + return -1 +} + +// SYS-REQ-001, SYS-REQ-020, SYS-REQ-021, SYS-REQ-022, SYS-REQ-023, SYS-REQ-047, SYS-REQ-111 +func searchKeys(data []byte, keys ...string) int { + return searchKeysConfig(DefaultConfig, data, keys...) +} + +// SYS-REQ-115 +func searchKeysConfig(config Config, data []byte, keys ...string) int { + keyLevel := 0 + level := 0 + i := 0 + ln := len(data) + lk := len(keys) + lastMatched := true + + if lk == 0 { + return 0 + } + + 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] + if quote == '\'' && !config.AllowSingleQuotes { + break + } + i++ + keyBegin := i + + strEnd, keyEscaped := stringEndConfig(config, data[i:], quote) + if strEnd == -1 { + return -1 + } + i += strEnd + keyEnd := i - 1 + + valueOffset := nextTokenConfig(config, data[i:]) + if valueOffset == -1 { + return -1 + } + + i += valueOffset + + // if string is a key + if data[i] == ':' { + if level < 1 { + return -1 + } + + key := data[keyBegin:keyEnd] + + // for unescape: if there are no escape sequences, this is cheap; if there are, it is a + // bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize + var keyUnesc []byte + if !keyEscaped { + keyUnesc = key + } else if ku, err := unescapeConfig(config, key, stackbuf[:]); err != nil { + return -1 + } else { + keyUnesc = ku + } + + if level <= len(keys) { + if equalStr(&keyUnesc, keys[level-1]) { + lastMatched = true + + // if key level match + if keyLevel == level-1 { + keyLevel++ + // If we found all keys in path + if keyLevel == lk { + return i + 1 + } + } + } else { + lastMatched = false + } + } else { + return -1 + } + } else { + i-- + } + case '{': + + // in case parent key is matched then only we will increase the level otherwise can directly + // can move to the end of this block + if !lastMatched { + end := blockEndConfig(config, data[i:], '{', '}') + if end == -1 { + return -1 + } + i += end - 1 + } else { + level++ + } + case '}': + level-- + if level == keyLevel { + keyLevel-- + } + case '[': + // If we want to get array element by index + // guard: empty key component — not an array index, fall through to skip. + if keyLevel == level && len(keys[level]) > 0 && keys[level][0] == '[' { + keyLen := len(keys[level]) + // Note: keys[level][0] == '[' is guaranteed by the outer if-guard, + // so the former middle term `keys[level][0] != '['` was always false + // (dead code) and has been removed. + // guard: bounds-check on the same variable before the [keyLen-1] deref. + if len(keys[level]) < 3 || keys[level][keyLen-1] != ']' { + return -1 + } + aIdx, err := strconv.Atoi(keys[level][1 : keyLen-1]) + if err != nil { + return -1 + } + var curIdx int + var valueFound []byte + var valueOffset int + curI := i + arrayEachConfig(config, data[i:], func(value []byte, dataType ValueType, offset int, err error) { + if curIdx == aIdx { + valueFound = value + valueOffset = offset + if dataType == String { + valueOffset = valueOffset - 2 + valueFound = data[curI+valueOffset : curI+valueOffset+len(value)+2] + } + } + curIdx += 1 + }) + + if valueFound == nil { + return -1 + } else { + subIndex := searchKeysConfig(config, valueFound, keys[level+1:]...) + if subIndex < 0 { + return -1 + } + return i + valueOffset + subIndex + } + } else { + // Do not search for keys inside arrays + if arraySkip := blockEndConfig(config, data[i:], '[', ']'); arraySkip == -1 { + return -1 + } else { + i += arraySkip - 1 + } + } + case ':': // If encountered, JSON data is malformed + return -1 + } + + i++ + } + + return -1 +} + +// SYS-REQ-008 +func sameTree(p1, p2 []string) bool { + minLen := len(p1) + if len(p2) < minLen { + minLen = len(p2) + } + + for pi_1, p_1 := range p1[:minLen] { + if p2[pi_1] != p_1 { + return false + } + } + + return true +} + +const stackArraySize = 128 + +// SYS-REQ-008, SYS-REQ-085, SYS-REQ-111 +func EachKey(data []byte, cb func(int, []byte, ValueType, error), paths ...[]string) int { + var x struct{} + var level, pathsMatched, i int + ln := len(data) + + pathFlags := make([]bool, stackArraySize)[:] + if len(paths) > cap(pathFlags) { + pathFlags = make([]bool, len(paths))[:] + } + pathFlags = pathFlags[0:len(paths)] + + var maxPath int + for _, p := range paths { + if len(p) > maxPath { + maxPath = len(p) + } + } + + pathsBuf := make([]string, stackArraySize)[:] + if maxPath > cap(pathsBuf) { + pathsBuf = make([]string, maxPath)[:] + } + pathsBuf = pathsBuf[0:maxPath] + + for i < ln { + switch data[i] { + case '"': + i++ + keyBegin := i + + strEnd, keyEscaped := stringEnd(data[i:]) + if strEnd == -1 { + return -1 + } + i += strEnd + + keyEnd := i - 1 + + valueOffset := nextToken(data[i:]) + if valueOffset == -1 { + return -1 + } + + i += valueOffset + + // if string is a key, and key level match + if data[i] == ':' { + match := -1 + key := data[keyBegin:keyEnd] + + // for unescape: if there are no escape sequences, this is cheap; if there are, it is a + // bit more expensive, but causes no allocations unless len(key) > unescapeStackBufSize + var keyUnesc []byte + if !keyEscaped { + keyUnesc = key + } else { + var stackbuf [unescapeStackBufSize]byte + if ku, err := Unescape(key, stackbuf[:]); err != nil { + return -1 + } else { + keyUnesc = ku + } + } + + if maxPath >= level { + if level < 1 { + cb(-1, nil, Unknown, MalformedJsonError) + return -1 + } + + pathsBuf[level-1] = bytesToString(&keyUnesc) + for pi, p := range paths { + if len(p) != level || pathFlags[pi] || !equalStr(&keyUnesc, p[level-1]) || !sameTree(p, pathsBuf[:level]) { + continue + } + + match = pi + + pathsMatched++ + pathFlags[pi] = true + + v, dt, _, e := Get(data[i+1:]) + cb(pi, v, dt, e) + + if pathsMatched == len(paths) { + break + } + } + if pathsMatched == len(paths) { + return i + } + } + + if match == -1 { + tokenOffset := nextToken(data[i+1:]) + i += tokenOffset + // Note: i is now at the character BEFORE the value (the colon + // when tokenOffset==0, or the last whitespace character otherwise). + // The former `if data[i] == '{'` block-skip was structurally dead + // code because i never reaches the opening brace — the outer loop's + // i++ advances to it on the next iteration. Likewise, the former + // `if i < ln` guard was tautological since i remains within bounds. + } + + switch data[i] { + case '{', '}', '[', '"': + i-- + } + } else { + i-- + } + case '{': + level++ + case '}': + level-- + case '[': + var ok bool + arrIdxFlags := make(map[int]struct{}) + + pIdxFlags := make([]bool, stackArraySize)[:] + if len(paths) > cap(pIdxFlags) { + pIdxFlags = make([]bool, len(paths))[:] + } + pIdxFlags = pIdxFlags[0:len(paths)] + + if level < 0 { + cb(-1, nil, Unknown, MalformedJsonError) + return -1 + } + + for pi, p := range paths { + // guard: empty key component — skip this path (not an array index). + if len(p) < level+1 || pathFlags[pi] || len(p[level]) == 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { + continue + } + + indexComponent := p[level] + if len(indexComponent) < 3 || indexComponent[len(indexComponent)-1] != ']' { + continue + } + aIdx, err := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if err != nil { + continue + } + arrIdxFlags[aIdx] = x + pIdxFlags[pi] = true + } + + if len(arrIdxFlags) > 0 { + level++ + + var curIdx int + arrOff, _ := ArrayEach(data[i:], func(value []byte, dataType ValueType, offset int, err error) { + if _, ok = arrIdxFlags[curIdx]; ok { + for pi, p := range paths { + if !pIdxFlags[pi] || pathFlags[pi] { + continue + } + + indexComponent := p[level-1] + aIdx, parseErr := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if parseErr != nil || curIdx != aIdx { + continue + } + + if level == len(p) { + // ArrayEach has already parsed the terminal value. + // In particular, string values do not include their + // quotes and therefore cannot be reparsed by Get. + pathsMatched++ + pathFlags[pi] = true + cb(pi, value, dataType, err) + continue + } + + of := searchKeys(value, p[level:]...) + if of == -1 { + continue + } + + v, dt, _, e := Get(value[of:]) + pathsMatched++ + pathFlags[pi] = true + cb(pi, v, dt, e) + } + } + + curIdx += 1 + }) + + if pathsMatched == len(paths) { + return i + } + + i += arrOff - 1 + } else { + // Do not search for keys inside arrays + if arraySkip := blockEnd(data[i:], '[', ']'); arraySkip == -1 { + return -1 + } else { + i += arraySkip - 1 + } + } + case ']': + level-- + } + + i++ + } + + return -1 +} + +// EachKeyErr finds the requested paths and allows the callback to stop +// iteration by returning an error. io.EOF stops iteration gracefully. +// SYS-REQ-008 +func EachKeyErr(data []byte, cb func(idx int, value []byte, vt ValueType, err error) error, paths ...[]string) error { + var x struct{} + var level, pathsMatched, i int + ln := len(data) + + pathFlags := make([]bool, stackArraySize)[:] + if len(paths) > cap(pathFlags) { + pathFlags = make([]bool, len(paths))[:] + } + pathFlags = pathFlags[0:len(paths)] + + var maxPath int + for _, p := range paths { + if len(p) > maxPath { + maxPath = len(p) + } + } + + pathsBuf := make([]string, stackArraySize)[:] + if maxPath > cap(pathsBuf) { + pathsBuf = make([]string, maxPath)[:] + } + pathsBuf = pathsBuf[0:maxPath] + + for i < ln { + switch data[i] { + case '"': + i++ + keyBegin := i + + strEnd, keyEscaped := stringEnd(data[i:]) + if strEnd == -1 { + return nil + } + i += strEnd + + keyEnd := i - 1 + + valueOffset := nextToken(data[i:]) + if valueOffset == -1 { + return nil + } + + i += valueOffset + + if data[i] == ':' { + match := -1 + key := data[keyBegin:keyEnd] + + var keyUnesc []byte + if !keyEscaped { + keyUnesc = key + } else { + var stackbuf [unescapeStackBufSize]byte + if ku, unescapeErr := Unescape(key, stackbuf[:]); unescapeErr != nil { + return nil + } else { + keyUnesc = ku + } + } + + if maxPath >= level { + if level < 1 { + callbackErr := cb(-1, nil, Unknown, MalformedJsonError) + if callbackErr != nil && !errors.Is(callbackErr, io.EOF) { + return callbackErr + } + return nil + } + + pathsBuf[level-1] = bytesToString(&keyUnesc) + for pi, p := range paths { + if len(p) != level || pathFlags[pi] || !equalStr(&keyUnesc, p[level-1]) || !sameTree(p, pathsBuf[:level]) { + continue + } + + match = pi + + pathsMatched++ + pathFlags[pi] = true + + v, dt, _, parseErr := Get(data[i+1:]) + if callbackErr := cb(pi, v, dt, parseErr); callbackErr != nil { + if errors.Is(callbackErr, io.EOF) { + return nil + } + return callbackErr + } + + if pathsMatched == len(paths) { + break + } + } + if pathsMatched == len(paths) { + return nil + } + } + + if match == -1 { + tokenOffset := nextToken(data[i+1:]) + i += tokenOffset + } + + switch data[i] { + case '{', '}', '[', '"': + i-- + } + } else { + i-- + } + case '{': + level++ + case '}': + level-- + case '[': + var ok bool + arrIdxFlags := make(map[int]struct{}) + + pIdxFlags := make([]bool, stackArraySize)[:] + if len(paths) > cap(pIdxFlags) { + pIdxFlags = make([]bool, len(paths))[:] + } + pIdxFlags = pIdxFlags[0:len(paths)] + + if level < 0 { + callbackErr := cb(-1, nil, Unknown, MalformedJsonError) + if callbackErr != nil && !errors.Is(callbackErr, io.EOF) { + return callbackErr + } + return nil + } + + for pi, p := range paths { + if len(p) < level+1 || pathFlags[pi] || len(p[level]) == 0 || p[level][0] != '[' || !sameTree(p, pathsBuf[:level]) { + continue + } + + indexComponent := p[level] + if len(indexComponent) < 3 || indexComponent[len(indexComponent)-1] != ']' { + continue + } + aIdx, parseErr := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if parseErr != nil { + continue + } + arrIdxFlags[aIdx] = x + pIdxFlags[pi] = true + } + + if len(arrIdxFlags) > 0 { + level++ + + var curIdx int + var callbackErr error + var stopped bool + arrOff, _, _ := arrayEachErr(data[i:], func(value []byte, dataType ValueType, offset int, parseErr error) error { + if _, ok = arrIdxFlags[curIdx]; ok { + for pi, p := range paths { + if !pIdxFlags[pi] || pathFlags[pi] { + continue + } + + indexComponent := p[level-1] + aIdx, indexErr := strconv.Atoi(indexComponent[1 : len(indexComponent)-1]) + if indexErr != nil || curIdx != aIdx { + continue + } + + if level == len(p) { + pathsMatched++ + pathFlags[pi] = true + callbackErr = cb(pi, value, dataType, parseErr) + if callbackErr != nil { + stopped = true + return callbackErr + } + continue + } + + of := searchKeys(value, p[level:]...) + if of == -1 { + continue + } + + v, dt, _, getErr := Get(value[of:]) + pathsMatched++ + pathFlags[pi] = true + callbackErr = cb(pi, v, dt, getErr) + if callbackErr != nil { + stopped = true + return callbackErr + } + } + } + + curIdx++ + return nil + }) + + if stopped { + if errors.Is(callbackErr, io.EOF) { + return nil + } + return callbackErr + } + + if pathsMatched == len(paths) { + return nil + } + + i += arrOff - 1 + } else { + if arraySkip := blockEnd(data[i:], '[', ']'); arraySkip == -1 { + return nil + } else { + i += arraySkip - 1 + } + } + case ']': + level-- + } + + i++ + } + + return nil +} + +// Data types available in valid JSON data. +type ValueType int + +const ( + NotExist = ValueType(iota) + String + Number + Object + Array + Boolean + Null + Unknown +) + +// SYS-REQ-001 +func (vt ValueType) String() string { + switch vt { + case NotExist: + return "non-existent" + case String: + return "string" + case Number: + return "number" + case Object: + return "object" + case Array: + return "array" + case Boolean: + return "boolean" + case Null: + return "null" + default: + return "unknown" + } +} + +var ( + trueLiteral = []byte("true") + falseLiteral = []byte("false") + nullLiteral = []byte("null") +) + +// SYS-REQ-009, SYS-REQ-110, SYS-REQ-111 +func createInsertComponent(keys []string, setValue []byte, comma, object bool) []byte { + // guard: empty key component — not an array index. + isIndex := len(keys[0]) > 0 && string(keys[0][0]) == "[" + offset := 0 + lk := calcAllocateSpace(keys, setValue, comma, object) + buffer := make([]byte, lk, lk) + if comma { + offset += WriteToBuffer(buffer[offset:], ",") + } + if isIndex && !comma { + offset += WriteToBuffer(buffer[offset:], "[") + } else { + if object { + offset += WriteToBuffer(buffer[offset:], "{") + } + if !isIndex { + offset += WriteToBuffer(buffer[offset:], "\"") + offset += WriteToBuffer(buffer[offset:], keys[0]) + offset += WriteToBuffer(buffer[offset:], "\":") + } + } + + for i := 1; i < len(keys); i++ { + // guard: empty key component — treat as object key, not array index. + if len(keys[i]) > 0 && string(keys[i][0]) == "[" { + offset += WriteToBuffer(buffer[offset:], "[") + } else { + offset += WriteToBuffer(buffer[offset:], "{\"") + offset += WriteToBuffer(buffer[offset:], keys[i]) + offset += WriteToBuffer(buffer[offset:], "\":") + } + } + offset += copy(buffer[offset:], setValue) + for i := len(keys) - 1; i > 0; i-- { + // guard: empty key component — treat as object key, not array index. + if len(keys[i]) > 0 && string(keys[i][0]) == "[" { + offset += WriteToBuffer(buffer[offset:], "]") + } else { + offset += WriteToBuffer(buffer[offset:], "}") + } + } + if isIndex && !comma { + offset += WriteToBuffer(buffer[offset:], "]") + } + if object && !isIndex { + offset += WriteToBuffer(buffer[offset:], "}") + } + return buffer +} + +// SYS-REQ-009, SYS-REQ-111 +func calcAllocateSpace(keys []string, setValue []byte, comma, object bool) int { + // guard: empty key component — not an array index. + isIndex := len(keys[0]) > 0 && string(keys[0][0]) == "[" + lk := 0 + if comma { + // , + lk += 1 + } + if isIndex && !comma { + // [] + lk += 2 + } else { + if object { + // { + lk += 1 + } + if !isIndex { + // "keys[0]" + lk += len(keys[0]) + 3 + } + } + + lk += len(setValue) + for i := 1; i < len(keys); i++ { + // guard: empty key component — treat as object key, not array index. + if len(keys[i]) > 0 && string(keys[i][0]) == "[" { + // [] + lk += 2 + } else { + // {"keys[i]":setValue} + lk += len(keys[i]) + 5 + } + } + + if object && !isIndex { + // } + lk += 1 + } + + return lk +} + +// SYS-REQ-009 +func WriteToBuffer(buffer []byte, str string) int { + copy(buffer, str) + return len(str) +} + +/* + +Del - Receives existing data structure, path to delete. + +Returns: +`data` - return modified data + +*/ +// SYS-REQ-010, SYS-REQ-033, SYS-REQ-034, SYS-REQ-035, SYS-REQ-048, SYS-REQ-049, SYS-REQ-050, SYS-REQ-056 +func Delete(data []byte, keys ...string) []byte { + result, _ := deleteFoundConfig(DefaultConfig, data, keys...) + return result +} + +// DeleteFound removes the value addressed by keys and reports whether the +// value was found and removed. When found is false, result is data unchanged. +// SYS-REQ-010 +func DeleteFound(data []byte, keys ...string) (result []byte, found bool) { + return deleteFoundConfig(DefaultConfig, data, keys...) +} + +// SYS-REQ-115 +func deleteFoundConfig(config Config, data []byte, keys ...string) (result []byte, found bool) { + lk := len(keys) + if lk == 0 { + // Deleting the root produces an empty document whose backing array + // must not alias the caller's input. + return make([]byte, 0), true + } + + array := false + if len(keys[lk-1]) > 0 && string(keys[lk-1][0]) == "[" { + array = true + } + + var startOffset, keyOffset int + endOffset := len(data) + var err error + if !array { + if len(keys) > 1 { + _, _, startOffset, endOffset, err = internalGetConfig(config, data, keys[:lk-1]...) + if err != nil { + // problem parsing the data + return data, false + } + } + + keyOffset, err = findKeyStartConfig(config, data[startOffset:endOffset], keys[lk-1]) + if err == KeyPathNotFoundError { + // problem parsing the data + return data, false + } + keyOffset += startOffset + var subEndOffset int + _, _, _, subEndOffset, err = internalGetConfig(config, data[startOffset:endOffset], keys[lk-1]) + if err != nil { + return data, false + } + endOffset = startOffset + subEndOffset + tokEnd := tokenEnd(data[endOffset:]) + tokStart := findTokenStart(data[:keyOffset], ","[0]) + + if endOffset+tokEnd >= len(data) { + // tokenEnd sentinel: no delimiter found, input is truncated + return data, false + } + + // guard: tokenEnd sentinel may return -1 on truncated input; bounds-check before deref. + idx := endOffset + tokEnd + // Scan forward from idx through any JSON whitespace to find the next + // real token. The original check only matched a single ' ' byte + // before the comma, so inputs like '{"a":1,\n"b":2}' or '[0,0 ,0]' + // (multiple whitespace bytes) bypassed the cleanup and left a + // dangling comma sequence. Found by FuzzPathMutation. + nextTokIdx := idx + for nextTokIdx < len(data) && isJSONWhitespace(data[nextTokIdx]) { + nextTokIdx++ + } + if len(data) > idx && data[idx] == ',' { + endOffset += tokEnd + 1 + } else if len(data) > nextTokIdx && data[nextTokIdx] == ',' { + // Symmetric with the array-branch case below: when the bytes + // after the deleted element are "+," (one or more JSON + // whitespace bytes then a comma), advance endOffset past all + // of them so the trailing comma is removed with the element. + endOffset += nextTokIdx - idx + tokEnd + 1 + } else if len(data) > idx && data[idx] == '}' && data[tokStart] == ',' { + keyOffset = tokStart + } + } else { + _, _, keyOffset, endOffset, err = internalGetConfig(config, data, keys...) + if err != nil { + // problem parsing the data + return data, false + } + + tokEnd := tokenEnd(data[endOffset:]) + tokStart := findTokenStart(data[:keyOffset], ","[0]) + + if endOffset+tokEnd >= len(data) { + // tokenEnd sentinel: no delimiter found, input is truncated + return data, false + } + + // guard: tokenEnd sentinel may return -1 on truncated input; bounds-check before deref. + idx := endOffset + tokEnd + // Scan forward from idx through any JSON whitespace to find the next + // real token (mirrors the object-branch cleanup above). The original + // check only matched a single ' ' byte before the comma, so inputs + // like '[0,0 ,0]' or '[0,0\n\n,0]' bypassed the cleanup. Found by + // FuzzPathMutation. + nextTokIdx := idx + for nextTokIdx < len(data) && isJSONWhitespace(data[nextTokIdx]) { + nextTokIdx++ + } + if len(data) > idx && data[idx] == ',' { + endOffset += tokEnd + 1 + } else if len(data) > nextTokIdx && data[nextTokIdx] == ',' { + // Symmetric with the object-branch case above: when the bytes + // after the deleted element are "+," (one or more JSON + // whitespace bytes then a comma), advance endOffset past all + // of them so the trailing comma is removed with the element. + endOffset += nextTokIdx - idx + tokEnd + 1 + } else if len(data) > idx && data[idx] == ']' && data[tokStart] == ',' { + keyOffset = tokStart + } + } + + // We need to remove remaining trailing comma if we delete last element in the object. + // Extract nextToken once to avoid the redundant double call in the original code. + prevTok := lastToken(data[:keyOffset]) + remainedValue := data[endOffset:] + remainedTok := nextTokenConfig(config, remainedValue) + + var newOffset int + // Cleanup must remove the trailing comma both for objects (close '}') and + // arrays (close ']'). The original check only handled '}', so deleting + // the last array element left a dangling ',]' / ', ]' sequence and + // produced malformed JSON output (found by FuzzPathMutation, + // e.g. Delete("[0,0 ]", "[1]") -> "[0, ]"). The array close is now + // covered symmetrically with the object close. + if prevTok > -1 && remainedTok > -1 && (remainedValue[remainedTok] == '}' || remainedValue[remainedTok] == ']') && data[prevTok] == ',' { + newOffset = prevTok + } else if prevTok > -1 { + newOffset = prevTok + 1 + } else { + newOffset = 0 + } + + // Allocate the exact result size so neither the copy operation nor later + // appends to the returned slice can write into the input backing array. + result = make([]byte, newOffset+len(data)-endOffset) + copy(result, data[:newOffset]) + copy(result[newOffset:], data[endOffset:]) + + return result, true +} + +/* + +Set - Receives existing data structure, path to set, and data to set at that key. + +Returns: +`value` - modified byte array +`err` - On any parsing error + +*/ +// SYS-REQ-009, SYS-REQ-051, SYS-REQ-068, SYS-REQ-069, SYS-REQ-070, SYS-REQ-110 +func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error) { + return setConfig(DefaultConfig, data, setValue, keys...) +} + +// SYS-REQ-115 +func setConfig(config Config, data []byte, setValue []byte, keys ...string) (value []byte, err error) { + // ensure keys are set + if len(keys) == 0 { + return nil, KeyPathNotFoundError + } + + _, _, startOffset, endOffset, err := internalGetConfig(config, data, keys...) + if err != nil { + if err != KeyPathNotFoundError { + // problem parsing the data + return nil, err + } + // full path doesnt exist + // does any subpath exist? + var depth int + for i := range keys { + _, _, start, end, sErr := internalGetConfig(config, data, keys[:i+1]...) + if sErr != nil { + break + } else { + endOffset = end + startOffset = start + depth++ + } + } + comma := true + object := false + // KI-3: when the path's next component expects one container type but + // the existing structure is the other (array-index [N] under an object, + // or an object key under an array), auto-coerce the container to the + // type expected by the path and proceed with fresh insertion. The + // mismatched container is treated as if it needs to be (re)created, so + // the output is always valid JSON. + coerceTopLevel := false + coerceStart := 0 + topLevelArrayAppend := false + topLevelArrayEmpty := false + topLevelArrayStart := 0 + topLevelArrayInsertOffset := 0 + if endOffset == -1 { + firstToken := nextTokenConfig(config, data) + if firstToken < 0 { + return nil, KeyPathNotFoundError + } + pathIsIndex := len(keys[0]) > 0 && keys[0][0] == '[' + // An empty trailing key component is the degenerate "no path + // provided" case (SYS-REQ-111), not a real object key — it must + // keep returning KeyPathNotFoundError on a non-object root, so it + // is excluded from auto-coerce. + pathIsObjectKey := len(keys[0]) > 0 && !pathIsIndex + dataIsObject := data[firstToken] == '{' + dataIsArray := data[firstToken] == '[' + if (pathIsIndex && dataIsObject) || (pathIsObjectKey && dataIsArray) { + // SYS-REQ-009: cross-type Set at the top level — replace the + // mismatched container with a fresh container of the type the + // path expects, then perform a fresh insertion. + coerceTopLevel = true + coerceStart = firstToken + comma = false + object = !pathIsIndex + endOffset = lastToken(data) + } else if pathIsIndex && dataIsArray { + // SYS-REQ-110: a missing index in a top-level array appends at + // the array's end, just as it does for a nested array. + arrayEnd := blockEndConfig(config, data[firstToken:], '[', ']') + if arrayEnd == -1 { + return nil, MalformedArrayError + } + endOffset = firstToken + arrayEnd - 1 + topLevelArrayAppend = true + topLevelArrayStart = firstToken + topLevelArrayInsertOffset = endOffset + + interior := data[firstToken+1 : endOffset] + lastInteriorToken := lastToken(interior) + if lastInteriorToken == -1 { + // createInsertComponent wraps an index component in brackets + // when comma is false, so replace the empty root array. + comma = false + topLevelArrayEmpty = true + } else if interior[lastInteriorToken] == ',' { + // Replace a trailing comma (and any whitespace after it) + // with the normal comma-prefixed append component. + beforeComma := lastToken(interior[:lastInteriorToken]) + if beforeComma == -1 { + comma = false + topLevelArrayEmpty = true + } else { + topLevelArrayInsertOffset = firstToken + 1 + lastInteriorToken + } + } + } else if !dataIsObject { + // Non-container input and the degenerate empty-key-on-non-object + // case are rejected. + return nil, KeyPathNotFoundError + } else { + // Don't need a comma if the input is an empty object + secondToken := firstToken + 1 + nextTokenConfig(config, data[firstToken+1:]) + if data[secondToken] == '}' { + comma = false + } + // Set the top level key at the end (accounting for any trailing whitespace) + // This assumes last token is valid like '}', could check and return error + endOffset = lastToken(data) + } + } + depthOffset := endOffset + if depth != 0 { + trailing := keys[depth:] + pathIsIndex := len(trailing) > 0 && len(trailing[0]) > 0 && trailing[0][0] == '[' + containerIsObject := data[startOffset] == '{' + containerIsArray := data[startOffset] == '[' + if (pathIsIndex && containerIsObject) || (!pathIsIndex && containerIsArray) { + // SYS-REQ-009: cross-type Set under a subpath — replace the + // mismatched container (data[startOffset:depthOffset]) with a + // fresh container of the type the path expects. startOffset and + // depthOffset already bound the existing container, so keep them + // and let createInsertComponent build the replacement. + comma = false + object = !pathIsIndex + } else { + // if subpath is a non-empty object, add to it + // or if subpath is a non-empty array, add to it + // guard: nextToken returns -1 on truncated input; bounds-check the computed offset. + subObjOff := startOffset + 1 + nextTokenConfig(config, data[startOffset+1:]) + // The array-append condition must fire for ANY non-empty array + // (scalar, string, bool, null, nested, or object elements), not + // just arrays whose first element happens to be '{'. The former + // `data[subObjOff] == '{'` check silently destroyed scalar + // arrays on beyond-length Set (SYS-REQ-110 violation: the whole + // array was replaced with a single-element [value]). + if (containerIsObject && subObjOff >= 0 && subObjOff < len(data) && data[subObjOff] != '}') || + (containerIsArray && subObjOff >= 0 && subObjOff < len(data) && data[subObjOff] != ']' && pathIsIndex) { + depthOffset-- + startOffset = depthOffset + // otherwise, over-write it with a new object + } else { + comma = false + object = true + } + } + } else { + if coerceTopLevel { + startOffset = coerceStart + depthOffset = endOffset + 1 + } else if topLevelArrayAppend { + if topLevelArrayEmpty { + startOffset = topLevelArrayStart + depthOffset = endOffset + 1 + } else { + startOffset = topLevelArrayInsertOffset + } + } else { + startOffset = depthOffset + } + } + insertComponent := createInsertComponent(keys[depth:], setValue, comma, object) + value = make([]byte, startOffset+len(insertComponent)+len(data)-depthOffset) + offset := copy(value, data[:startOffset]) + offset += copy(value[offset:], insertComponent) + copy(value[offset:], data[depthOffset:]) + } else { + // path currently exists + startComponent := data[:startOffset] + endComponent := data[endOffset:] + + value = make([]byte, len(startComponent)+len(endComponent)+len(setValue)) + newEndOffset := startOffset + len(setValue) + copy(value[0:startOffset], startComponent) + copy(value[startOffset:newEndOffset], setValue) + copy(value[newEndOffset:], endComponent) + } + return value, nil +} + +// SYS-REQ-001, SYS-REQ-027 +func getType(data []byte, offset int) ([]byte, ValueType, int, error) { + return getTypeConfig(DefaultConfig, data, offset) +} + +// SYS-REQ-115 +func getTypeConfig(config Config, data []byte, offset int) ([]byte, ValueType, int, error) { + var dataType ValueType + endOffset := offset + + // if string value + if data[offset] == '"' || (config.AllowSingleQuotes && data[offset] == '\'') { + dataType = String + if idx, _ := stringEndConfig(config, data[offset+1:], data[offset]); idx != -1 { + endOffset += idx + 1 + } else { + return nil, dataType, offset, MalformedStringError + } + } else if data[offset] == '[' { // if array value + dataType = Array + // break label, for stopping nested loops + endOffset = blockEndConfig(config, data[offset:], '[', ']') + + if endOffset == -1 { + return nil, dataType, offset, MalformedArrayError + } + + endOffset += offset + } else if data[offset] == '{' { // if object value + dataType = Object + // break label, for stopping nested loops + endOffset = blockEndConfig(config, data[offset:], '{', '}') + + if endOffset == -1 { + return nil, dataType, offset, MalformedObjectError + } + + endOffset += offset + } else { + // Number, Boolean or None + // tokenEnd returns len(data) when no delimiter is found, never -1, + // so the old end == -1 guard was dead code and has been removed. + end := tokenEnd(data[endOffset:]) + + value := data[offset : endOffset+end] + + switch data[offset] { + case 't', 'f': // true or false + if bytes.Equal(value, trueLiteral) || bytes.Equal(value, falseLiteral) { + dataType = Boolean + } else { + return nil, Unknown, offset, UnknownValueTypeError + } + case 'u', 'n': // undefined or null + if bytes.Equal(value, nullLiteral) { + dataType = Null + } else { + return nil, Unknown, offset, UnknownValueTypeError + } + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': + dataType = Number + default: + return nil, Unknown, offset, UnknownValueTypeError + } + + endOffset += end + } + return data[offset:endOffset], dataType, endOffset, nil +} + +/* +Get - Receives data structure, and key path to extract value from. + +Returns: +`value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error +`dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null` +`offset` - Offset from provided data structure where key value ends. Used mostly internally, for example for `ArrayEach` helper. +`err` - If key not found or any other parsing issue it should return error. If key not found it also sets `dataType` to `NotExist` + +Accept multiple keys to specify path to JSON value (in case of quering nested structures). +If no keys provided it will try to extract closest JSON value (simple ones or object/array), useful for reading streams or arrays, see `ArrayEach` implementation. +*/ +// SYS-REQ-001, SYS-REQ-016, SYS-REQ-017, SYS-REQ-018, SYS-REQ-019, SYS-REQ-025, SYS-REQ-026, SYS-REQ-041, SYS-REQ-042, SYS-REQ-043 +func Get(data []byte, keys ...string) (value []byte, dataType ValueType, offset int, err error) { + a, b, _, d, e := internalGet(data, keys...) + return a, b, d, e +} + +// SYS-REQ-001 +func internalGet(data []byte, keys ...string) (value []byte, dataType ValueType, offset, endOffset int, err error) { + return internalGetConfig(DefaultConfig, data, keys...) +} + +// SYS-REQ-115 +func internalGetConfig(config Config, data []byte, keys ...string) (value []byte, dataType ValueType, offset, endOffset int, err error) { + if len(keys) > 0 { + if offset = searchKeysConfig(config, data, keys...); offset == -1 { + return nil, NotExist, -1, -1, KeyPathNotFoundError + } + } + + // Go to closest value + nO := nextTokenConfig(config, data[offset:]) + if nO == -1 { + return nil, NotExist, offset, -1, MalformedJsonError + } + + offset += nO + value, dataType, endOffset, err = getTypeConfig(config, data, offset) + if err != nil { + return value, dataType, offset, endOffset, err + } + + // Strip quotes from string values + if dataType == String { + value = value[1 : len(value)-1] + } + + return value[:len(value):len(value)], dataType, offset, endOffset, nil +} + +// SYS-REQ-006, SYS-REQ-028, SYS-REQ-029, SYS-REQ-052, SYS-REQ-053, SYS-REQ-055, SYS-REQ-083 +// ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`. +func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) { + return arrayEachConfig(DefaultConfig, data, cb, keys...) +} + +// SYS-REQ-115 +func arrayEachConfig(config Config, data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error) { + if len(data) == 0 { + return -1, MalformedObjectError + } + + nT := nextTokenConfig(config, data) + if nT == -1 { + return -1, MalformedJsonError + } + + // Guard: when ArrayEach is called without a key path, the addressed + // root value must be an array. Without this guard, the main loop below + // happily parses the first token of a non-array value (e.g. the opening + // key of an object, or a bare number) as if it were an array element, + // invoking the callback once with bogus data before eventually returning + // MalformedArrayError. A caller performing side effects in the callback + // would observe a spurious invocation on input that is not an array at + // all. (SYS-REQ-029 partition: non-array root, no key path.) + // When a key path IS provided, the keys block below already enforces the + // same contract via its own `data[offset] != '['` check after resolving + // the path, so the guard is only needed for the no-keys case. + if len(keys) == 0 && data[nT] != '[' { + return -1, MalformedArrayError + } + + offset = nT + 1 + + if len(keys) > 0 { + if offset = searchKeysConfig(config, data, keys...); offset == -1 { + return offset, KeyPathNotFoundError + } + + // Go to closest value + nO := nextTokenConfig(config, data[offset:]) + if nO == -1 { + return offset, MalformedJsonError + } + + offset += nO + + if data[offset] != '[' { + return offset, MalformedArrayError + } + + offset++ + } + + nO := nextTokenConfig(config, data[offset:]) + if nO == -1 { + return offset, MalformedJsonError + } + + offset += nO + + if data[offset] == ']' { + return offset, nil + } + + for { + v, t, o, e := config.Get(data[offset:]) + + if o == 0 { + // When Get returns endOffset==0, it always means a parse error + // (no valid value found at the current position). The former + // e==nil/break branch was structurally unreachable because Get + // never returns endOffset==0 without an error. + return offset, e + } + + // Pass the error to the callback — the callback signature declares + // an err parameter, so callers who check it should see real errors. + cb(v, t, offset+o-len(v), e) + + if e != nil { + return offset, e + } + + offset += o + + skipToToken := nextTokenConfig(config, data[offset:]) + if skipToToken == -1 { + return offset, MalformedArrayError + } + offset += skipToToken + + if data[offset] == ']' { + break + } + + if data[offset] != ',' { + return offset, MalformedArrayError + } + + offset++ + } + + return offset, nil +} + +// ArrayEachErr is used when iterating arrays and allows the callback to stop +// iteration by returning an error. io.EOF stops iteration without returning an +// error. The returned count includes the element whose callback stopped the +// iteration. +// SYS-REQ-004 +func ArrayEachErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (count int, err error) { + _, count, err = arrayEachErr(data, cb, keys...) + return count, err +} + +// arrayEachErr also returns ArrayEach's closing-bracket offset for use by +// EachKeyErr while traversing array-index paths. +// SYS-REQ-004 +func arrayEachErr(data []byte, cb func(value []byte, dataType ValueType, offset int, err error) error, keys ...string) (offset, count int, err error) { + if len(data) == 0 { + return -1, 0, MalformedObjectError + } + + nT := nextToken(data) + if nT == -1 { + return -1, 0, MalformedJsonError + } + + if len(keys) == 0 && data[nT] != '[' { + return -1, 0, MalformedArrayError + } + + offset = nT + 1 + + if len(keys) > 0 { + if offset = searchKeys(data, keys...); offset == -1 { + return offset, 0, KeyPathNotFoundError + } + + nO := nextToken(data[offset:]) + if nO == -1 { + return offset, 0, MalformedJsonError + } + + offset += nO + + if data[offset] != '[' { + return offset, 0, MalformedArrayError + } + + offset++ + } + + nO := nextToken(data[offset:]) + if nO == -1 { + return offset, 0, MalformedJsonError + } + + offset += nO + + if data[offset] == ']' { + return offset, 0, nil + } + + for { + v, t, o, parseErr := Get(data[offset:]) + + if o == 0 { + return offset, count, parseErr + } + + count++ + if callbackErr := cb(v, t, offset+o-len(v), parseErr); callbackErr != nil { + if errors.Is(callbackErr, io.EOF) { + return offset, count, nil + } + return offset, count, callbackErr + } + + if parseErr != nil { + return offset, count, parseErr + } + + offset += o + + skipToToken := nextToken(data[offset:]) + if skipToToken == -1 { + return offset, count, MalformedArrayError + } + offset += skipToToken + + if data[offset] == ']' { + break + } + + if data[offset] != ',' { + return offset, count, MalformedArrayError + } + + offset++ + } + + return offset, count, nil +} + +// SYS-REQ-007, SYS-REQ-030, SYS-REQ-031, SYS-REQ-032, SYS-REQ-054, SYS-REQ-084 +// ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry +func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) { + return objectEachConfig(DefaultConfig, data, callback, keys...) +} + +// SYS-REQ-115 +func objectEachConfig(config Config, data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error) { + offset := 0 + + // Descend to the desired key, if requested + if len(keys) > 0 { + if off := searchKeysConfig(config, data, keys...); off == -1 { + return KeyPathNotFoundError + } else { + offset = off + } + } + + // Validate and skip past opening brace + if off := nextTokenConfig(config, data[offset:]); off == -1 { + return MalformedObjectError + } else if offset += off; data[offset] != '{' { + return MalformedObjectError + } else { + offset++ + } + + // Skip to the first token inside the object, or stop if we find the ending brace + if off := nextTokenConfig(config, data[offset:]); off == -1 { + return MalformedJsonError + } else if offset += off; data[offset] == '}' { + return nil + } + + // Loop pre-condition: data[offset] points to what should be either the next entry's key, + // or the closing brace (if it's anything else, the JSON is malformed). + // Every iteration either returns or advances offset past a token, so the loop + // always exits via return; the former `offset < len(data)` guard was structurally + // always true because internal nextToken/stringEnd calls return errors before + // offset can reach len(data). + for { + // Step 1: find the next key + var key []byte + + // Check what the the next token is: start of string, end of object, or something else (error) + switch data[offset] { + case '"': + offset++ // accept as string and skip opening quote + case '\'': + if !config.AllowSingleQuotes { + return MalformedObjectError + } + offset++ // accept as string and skip opening quote + case '}': + return nil // we found the end of the object; stop and return success + default: + return MalformedObjectError + } + + // Find the end of the key string + var keyEscaped bool + quote := data[offset-1] + if off, esc := stringEndConfig(config, data[offset:], quote); off == -1 { + return MalformedJsonError + } else { + key, keyEscaped = data[offset:offset+off-1], esc + offset += off + } + + // Unescape the string if needed + if keyEscaped { + var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings + if keyUnescaped, err := unescapeConfig(config, key, stackbuf[:]); err != nil { + return MalformedStringEscapeError + } else { + key = keyUnescaped + } + } + + // Step 2: skip the colon + if off := nextTokenConfig(config, data[offset:]); off == -1 { + return MalformedJsonError + } else if offset += off; data[offset] != ':' { + return MalformedJsonError + } else { + offset++ + } + + // Step 3: find the associated value, then invoke the callback + if value, valueType, off, err := config.Get(data[offset:]); err != nil { + return err + } else if err := callback(key, value, valueType, offset+off); err != nil { // Invoke the callback here! + return err + } else { + offset += off + } + + // Step 4: skip over the next comma to the following token, or stop if we hit the ending brace + if off := nextTokenConfig(config, data[offset:]); off == -1 { + return MalformedArrayError + } else { + offset += off + switch data[offset] { + case '}': + return nil // Stop if we hit the close brace + case ',': + offset++ // Ignore the comma + default: + return MalformedObjectError + } + } + + // Skip to the next token after the comma + if off := nextTokenConfig(config, data[offset:]); off == -1 { + return MalformedArrayError + } else { + offset += off + } + } + + return MalformedObjectError // we shouldn't get here; it's expected that we will return via finding the ending brace +} + +// SYS-REQ-011, SYS-REQ-080, SYS-REQ-081, SYS-REQ-082 +// GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols. +func GetUnsafeString(data []byte, keys ...string) (val string, err error) { + v, _, _, e := Get(data, keys...) + + if e != nil { + return "", e + } + + return bytesToString(&v), nil +} + +// SYS-REQ-002, SYS-REQ-071, SYS-REQ-072, SYS-REQ-073, SYS-REQ-074 +// GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols +// If key data type do not match, it will return an error. +func GetString(data []byte, keys ...string) (val string, err error) { + v, t, _, e := Get(data, keys...) + + if e != nil { + return "", e + } + + if t != String { + if t == Null { + return "", NullValueError + } + return "", fmt.Errorf("Value is not a string: %s", string(v)) + } + + // If no escapes return raw content + if bytes.IndexByte(v, '\\') == -1 { + return string(v), nil + } + + return ParseString(v) +} + +// GetFloat returns the value retrieved by `Get`, cast to a float64 if possible. +// The offset is the same as in `Get`. +// If key data type do not match, it will return an error. +// SYS-REQ-004 +func GetFloat(data []byte, keys ...string) (val float64, err error) { + v, t, _, e := Get(data, keys...) + + if e != nil { + return 0, e + } + + if t != Number { + if t == Null { + return 0, NullValueError + } + return 0, fmt.Errorf("Value is not a number: %s", string(v)) + } + + return ParseFloat(v) +} + +// GetInt returns the value retrieved by `Get`, cast to a int64 if possible. +// If key data type do not match, it will return an error. +// SYS-REQ-003, SYS-REQ-075, SYS-REQ-076, SYS-REQ-077, SYS-REQ-078 +func GetInt(data []byte, keys ...string) (val int64, err error) { + v, t, _, e := Get(data, keys...) + + if e != nil { + return 0, e + } + + if t != Number { + if t == Null { + return 0, NullValueError + } + return 0, fmt.Errorf("Value is not a number: %s", string(v)) + } + + return ParseInt(v) +} + +// GetBoolean returns the value retrieved by `Get`, cast to a bool if possible. +// The offset is the same as in `Get`. +// If key data type do not match, it will return error. +// SYS-REQ-005, SYS-REQ-079 +func GetBoolean(data []byte, keys ...string) (val bool, err error) { + v, t, _, e := Get(data, keys...) + + if e != nil { + return false, e + } + + if t != Boolean { + if t == Null { + return false, NullValueError + } + return false, fmt.Errorf("Value is not a boolean: %s", string(v)) + } + + return ParseBoolean(v) +} + +// ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness) +// SYS-REQ-012, SYS-REQ-036, SYS-REQ-057, SYS-REQ-066 +func ParseBoolean(b []byte) (bool, error) { + switch { + case bytes.Equal(b, trueLiteral): + return true, nil + case bytes.Equal(b, falseLiteral): + return false, nil + default: + return false, MalformedValueError + } +} + +// ParseString parses a String ValueType into a Go string (the main parsing work is unescaping the JSON string) +// SYS-REQ-014, SYS-REQ-038, SYS-REQ-060, SYS-REQ-063, SYS-REQ-067 +func ParseString(b []byte) (string, error) { + var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings + if bU, err := Unescape(b, stackbuf[:]); err != nil { + return "", MalformedValueError + } else { + return string(bU), nil + } +} + +// ParseNumber parses a Number ValueType into a Go float64 +// SYS-REQ-013, SYS-REQ-037, SYS-REQ-065 +func ParseFloat(b []byte) (float64, error) { + if v, err := parseFloat(&b); err != nil { + return 0, MalformedValueError + } else { + return v, nil + } +} + +// ParseInt parses a Number ValueType into a Go int64 +// SYS-REQ-015, SYS-REQ-039, SYS-REQ-040, SYS-REQ-058, SYS-REQ-059, SYS-REQ-064 +func ParseInt(b []byte) (int64, error) { + if v, ok, overflow := parseInt(b); !ok { + if overflow { + return 0, OverflowIntegerError + } + return 0, MalformedValueError + } else { + return v, nil + } +} + +// GetArrayLen returns the number of elements in the addressed JSON array. +// It scans the array without invoking a callback. +// SYS-REQ-112 +func GetArrayLen(data []byte, keys ...string) (int, error) { + offset, err := containerStart(data, '[', keys...) + if err != nil { + return 0, err + } + + return scanContainerLen(data, offset, '[') +} + +// GetObjectLen returns the number of key-value pairs in the addressed JSON +// object. It scans the object without invoking a callback. +// SYS-REQ-112 +func GetObjectLen(data []byte, keys ...string) (int, error) { + offset, err := containerStart(data, '{', keys...) + if err != nil { + return 0, err + } + + return scanContainerLen(data, offset, '{') +} + +// GetUint64 returns the value retrieved by internalGet, cast to a uint64 if +// possible. Negative values and malformed integers return MalformedValueError; +// values larger than uint64 return OverflowIntegerError. +// SYS-REQ-003 +func GetUint64(data []byte, keys ...string) (uint64, error) { + v, t, _, _, err := internalGet(data, keys...) + if err != nil { + return 0, err + } + + if t != Number { + if t == Null { + return 0, NullValueError + } + return 0, fmt.Errorf("Value is not a number: %s", string(v)) + } + + if n, ok, _ := parseInt(v); ok { + if n < 0 { + return 0, MalformedValueError + } + return uint64(n), nil + } + + n, parseErr := strconv.ParseUint(string(v), 10, 64) + if parseErr == nil { + return n, nil + } + + var numErr *strconv.NumError + if errors.As(parseErr, &numErr) && numErr.Err == strconv.ErrRange { + return 0, OverflowIntegerError + } + return 0, MalformedValueError +} + +// SYS-REQ-112 +func containerStart(data []byte, open byte, keys ...string) (int, error) { + offset := 0 + if len(keys) > 0 { + offset = searchKeys(data, keys...) + if offset == -1 { + return -1, KeyPathNotFoundError + } + } + + tokenOffset := nextToken(data[offset:]) + if tokenOffset == -1 { + return -1, KeyPathNotFoundError + } + offset += tokenOffset + + if data[offset] != open { + return -1, KeyPathNotFoundError + } + return offset, nil +} + +// SYS-REQ-112 +func scanContainerLen(data []byte, offset int, open byte) (int, error) { + const ( + scanArrayValue = iota + scanArrayPrimitive + scanArrayDelimiter + scanObjectKey + scanObjectColon + scanObjectValue + scanObjectPrimitive + scanObjectDelimiter + ) + + close := byte(']') + malformedErr := MalformedArrayError + state := scanArrayValue + if open == '{' { + close = '}' + malformedErr = MalformedObjectError + state = scanObjectKey + } + + var fixedStack [32]byte + stack := fixedStack[:1] + stack[0] = close + + count := 0 + primitiveStart := -1 + + for i := offset + 1; i < len(data); i++ { + c := data[i] + + // Only delimiters at the addressed container's top level affect its + // length. Strings and nested containers are skipped structurally. + if len(stack) > 1 { + switch c { + case '"': + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + case '[': + stack = append(stack, ']') + case '{': + stack = append(stack, '}') + case ']', '}': + if c != stack[len(stack)-1] { + return 0, malformedErr + } + stack = stack[:len(stack)-1] + } + continue + } + + switch state { + case scanArrayValue: + if isContainerWhitespace(c) { + continue + } + if c == close { + if count == 0 { + return 0, nil + } + return 0, malformedErr + } + if c == ',' || c == '}' || c == ':' { + return 0, malformedErr + } + + count++ + switch c { + case '"': + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + state = scanArrayDelimiter + case '[': + stack = append(stack, ']') + state = scanArrayDelimiter + case '{': + stack = append(stack, '}') + state = scanArrayDelimiter + default: + primitiveStart = i + state = scanArrayPrimitive + } + + case scanArrayPrimitive: + switch c { + case ',': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + state = scanArrayValue + case ']': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + return count, nil + case '}': + return 0, malformedErr + } + + case scanArrayDelimiter: + if isContainerWhitespace(c) { + continue + } + switch c { + case ',': + state = scanArrayValue + case ']': + return count, nil + default: + return 0, malformedErr + } + + case scanObjectKey: + if isContainerWhitespace(c) { + continue + } + if c == close { + if count == 0 { + return 0, nil + } + return 0, malformedErr + } + if c != '"' { + return 0, malformedErr + } + + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + state = scanObjectColon + + case scanObjectColon: + if isContainerWhitespace(c) { + continue + } + if c != ':' { + return 0, malformedErr + } + state = scanObjectValue + + case scanObjectValue: + if isContainerWhitespace(c) { + continue + } + if c == ',' || c == '}' || c == ']' || c == ':' { + return 0, malformedErr + } + + count++ + switch c { + case '"': + stringLength, _ := stringEnd(data[i+1:]) + if stringLength == -1 { + return 0, malformedErr + } + i += stringLength + state = scanObjectDelimiter + case '[': + stack = append(stack, ']') + state = scanObjectDelimiter + case '{': + stack = append(stack, '}') + state = scanObjectDelimiter + default: + primitiveStart = i + state = scanObjectPrimitive + } + + case scanObjectPrimitive: + switch c { + case ',': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + state = scanObjectKey + case '}': + if !validContainerPrimitive(data[primitiveStart:i]) { + return 0, malformedErr + } + return count, nil + case ']': + return 0, malformedErr + } + + case scanObjectDelimiter: + if isContainerWhitespace(c) { + continue + } + switch c { + case ',': + state = scanObjectKey + case '}': + return count, nil + default: + return 0, malformedErr + } + } + } + + return 0, malformedErr +} + +// SYS-REQ-112 +func isContainerWhitespace(c byte) bool { + return c == ' ' || c == '\n' || c == '\r' || c == '\t' +} + +// SYS-REQ-112 +func validContainerPrimitive(value []byte) bool { + for len(value) > 0 && isContainerWhitespace(value[len(value)-1]) { + value = value[:len(value)-1] + } + if len(value) == 0 { + return false + } + + if bytes.Equal(value, trueLiteral) || bytes.Equal(value, falseLiteral) || bytes.Equal(value, nullLiteral) { + return true + } + return validJSONNumber(value) +} + +// SYS-REQ-112 +func validJSONNumber(value []byte) bool { + i := 0 + if value[i] == '-' { + i++ + if i == len(value) { + return false + } + } + + if value[i] == '0' { + i++ + if i < len(value) && value[i] >= '0' && value[i] <= '9' { + return false + } + } else { + if value[i] < '1' || value[i] > '9' { + return false + } + for i < len(value) && value[i] >= '0' && value[i] <= '9' { + i++ + } + } + + if i < len(value) && value[i] == '.' { + i++ + start := i + for i < len(value) && value[i] >= '0' && value[i] <= '9' { + i++ + } + if i == start { + return false + } + } + + if i < len(value) && (value[i] == 'e' || value[i] == 'E') { + i++ + if i < len(value) && (value[i] == '+' || value[i] == '-') { + i++ + } + start := i + for i < len(value) && value[i] >= '0' && value[i] <= '9' { + i++ + } + if i == start { + return false + } + } + + return i == len(value) +} diff --git a/vendor/github.com/buger/jsonparser/path_compiler.go b/vendor/github.com/buger/jsonparser/path_compiler.go new file mode 100644 index 0000000..b044e7e --- /dev/null +++ b/vendor/github.com/buger/jsonparser/path_compiler.go @@ -0,0 +1,226 @@ +package jsonparser + +import ( + "errors" + "strings" +) + +var ( + errEmptyPath = errors.New("jsonparser: path must not be empty") + errMalformedPath = errors.New("jsonparser: malformed path") + errUnterminatedKey = errors.New("jsonparser: unterminated quoted key") +) + +// ParsePath converts a JSONPath-style path into the path components accepted +// by Get, Set, Delete, ArrayEach, and EachKey. +// SYS-REQ-114 +func ParsePath(jsonPath string) ([]string, error) { + if jsonPath == "" { + return nil, errEmptyPath + } + + switch { + case jsonPath == "$": + return []string{}, nil + case strings.HasPrefix(jsonPath, "$."): + jsonPath = jsonPath[2:] + case strings.HasPrefix(jsonPath, "$["): + jsonPath = jsonPath[1:] + case jsonPath[0] == '$': + return nil, errMalformedPath + } + + if jsonPath == "" { + return nil, errMalformedPath + } + + // A path component is either a dot-delimited key or bracket notation. + // Counting both separators gives an exact capacity for ordinary paths and + // a safe upper bound for quoted keys containing dots or brackets. + parts := make([]string, 0, 1+strings.Count(jsonPath, ".")+strings.Count(jsonPath, "[")) + + for pos := 0; pos < len(jsonPath); { + switch jsonPath[pos] { + case '.': + return nil, errMalformedPath + case '"': + key, next, err := parseQuotedPathKey(jsonPath, pos) + if err != nil { + return nil, err + } + parts = append(parts, key) + pos = next + case '[': + // A root array path or a bracket immediately following a dot has + // no key component before its index. + default: + start := pos + for pos < len(jsonPath) && jsonPath[pos] != '.' && jsonPath[pos] != '[' { + if jsonPath[pos] == ']' || jsonPath[pos] == '"' { + return nil, errMalformedPath + } + pos++ + } + if start == pos { + return nil, errMalformedPath + } + parts = append(parts, jsonPath[start:pos]) + } + + for pos < len(jsonPath) && jsonPath[pos] == '[' { + component, next, err := parseBracketPathComponent(jsonPath, pos) + if err != nil { + return nil, err + } + parts = append(parts, component) + pos = next + } + + if pos == len(jsonPath) { + break + } + if jsonPath[pos] != '.' { + return nil, errMalformedPath + } + + pos++ + if pos == len(jsonPath) { + return nil, errMalformedPath + } + } + + if len(parts) == 0 { + return nil, errMalformedPath + } + return parts, nil +} + +// SYS-REQ-114 +func parseQuotedPathKey(path string, start int) (string, int, error) { + contentStart := start + 1 + for pos := contentStart; pos < len(path); pos++ { + switch path[pos] { + case '\\': + // Skip the escaped byte while locating the closing quote. Unescape + // below performs complete JSON escape validation. + pos++ + if pos >= len(path) { + return "", 0, errUnterminatedKey + } + case '"': + content := path[contentStart:pos] + if strings.IndexByte(content, '\\') == -1 { + return content, pos + 1, nil + } + + unescaped, err := Unescape([]byte(content), nil) + if err != nil { + return "", 0, errMalformedPath + } + return string(unescaped), pos + 1, nil + default: + if path[pos] < 0x20 { + return "", 0, errMalformedPath + } + } + } + + return "", 0, errUnterminatedKey +} + +// SYS-REQ-114 +func parseBracketPathComponent(path string, start int) (string, int, error) { + end := start + 1 + for end < len(path) && path[end] != ']' { + if path[end] == '[' || path[end] == '"' { + return "", 0, errMalformedPath + } + end++ + } + if end == len(path) || end == start+1 { + return "", 0, errMalformedPath + } + + if path[start+1] == '*' { + if end != start+2 { + return "", 0, errMalformedPath + } + } else { + for pos := start + 1; pos < end; pos++ { + if path[pos] < '0' || path[pos] > '9' { + return "", 0, errMalformedPath + } + } + } + + return path[start : end+1], end + 1, nil +} + +// CompiledPath stores a parsed path for repeated operations. +// SYS-REQ-114 +type CompiledPath struct { + parts []string +} + +// CompilePath parses jsonPath once for reuse. +// SYS-REQ-114 +func CompilePath(jsonPath string) (CompiledPath, error) { + parts, err := ParsePath(jsonPath) + if err != nil { + return CompiledPath{}, err + } + return CompiledPath{parts: parts}, nil +} + +// Get resolves the compiled path in data. +// Verifies: SYS-REQ-001 (Get) +// SYS-REQ-114 +func (c CompiledPath) Get(data []byte) ([]byte, ValueType, int, error) { + return Get(data, c.parts...) +} + +// GetString resolves the compiled path and returns its string value. +// SYS-REQ-114 +func (c CompiledPath) GetString(data []byte) (string, error) { + return GetString(data, c.parts...) +} + +// GetInt resolves the compiled path and returns its integer value. +// SYS-REQ-114 +func (c CompiledPath) GetInt(data []byte) (int64, error) { + return GetInt(data, c.parts...) +} + +// Set writes value at the compiled path. +// Verifies: SYS-REQ-009 (Set) +// SYS-REQ-114 +func (c CompiledPath) Set(data []byte, value []byte) ([]byte, error) { + return Set(data, value, c.parts...) +} + +// Delete removes the value at the compiled path. +// SYS-REQ-114 +func (c CompiledPath) Delete(data []byte) []byte { + return Delete(data, c.parts...) +} + +// ArrayEach iterates over the array at the compiled path. +// SYS-REQ-114 +func (c CompiledPath) ArrayEach(data []byte, cb func([]byte, ValueType, int, error)) (int, error) { + return ArrayEach(data, cb, c.parts...) +} + +// EachKey resolves the compiled path using EachKey. +// SYS-REQ-114 +func (c CompiledPath) EachKey(data []byte, cb func(int, []byte, ValueType, error)) error { + EachKey(data, cb, c.parts) + return nil +} + +// Parts returns a copy of the compiled path components. +// SYS-REQ-114 +func (c CompiledPath) Parts() []string { + parts := make([]string, len(c.parts)) + copy(parts, c.parts) + return parts +} diff --git a/vendor/github.com/buger/jsonparser/proof.yaml b/vendor/github.com/buger/jsonparser/proof.yaml new file mode 100644 index 0000000..f15efe7 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/proof.yaml @@ -0,0 +1,252 @@ +project: + name: jsonparser + # High-assurance posture: the library is a pure function over untrusted, + # adversarial byte input (fuzz targets, OSS-Fuzz). L3 is the strict + # non-trivial level that obligates formalization, coverage, and hazard + # review rather than informal inspection alone. + assurance_target: L3 + specs: + - path: specs/stakeholder + prefix: STK-REQ + type: stakeholder + - path: specs/system + prefix: SYS-REQ + type: system + parent_spec: specs/stakeholder + obligation_classes: + - nominal + - missing_path + - malformed_input + - truncated_at_value_boundary + - truncated_mid_structure + - truncated_mid_key + - empty_input + - boundary + - type_mismatch + - negative_array_index + - sentinel_value_boundary + - error_propagation + - no_path_provided + - nested_mutation + - callback_error_propagation + - truncated_escape_sequence + - partial_literal + - truncated_mid_element + - determinism + - idempotency + - nil_safety + - encoding_safety + - edge_case + - no_input_mutation + - api_consistency + - element_type_partition + - non_array_root_no_callback + commands: + build: go build ./... + # Standard audit test command: runs unit + MC/DC witness tests but + # SKIPS the heavy iteration-count suites (property-based, reference- + # oracle, fuzz-harness coverage) so `proof audit` stays fast on every + # PR. Those suites run via `make test-full` (see Makefile) in the + # dedicated CI "Fuzzing" job. Go's -skip flag (1.20+) accepts a regex; + # Fuzz* functions only run under -fuzz anyway. + test: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1 + # Named per-language test commands consumed by code_mcdc (the MC/DC + # engine needs a discoverable go test command it can instrument and + # rerun, then collect fingerprints). Mirrors the reqforge schema. + tests: + go: + language: go + command: mkdir -p .proof/coverage .proof/test-results && go test ./... -count=1 -skip='TestProperty|TestOracle|TestFuzz.*Harness' -coverprofile=.proof/coverage/unit.coverprofile -json > .proof/test-results/go-test.json 2>&1 + # Instrumented execution path used only when the code-level + # MC/DC engine reruns tests in its temp workspace (cwd = + # /module). The engine does NOT inject -coverprofile or + # -count into a user-provided command, so this must write the + # managed cover artifact itself: ../cover.out resolves to the + # workspace root the engine reads. -json is redirected back to + # the source workspace via REQPROOF_MCDC_ORIGINAL_SOURCE_DIR so + # test_results auto_link sees a fresh report. The ordinary + # `command` above still feeds coverage_threshold / test_results + # for the non-MC/DC path; -race still comes from test_args. + mcdc_command: go test ./... -coverprofile=../cover.out -json > "$REQPROOF_MCDC_ORIGINAL_SOURCE_DIR/.proof/test-results/go-test.json" 2>&1 + # Fixtures are generated artifacts, not committed to the repo. + # MC/DC coverage is enforced through test annotations instead. + # To regenerate locally: + # proof testgen specs/system parser --output tests/ + # proof proptest specs/system parser --source z3 --output tests/parser/ + # + # Code signals — project-local OpenGrep rule packs. + # + # The jsonparser.boundary.unchecked-caller-slice-deref rule closes the + # gap exposed by the 8th empty-key panic site (parser.go:1000): the + # prior hazard sweep matched only `identifier[index][0]` and missed the + # slice-expression variant `keys[depth:][0][0]`. The rule treats + # slice-expression-then-index, direct-index-then-field, nested direct + # index, computed-offset byte-slice index, and path-segment index as + # the SAME hazard class, while excluding `len(X) > N && ...` / + # `if len(X) > N { ... }` guarded sites and bounded `for i := range` + # loops. Findings map to the boundary obligation class (already owned + # by the parser requirement family) so each one opens a real review + # item. The semantically precise class is panic_free_input_handling; + # adopting it project-wide is the right follow-up — see the rule file + # header for the migration note. + # + # Local dev / CI install of the analyzer backend: + # npm install -g @opengrep/cli@1.22.0 + # `tools.opengrep.auto_download: true` below also fetches the pinned + # version on the first `proof signals collect --provider opengrep`. + signals: + output_dir: proof/signals + # Keep audit refresh explicit so a missing analyzer in CI does not + # turn into a spurious red. Run `proof signals collect --provider + # opengrep` before merge / locally to refresh findings; the audit + # check consumes whatever cache that command writes. + refresh_on_audit: false + defaults: auto + rule_packs: + - proof/signals/rules/unchecked-caller-slice-deref.yaml + providers: + opengrep: + enabled: true + mode: run + command: + - opengrep + - scan + - '{configs}' + - --sarif + - --quiet + - --no-rewrite-rule-ids + - '{include_paths}' + format: sarif + include_paths: + - parser.go + - bytes.go + - bytes_safe.go + - bytes_unsafe.go + - escape.go + - fuzz.go + exclude_paths: + - '*_test.go' + - benchmark/** + # `go.parameter-boundary.degenerate` anchors the + # parameter_boundary_safe catalog class, DEFINED as a + # Solidity-style governance / operator setter whose value + # is later consumed in slippage / throttle / timelock + # arithmetic or truncated by a narrowing cast. This + # project is a pure-function Go JSON parser library: the + # only "setters" it exposes are top-level exported + # functions taking byte slices, none consumed in + # protection arithmetic and none cast to a narrower type. + # The class's applies_when is never satisfied here, so + # the project can neither satisfy nor violate it. The + # honest record is "rule does not apply", not "83 + # requirement-owners each adjudicated and excused the + # same site". Rule entries use the ProviderRuleID form + # (hyphenated), matching how reqforge disables the same + # rule for the same reason. + disabled_rules: + - go.parameter-boundary.degenerate + fail_if_missing: false + timeout_seconds: 120 + tools: + opengrep: + version: 1.22.0 + auto_download: true + checks: + solver_latency_clean: + threshold: 360 + coverage_threshold: + threshold: 80 + auto_link: false + report_path: .proof/coverage/unit.coverprofile + format: go-cover + test_results: + auto_link: true + report_path: .proof/test-results/go-test.json + slow_tests: + enabled: true + threshold_seconds: 60 + max_allowed: 5 + code_mcdc: + severity: warn + languages: + go: + test_args: + - -race + min_decision_percent: 100 + min_condition_percent: 100 + max_incomplete_decisions: 0 + targets: + - id: parser + enabled: true + language: go + scope: ./... + mcdc_coverage: {} + proof_complexity_clean: + max_formalized_requirements: 120 + max_variables: 280 + max_guarantees: 120 + evidence_diversity: + min_classes: + A: 3 + B: 2 + C: 1 + # Worst-case-first hazard coverage gate (hazard-sweep role precondition). + # `all` is stricter than proof's built-in default `security`: every + # in-scope obligation class must carry an enumerated worst_case, so a + # missing worst-case surfaces as a finding instead of a silent gap. + hazard_consequence: + require_worst_case_scope: all + # Keep every remaining check enabled so the audit surface is fully + # honest (no silently-disabled gates). Each was verified PASS on this + # project; keeping them on catches regressions. + change_evidence_complete: + enabled: true + code_signal_obligations_reviewed: + enabled: true + code_signal_unbindable: + enabled: true + description_grammar_enumeration_complete: + enabled: true + no_authored_change_surface_reviewed: + enabled: true + property_fixtures_exist: + enabled: true + flip_fixtures_exist: + enabled: false + fixture_staleness_clean: + enabled: true + signal_fixtures_valid: + enabled: true + property_based_test_coverage: + enabled: true + approval: + required_for: + assurance_levels: + - A + - B + roles: + - system_owner + - lead_engineer + comment_required: true + # Agent-driven review posture (mirrors reqforge self-dogfood): an AI + # agent driving this repo may run `proof approve` at any assurance + # level so the spec/hazard review loops can close autonomously. Set + # `all: false` and enumerate levels to re-human-gate. + agent_autonomous_for: + all: true + audit: + # CI runs `proof audit --fail-level warn --scope full`; pinning the + # same posture in config makes local runs match CI exactly. + fail_level: warn + scope: full + invocation_log: + enabled: true + path: .proof/invocations.jsonl + documentation: + sources: + - path: . + type: auto + threshold: 0 + verification_scope: + exclude: null + include: null diff --git a/vendor/github.com/buger/jsonparser/reader_parser.go b/vendor/github.com/buger/jsonparser/reader_parser.go new file mode 100644 index 0000000..368d2b2 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/reader_parser.go @@ -0,0 +1,696 @@ +package jsonparser + +import ( + "bytes" + "io" + "strconv" +) + +const ( + defaultReaderBufferSize = 64 * 1024 + defaultReaderMaxBufferSize = 64 * 1024 * 1024 + maxConsecutiveEmptyReads = 100 +) + +// ReaderParser provides path-based access to a JSON stream. It is intended for +// one operation per stream: call Get, GetString, or ArrayEach after creating +// the parser. ReaderParser is not safe for concurrent use. +// +// The sliding window is bounded by Config.MaxBufferSize while skipping input. +// A returned value (or one ArrayEach element) may exceed that size because its +// complete byte slice must remain available to the caller. +// SYS-REQ-116 +type ReaderParser struct { + reader io.Reader + buf []byte + bufStart int64 + pos int + config Config + + readErr error + emptyReads int +} + +// NewReaderParser creates a streaming parser. If opts contains a Config, the +// first Config controls lenient parsing and the sliding-window size. +// SYS-REQ-116 +func NewReaderParser(r io.Reader, opts ...Config) *ReaderParser { + config := DefaultConfig + if len(opts) > 0 { + config = opts[0] + } + return &ReaderParser{ + reader: r, + config: config, + } +} + +// Get returns the value addressed by keys without loading the whole document. +// As with the package-level Get, string values are returned without quotes but +// retain their JSON escapes. +// SYS-REQ-116 +func (rp *ReaderParser) Get(keys ...string) (value []byte, vt ValueType, err error) { + for _, key := range keys { + if key == "" { + return nil, NotExist, KeyPathNotFoundError + } + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return nil, NotExist, KeyPathNotFoundError + } + return nil, NotExist, err + } + + var raw []byte + if len(keys) == 0 { + raw, err = rp.captureValue() + } else { + var found bool + found, raw, err = rp.findValue(keys, 0) + if err == nil && !found { + err = KeyPathNotFoundError + } + } + if err != nil { + return nil, NotExist, err + } + + value, vt, _, err = rp.config.Get(raw) + if err != nil { + return value, vt, err + } + return value, vt, nil +} + +// GetString returns and decodes the string addressed by keys. +// SYS-REQ-116 +func (rp *ReaderParser) GetString(keys ...string) (string, error) { + value, vt, err := rp.Get(keys...) + if err != nil { + return "", err + } + if vt != String { + if vt == Null { + return "", NullValueError + } + return "", valueTypeError("string", value) + } + if bytes.IndexByte(value, '\\') == -1 { + return string(value), nil + } + + var stackbuf [unescapeStackBufSize]byte + unescaped, err := unescapeConfig(rp.config, value, stackbuf[:]) + if err != nil { + return "", MalformedValueError + } + return string(unescaped), nil +} + +// ArrayEach incrementally iterates a root JSON array. Callback value slices are +// valid for the duration of the callback and must be copied if retained. +// Memory use is bounded by the largest element plus the sliding read window. +// SYS-REQ-116 +func (rp *ReaderParser) ArrayEach(cb func(value []byte, vt ValueType, err error)) error { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedObjectError + } + return err + } + + b, err := rp.peekByte(false) + if err != nil { + return err + } + if b != '[' { + return MalformedArrayError + } + rp.pos++ + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedArrayError + } + return err + } + b, err = rp.peekByte(false) + if err != nil { + return err + } + if b == ']' { + rp.pos++ + return nil + } + + for { + raw, captureErr := rp.captureValue() + if captureErr != nil { + cb(nil, Unknown, captureErr) + return captureErr + } + + value, vt, _, valueErr := rp.config.Get(raw) + cb(value, vt, valueErr) + if valueErr != nil { + return valueErr + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedArrayError + } + return err + } + b, err = rp.peekByte(false) + if err != nil { + return err + } + switch b { + case ']': + rp.pos++ + return nil + case ',': + rp.pos++ + default: + return MalformedArrayError + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return MalformedArrayError + } + return err + } + b, err = rp.peekByte(false) + if err != nil { + return err + } + if b == ']' { + return MalformedArrayError + } + } +} + +// findValue resolves keys[depth:] against the value at rp.pos. A not-found +// result consumes the current value so a containing object can continue past a +// duplicate key. A found result leaves the final value in the sliding buffer. +// SYS-REQ-116 +func (rp *ReaderParser) findValue(keys []string, depth int) (bool, []byte, error) { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedJsonError + } + return false, nil, err + } + if depth == len(keys) { + raw, err := rp.captureValue() + return err == nil, raw, err + } + + b, err := rp.peekByte(false) + if err != nil { + return false, nil, err + } + switch b { + case '{': + return rp.findObjectValue(keys, depth) + case '[': + return rp.findArrayValue(keys, depth) + default: + if err := rp.skipValue(); err != nil { + return false, nil, err + } + return false, nil, nil + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) findObjectValue(keys []string, depth int) (bool, []byte, error) { + rp.pos++ // opening { + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedObjectError + } + return false, nil, err + } + b, err := rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == '}' { + rp.pos++ + return false, nil, nil + } + + for { + matches, err := rp.readObjectKey(keys[depth]) + if err != nil { + return false, nil, err + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedJsonError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b != ':' { + return false, nil, MalformedJsonError + } + rp.pos++ + + if matches { + found, raw, err := rp.findValue(keys, depth+1) + if err != nil || found { + return found, raw, err + } + } else { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedJsonError + } + return false, nil, err + } + if err := rp.skipValue(); err != nil { + return false, nil, err + } + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedObjectError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + switch b { + case '}': + rp.pos++ + return false, nil, nil + case ',': + rp.pos++ + default: + return false, nil, MalformedObjectError + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedObjectError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == '}' { + return false, nil, MalformedObjectError + } + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) findArrayValue(keys []string, depth int) (bool, []byte, error) { + wanted, ok := parseReaderArrayIndex(keys[depth]) + if !ok { + if err := rp.skipValue(); err != nil { + return false, nil, err + } + return false, nil, nil + } + + rp.pos++ // opening [ + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedArrayError + } + return false, nil, err + } + b, err := rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == ']' { + rp.pos++ + return false, nil, nil + } + + for index := 0; ; index++ { + if index == wanted { + found, raw, err := rp.findValue(keys, depth+1) + if err != nil || found { + return found, raw, err + } + } else { + if err := rp.skipValue(); err != nil { + return false, nil, err + } + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedArrayError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + switch b { + case ']': + rp.pos++ + return false, nil, nil + case ',': + rp.pos++ + default: + return false, nil, MalformedArrayError + } + + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return false, nil, MalformedArrayError + } + return false, nil, err + } + b, err = rp.peekByte(false) + if err != nil { + return false, nil, err + } + if b == ']' { + return false, nil, MalformedArrayError + } + } +} + +// SYS-REQ-116 +func parseReaderArrayIndex(key string) (int, bool) { + if len(key) < 3 || key[0] != '[' || key[len(key)-1] != ']' { + return 0, false + } + index, err := strconv.Atoi(key[1 : len(key)-1]) + return index, err == nil && index >= 0 +} + +// SYS-REQ-116 +func (rp *ReaderParser) readObjectKey(wanted string) (bool, error) { + b, err := rp.peekByte(false) + if err != nil { + return false, err + } + if b != '"' && !(b == '\'' && rp.config.AllowSingleQuotes) { + return false, MalformedJsonError + } + + // The parent prefix is no longer needed. Discarding it before retaining the + // key ensures that an arbitrarily late key does not grow the window. + rp.discardConsumed() + start := rp.pos + if err := rp.scanString(true); err != nil { + return false, err + } + token := rp.buf[start:rp.pos] + body := token[1 : len(token)-1] + if bytes.IndexByte(body, '\\') == -1 { + return string(body) == wanted, nil + } + + var stackbuf [unescapeStackBufSize]byte + unescaped, err := unescapeConfig(rp.config, body, stackbuf[:]) + if err != nil { + return false, err + } + return string(unescaped) == wanted, nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) captureValue() ([]byte, error) { + if err := rp.skipWhitespace(); err != nil { + if err == io.EOF { + return nil, MalformedJsonError + } + return nil, err + } + + // Retain only this value and any already-read suffix. The suffix is at most + // one read chunk; prefixes consumed while locating the value are released. + rp.discardConsumed() + start := rp.pos + if err := rp.scanValue(true); err != nil { + return nil, err + } + return rp.buf[start:rp.pos], nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) skipValue() error { + return rp.scanValue(false) +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanValue(retain bool) error { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF { + return MalformedJsonError + } + return err + } + + switch { + case b == '"' || (b == '\'' && rp.config.AllowSingleQuotes): + return rp.scanString(retain) + case b == '[' || b == '{': + return rp.scanComposite(retain, b) + default: + return rp.scanScalar(retain) + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanString(retain bool) error { + quote, err := rp.peekByte(retain) + if err != nil { + return err + } + rp.pos++ + escaped := false + + for { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF { + return MalformedStringError + } + return err + } + rp.pos++ + + if escaped { + escaped = false + continue + } + if b == '\\' { + escaped = true + continue + } + if b == quote { + return nil + } + } +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanComposite(retain bool, opening byte) error { + stack := []byte{closingDelimiter(opening)} + rp.pos++ + + for len(stack) > 0 { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF { + if opening == '[' { + return MalformedArrayError + } + return MalformedObjectError + } + return err + } + + if b == '"' || (b == '\'' && rp.config.AllowSingleQuotes) { + if err := rp.scanString(retain); err != nil { + return err + } + continue + } + + switch b { + case '{': + stack = append(stack, '}') + case '[': + stack = append(stack, ']') + case '}', ']': + if b != stack[len(stack)-1] { + return MalformedJsonError + } + stack = stack[:len(stack)-1] + } + rp.pos++ + } + return nil +} + +// SYS-REQ-116 +func closingDelimiter(opening byte) byte { + if opening == '[' { + return ']' + } + return '}' +} + +// SYS-REQ-116 +func (rp *ReaderParser) scanScalar(retain bool) error { + consumed := false + for { + b, err := rp.peekByte(retain) + if err != nil { + if err == io.EOF && consumed { + return nil + } + if err == io.EOF { + return MalformedJsonError + } + return err + } + if isReaderValueDelimiter(b) { + if !consumed { + return MalformedJsonError + } + return nil + } + consumed = true + rp.pos++ + } +} + +// SYS-REQ-116 +func isReaderValueDelimiter(b byte) bool { + return isJSONWhitespace(b) || b == ',' || b == '}' || b == ']' +} + +// SYS-REQ-116 +func (rp *ReaderParser) skipWhitespace() error { + for { + b, err := rp.peekByte(false) + if err != nil { + return err + } + if !isJSONWhitespace(b) { + return nil + } + rp.pos++ + } +} + +// peekByte returns the next byte. When retain is false, fully consumed chunks +// are discarded before reading more data. +// SYS-REQ-116 +func (rp *ReaderParser) peekByte(retain bool) (byte, error) { + for rp.pos >= len(rp.buf) { + if !retain { + rp.discardConsumed() + } + if err := rp.readMore(); err != nil { + return 0, err + } + } + return rp.buf[rp.pos], nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) readMore() error { + if rp.readErr != nil { + return rp.readErr + } + if rp.reader == nil { + rp.readErr = io.EOF + return rp.readErr + } + + readSize := defaultReaderBufferSize + maxBufferSize := rp.config.MaxBufferSize + if maxBufferSize <= 0 { + maxBufferSize = defaultReaderMaxBufferSize + } + if readSize > maxBufferSize { + readSize = maxBufferSize + } + if readSize < 1 { + readSize = 1 + } + + oldLen := len(rp.buf) + if cap(rp.buf)-oldLen < readSize { + grown := make([]byte, oldLen, oldLen+readSize) + copy(grown, rp.buf) + rp.buf = grown + } + rp.buf = rp.buf[:oldLen+readSize] + n, err := rp.reader.Read(rp.buf[oldLen:]) + rp.buf = rp.buf[:oldLen+n] + + if n > 0 { + rp.emptyReads = 0 + if err != nil { + rp.readErr = err + } + return nil + } + if err != nil { + rp.readErr = err + return err + } + + rp.emptyReads++ + if rp.emptyReads >= maxConsecutiveEmptyReads { + rp.readErr = io.ErrNoProgress + return rp.readErr + } + return nil +} + +// SYS-REQ-116 +func (rp *ReaderParser) discardConsumed() { + if rp.pos == 0 { + return + } + rp.bufStart += int64(rp.pos) + rp.buf = rp.buf[rp.pos:] + rp.pos = 0 +} + +// SYS-REQ-116 +func valueTypeError(want string, value []byte) error { + return &readerTypeError{want: want, value: string(value)} +} + +type readerTypeError struct { + want string + value string +} + +// SYS-REQ-116 +func (e *readerTypeError) Error() string { + return "Value is not a " + e.want + ": " + e.value +} diff --git a/vendor/github.com/buger/jsonparser/run_fuzz_campaign.sh b/vendor/github.com/buger/jsonparser/run_fuzz_campaign.sh new file mode 100644 index 0000000..973be85 --- /dev/null +++ b/vendor/github.com/buger/jsonparser/run_fuzz_campaign.sh @@ -0,0 +1,54 @@ +#!/bin/bash +set -u +cd "$(dirname "$0")" +mkdir -p fuzz_results/crashes +LOG=fuzz_results/campaign.log +: > "$LOG" + +TARGETS=( + DeleteNative + ParseStringNative + EachKeyNative + SetNative + ObjectEachNative + ParseFloatNative + ParseIntNative + ParseBoolNative + TokenStartNative + GetStringNative + GetFloatNative + GetIntNative + GetBooleanNative + GetUnsafeStringNative +) +PER_TARGET=${PER_TARGET:-180s} +MAX_PASSES=${MAX_PASSES:-4} + +count_crashes() { ls fuzz_results/crashes/ 2>/dev/null | wc -l | tr -d ' '; } + +prev_count=$(count_crashes) +pass=0 +while [ $pass -lt $MAX_PASSES ]; do + pass=$((pass+1)) + echo "=== $(date '+%H:%M:%S') PASS $pass start (per-target=$PER_TARGET, baseline_unique_crashes=$prev_count) ===" | tee -a "$LOG" + for t in "${TARGETS[@]}"; do + pre=$(count_crashes) + echo " -> $(date '+%H:%M:%S') Fuzz${t}" | tee -a "$LOG" + go test -run='^$' -fuzz="^Fuzz${t}$" -fuzztime="${PER_TARGET}" \ + > "fuzz_results/${t}_pass${pass}.log" 2>&1 + rc=$? + post=$(count_crashes) + delta=$((post - pre)) + summary=$(tail -n 3 "fuzz_results/${t}_pass${pass}.log" | tr '\n' ' | ') + echo " rc=$rc new_crashes=$delta total=$post :: $summary" | tee -a "$LOG" + done + new_count=$(count_crashes) + pass_delta=$((new_count - prev_count)) + echo "=== $(date '+%H:%M:%S') PASS $pass done: total_unique_crashes=$new_count (+$pass_delta this pass) ===" | tee -a "$LOG" + if [ $pass_delta -eq 0 ] && [ $pass -ge 2 ]; then + echo "=== SATURATED after pass $pass — no new crashes ===" | tee -a "$LOG" + break + fi + prev_count=$new_count +done +echo "=== $(date '+%H:%M:%S') CAMPAIGN COMPLETE total_unique_crashes=$(count_crashes) ===" | tee -a "$LOG" diff --git a/vendor/github.com/buger/jsonparser/wildcard.go b/vendor/github.com/buger/jsonparser/wildcard.go new file mode 100644 index 0000000..9c0eebc --- /dev/null +++ b/vendor/github.com/buger/jsonparser/wildcard.go @@ -0,0 +1,158 @@ +package jsonparser + +import "strconv" + +const wildcardPathComponent = "[*]" + +// EachKeyWildcard resolves a path that may contain [*] components. A wildcard +// requires an array at that position and fans out over its elements before +// resolving the rest of the path. Multiple wildcards produce one callback for +// every matching combination, in document order. +// +// idx is the zero-based order in which matches are reported. +// +// SYS-REQ-113 +func EachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), path ...string) error { + nextMatch := 0 + return eachKeyWildcard(data, cb, &nextMatch, path) +} + +// SYS-REQ-113 +func eachKeyWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, err error), nextMatch *int, path []string) error { + wildcard := wildcardIndex(path) + if wildcard == -1 { + value, valueType, _, err := Get(data, path...) + if err != nil { + // A missing path has no value to report. Parsing errors for a + // located terminal value, however, follow EachKey's convention + // and are delivered to the callback as well as returned. + if err != KeyPathNotFoundError { + cb(*nextMatch, value, valueType, err) + (*nextMatch)++ + } + return err + } + + cb(*nextMatch, value, valueType, nil) + (*nextMatch)++ + return nil + } + + array, valueType, _, err := Get(data, path[:wildcard]...) + if err != nil { + return err + } + if valueType != Array { + return MalformedArrayError + } + + remaining := path[wildcard+1:] + _, err = ArrayEachErr(array, func(value []byte, elementType ValueType, _ int, parseErr error) error { + if parseErr != nil { + cb(*nextMatch, value, elementType, parseErr) + (*nextMatch)++ + return parseErr + } + + if len(remaining) == 0 { + cb(*nextMatch, value, elementType, nil) + (*nextMatch)++ + return nil + } + + return eachKeyWildcard(value, cb, nextMatch, remaining) + }) + return err +} + +// ArrayEachWildcard iterates over an array addressed by keys. A terminal [*] +// component is accepted as an explicit request for all elements; without it, +// the function behaves like ArrayEachErr. +// SYS-REQ-113 +func ArrayEachWildcard(data []byte, cb func(idx int, value []byte, vt ValueType, offset int, err error) error, keys ...string) (int, error) { + if len(keys) > 0 && keys[len(keys)-1] == wildcardPathComponent { + keys = keys[:len(keys)-1] + } + + index := 0 + return ArrayEachErr(data, func(value []byte, valueType ValueType, offset int, err error) error { + current := index + index++ + return cb(current, value, valueType, offset, err) + }, keys...) +} + +// SetWildcard applies Set to every concrete path matched by [*]. Wildcards +// may appear at any array position and may be repeated. If a wildcard matches +// an empty array, data is returned unchanged. +// +// SYS-REQ-113 +func SetWildcard(data []byte, setValue []byte, keys ...string) ([]byte, error) { + if wildcardIndex(keys) == -1 { + return Set(data, setValue, keys...) + } + + var paths [][]string + if err := expandWildcardPaths(data, nil, keys, &paths); err != nil { + return nil, err + } + + result := data + for _, path := range paths { + var err error + result, err = Set(result, setValue, path...) + if err != nil { + return nil, err + } + } + return result, nil +} + +// SYS-REQ-113 +func expandWildcardPaths(data []byte, concrete, remaining []string, paths *[][]string) error { + wildcard := wildcardIndex(remaining) + if wildcard == -1 { + path := make([]string, len(concrete)+len(remaining)) + copy(path, concrete) + copy(path[len(concrete):], remaining) + *paths = append(*paths, path) + return nil + } + + arrayPath := make([]string, len(concrete)+wildcard) + copy(arrayPath, concrete) + copy(arrayPath[len(concrete):], remaining[:wildcard]) + + array, valueType, _, err := Get(data, arrayPath...) + if err != nil { + return err + } + if valueType != Array { + return MalformedArrayError + } + + index := 0 + _, err = ArrayEachErr(array, func(_ []byte, _ ValueType, _ int, parseErr error) error { + if parseErr != nil { + return parseErr + } + + nextPath := make([]string, len(arrayPath)+1) + copy(nextPath, arrayPath) + nextPath[len(arrayPath)] = "[" + strconv.Itoa(index) + "]" + index++ + + return expandWildcardPaths(data, nextPath, remaining[wildcard+1:], paths) + }) + return err +} + +// SYS-REQ-113 +func wildcardIndex(path []string) int { + for i, component := range path { + if component == wildcardPathComponent { + return i + } + } + return -1 +} diff --git a/vendor/github.com/cenkalti/backoff/v5/.gitignore b/vendor/github.com/cenkalti/backoff/v5/.gitignore new file mode 100644 index 0000000..50d95c5 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/.gitignore @@ -0,0 +1,25 @@ +# 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 + +# IDEs +.idea/ diff --git a/vendor/github.com/cenkalti/backoff/v5/CHANGELOG.md b/vendor/github.com/cenkalti/backoff/v5/CHANGELOG.md new file mode 100644 index 0000000..658c374 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/CHANGELOG.md @@ -0,0 +1,29 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [5.0.0] - 2024-12-19 + +### Added + +- RetryAfterError can be returned from an operation to indicate how long to wait before the next retry. + +### Changed + +- Retry function now accepts additional options for specifying max number of tries and max elapsed time. +- Retry function now accepts a context.Context. +- Operation function signature changed to return result (any type) and error. + +### Removed + +- RetryNotify* and RetryWithData functions. Only single Retry function remains. +- Optional arguments from ExponentialBackoff constructor. +- Clock and Timer interfaces. + +### Fixed + +- The original error is returned from Retry if there's a PermanentError. (#144) +- The Retry function respects the wrapped PermanentError. (#140) diff --git a/vendor/github.com/cenkalti/backoff/v5/LICENSE b/vendor/github.com/cenkalti/backoff/v5/LICENSE new file mode 100644 index 0000000..89b8179 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Cenk Altı + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/cenkalti/backoff/v5/README.md b/vendor/github.com/cenkalti/backoff/v5/README.md new file mode 100644 index 0000000..4611b1d --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/README.md @@ -0,0 +1,31 @@ +# Exponential Backoff [![GoDoc][godoc image]][godoc] + +This is a Go port of the exponential backoff algorithm from [Google's HTTP Client Library for Java][google-http-java-client]. + +[Exponential backoff][exponential backoff wiki] +is an algorithm that uses feedback to multiplicatively decrease the rate of some process, +in order to gradually find an acceptable rate. +The retries exponentially increase and stop increasing when a certain threshold is met. + +## Usage + +Import path is `github.com/cenkalti/backoff/v5`. Please note the version part at the end. + +For most cases, use `Retry` function. See [example_test.go][example] for an example. + +If you have specific needs, copy `Retry` function (from [retry.go][retry-src]) into your code and modify it as needed. + +## Contributing + +* I would like to keep this library as small as possible. +* Please don't send a PR without opening an issue and discussing it first. +* If proposed change is not a common use case, I will probably not accept it. + +[godoc]: https://pkg.go.dev/github.com/cenkalti/backoff/v5 +[godoc image]: https://godoc.org/github.com/cenkalti/backoff?status.png + +[google-http-java-client]: https://github.com/google/google-http-java-client/blob/da1aa993e90285ec18579f1553339b00e19b3ab5/google-http-client/src/main/java/com/google/api/client/util/ExponentialBackOff.java +[exponential backoff wiki]: http://en.wikipedia.org/wiki/Exponential_backoff + +[retry-src]: https://github.com/cenkalti/backoff/blob/v5/retry.go +[example]: https://github.com/cenkalti/backoff/blob/v5/example_test.go diff --git a/vendor/github.com/cenkalti/backoff/v5/backoff.go b/vendor/github.com/cenkalti/backoff/v5/backoff.go new file mode 100644 index 0000000..dd2b24c --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/backoff.go @@ -0,0 +1,66 @@ +// Package backoff implements backoff algorithms for retrying operations. +// +// Use Retry function for retrying operations that may fail. +// If Retry does not meet your needs, +// copy/paste the function into your project and modify as you wish. +// +// There is also Ticker type similar to time.Ticker. +// You can use it if you need to work with channels. +// +// See Examples section below for usage examples. +package backoff + +import "time" + +// BackOff is a backoff policy for retrying an operation. +type BackOff interface { + // NextBackOff returns the duration to wait before retrying the operation, + // backoff.Stop to indicate that no more retries should be made. + // + // Example usage: + // + // duration := backoff.NextBackOff() + // if duration == backoff.Stop { + // // Do not retry operation. + // } else { + // // Sleep for duration and retry operation. + // } + // + NextBackOff() time.Duration + + // Reset to initial state. + Reset() +} + +// Stop indicates that no more retries should be made for use in NextBackOff(). +const Stop time.Duration = -1 + +// ZeroBackOff is a fixed backoff policy whose backoff time is always zero, +// meaning that the operation is retried immediately without waiting, indefinitely. +type ZeroBackOff struct{} + +func (b *ZeroBackOff) Reset() {} + +func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 } + +// StopBackOff is a fixed backoff policy that always returns backoff.Stop for +// NextBackOff(), meaning that the operation should never be retried. +type StopBackOff struct{} + +func (b *StopBackOff) Reset() {} + +func (b *StopBackOff) NextBackOff() time.Duration { return Stop } + +// ConstantBackOff is a backoff policy that always returns the same backoff delay. +// This is in contrast to an exponential backoff policy, +// which returns a delay that grows longer as you call NextBackOff() over and over again. +type ConstantBackOff struct { + Interval time.Duration +} + +func (b *ConstantBackOff) Reset() {} +func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval } + +func NewConstantBackOff(d time.Duration) *ConstantBackOff { + return &ConstantBackOff{Interval: d} +} diff --git a/vendor/github.com/cenkalti/backoff/v5/error.go b/vendor/github.com/cenkalti/backoff/v5/error.go new file mode 100644 index 0000000..beb2b38 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/error.go @@ -0,0 +1,46 @@ +package backoff + +import ( + "fmt" + "time" +) + +// PermanentError signals that the operation should not be retried. +type PermanentError struct { + Err error +} + +// Permanent wraps the given err in a *PermanentError. +func Permanent(err error) error { + if err == nil { + return nil + } + return &PermanentError{ + Err: err, + } +} + +// Error returns a string representation of the Permanent error. +func (e *PermanentError) Error() string { + return e.Err.Error() +} + +// Unwrap returns the wrapped error. +func (e *PermanentError) Unwrap() error { + return e.Err +} + +// RetryAfterError signals that the operation should be retried after the given duration. +type RetryAfterError struct { + Duration time.Duration +} + +// RetryAfter returns a RetryAfter error that specifies how long to wait before retrying. +func RetryAfter(seconds int) error { + return &RetryAfterError{Duration: time.Duration(seconds) * time.Second} +} + +// Error returns a string representation of the RetryAfter error. +func (e *RetryAfterError) Error() string { + return fmt.Sprintf("retry after %s", e.Duration) +} diff --git a/vendor/github.com/cenkalti/backoff/v5/exponential.go b/vendor/github.com/cenkalti/backoff/v5/exponential.go new file mode 100644 index 0000000..79d425e --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/exponential.go @@ -0,0 +1,118 @@ +package backoff + +import ( + "math/rand/v2" + "time" +) + +/* +ExponentialBackOff is a backoff implementation that increases the backoff +period for each retry attempt using a randomization function that grows exponentially. + +NextBackOff() is calculated using the following formula: + + randomized interval = + RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) + +In other words NextBackOff() will range between the randomization factor +percentage below and above the retry interval. + +For example, given the following parameters: + + RetryInterval = 2 + RandomizationFactor = 0.5 + Multiplier = 2 + +the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, +multiplied by the exponential, that is, between 2 and 6 seconds. + +Note: MaxInterval caps the RetryInterval and not the randomized interval. + +Example: Given the following default arguments, for 9 tries the sequence will be: + + Request # RetryInterval (seconds) Randomized Interval (seconds) + + 1 0.5 [0.25, 0.75] + 2 0.75 [0.375, 1.125] + 3 1.125 [0.562, 1.687] + 4 1.687 [0.8435, 2.53] + 5 2.53 [1.265, 3.795] + 6 3.795 [1.897, 5.692] + 7 5.692 [2.846, 8.538] + 8 8.538 [4.269, 12.807] + 9 12.807 [6.403, 19.210] + +Note: Implementation is not thread-safe. +*/ +type ExponentialBackOff struct { + InitialInterval time.Duration + RandomizationFactor float64 + Multiplier float64 + MaxInterval time.Duration + + currentInterval time.Duration +} + +// Default values for ExponentialBackOff. +const ( + DefaultInitialInterval = 500 * time.Millisecond + DefaultRandomizationFactor = 0.5 + DefaultMultiplier = 1.5 + DefaultMaxInterval = 60 * time.Second +) + +// NewExponentialBackOff creates an instance of ExponentialBackOff using default values. +func NewExponentialBackOff() *ExponentialBackOff { + return &ExponentialBackOff{ + InitialInterval: DefaultInitialInterval, + RandomizationFactor: DefaultRandomizationFactor, + Multiplier: DefaultMultiplier, + MaxInterval: DefaultMaxInterval, + } +} + +// Reset the interval back to the initial retry interval and restarts the timer. +// Reset must be called before using b. +func (b *ExponentialBackOff) Reset() { + b.currentInterval = b.InitialInterval +} + +// NextBackOff calculates the next backoff interval using the formula: +// +// Randomized interval = RetryInterval * (1 ± RandomizationFactor) +func (b *ExponentialBackOff) NextBackOff() time.Duration { + if b.currentInterval == 0 { + b.currentInterval = b.InitialInterval + } + + next := getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval) + b.incrementCurrentInterval() + return next +} + +// Increments the current interval by multiplying it with the multiplier. +func (b *ExponentialBackOff) incrementCurrentInterval() { + // Check for overflow, if overflow is detected set the current interval to the max interval. + if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier { + b.currentInterval = b.MaxInterval + } else { + b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier) + } +} + +// Returns a random value from the following interval: +// +// [currentInterval - randomizationFactor * currentInterval, currentInterval + randomizationFactor * currentInterval]. +func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { + if randomizationFactor == 0 { + return currentInterval // make sure no randomness is used when randomizationFactor is 0. + } + var delta = randomizationFactor * float64(currentInterval) + var minInterval = float64(currentInterval) - delta + var maxInterval = float64(currentInterval) + delta + + // Get a random value from the range [minInterval, maxInterval]. + // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then + // we want a 33% chance for selecting either 1, 2 or 3. + return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) +} diff --git a/vendor/github.com/cenkalti/backoff/v5/retry.go b/vendor/github.com/cenkalti/backoff/v5/retry.go new file mode 100644 index 0000000..32a7f98 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/retry.go @@ -0,0 +1,139 @@ +package backoff + +import ( + "context" + "errors" + "time" +) + +// DefaultMaxElapsedTime sets a default limit for the total retry duration. +const DefaultMaxElapsedTime = 15 * time.Minute + +// Operation is a function that attempts an operation and may be retried. +type Operation[T any] func() (T, error) + +// Notify is a function called on operation error with the error and backoff duration. +type Notify func(error, time.Duration) + +// retryOptions holds configuration settings for the retry mechanism. +type retryOptions struct { + BackOff BackOff // Strategy for calculating backoff periods. + Timer timer // Timer to manage retry delays. + Notify Notify // Optional function to notify on each retry error. + MaxTries uint // Maximum number of retry attempts. + MaxElapsedTime time.Duration // Maximum total time for all retries. +} + +type RetryOption func(*retryOptions) + +// WithBackOff configures a custom backoff strategy. +func WithBackOff(b BackOff) RetryOption { + return func(args *retryOptions) { + args.BackOff = b + } +} + +// withTimer sets a custom timer for managing delays between retries. +func withTimer(t timer) RetryOption { + return func(args *retryOptions) { + args.Timer = t + } +} + +// WithNotify sets a notification function to handle retry errors. +func WithNotify(n Notify) RetryOption { + return func(args *retryOptions) { + args.Notify = n + } +} + +// WithMaxTries limits the number of all attempts. +func WithMaxTries(n uint) RetryOption { + return func(args *retryOptions) { + args.MaxTries = n + } +} + +// WithMaxElapsedTime limits the total duration for retry attempts. +func WithMaxElapsedTime(d time.Duration) RetryOption { + return func(args *retryOptions) { + args.MaxElapsedTime = d + } +} + +// Retry attempts the operation until success, a permanent error, or backoff completion. +// It ensures the operation is executed at least once. +// +// Returns the operation result or error if retries are exhausted or context is cancelled. +func Retry[T any](ctx context.Context, operation Operation[T], opts ...RetryOption) (T, error) { + // Initialize default retry options. + args := &retryOptions{ + BackOff: NewExponentialBackOff(), + Timer: &defaultTimer{}, + MaxElapsedTime: DefaultMaxElapsedTime, + } + + // Apply user-provided options to the default settings. + for _, opt := range opts { + opt(args) + } + + defer args.Timer.Stop() + + startedAt := time.Now() + args.BackOff.Reset() + for numTries := uint(1); ; numTries++ { + // Execute the operation. + res, err := operation() + if err == nil { + return res, nil + } + + // Stop retrying if maximum tries exceeded. + if args.MaxTries > 0 && numTries >= args.MaxTries { + return res, err + } + + // Handle permanent errors without retrying. + var permanent *PermanentError + if errors.As(err, &permanent) { + return res, permanent.Unwrap() + } + + // Stop retrying if context is cancelled. + if cerr := context.Cause(ctx); cerr != nil { + return res, cerr + } + + // Calculate next backoff duration. + next := args.BackOff.NextBackOff() + if next == Stop { + return res, err + } + + // Reset backoff if RetryAfterError is encountered. + var retryAfter *RetryAfterError + if errors.As(err, &retryAfter) { + next = retryAfter.Duration + args.BackOff.Reset() + } + + // Stop retrying if maximum elapsed time exceeded. + if args.MaxElapsedTime > 0 && time.Since(startedAt)+next > args.MaxElapsedTime { + return res, err + } + + // Notify on error if a notifier function is provided. + if args.Notify != nil { + args.Notify(err, next) + } + + // Wait for the next backoff period or context cancellation. + args.Timer.Start(next) + select { + case <-args.Timer.C(): + case <-ctx.Done(): + return res, context.Cause(ctx) + } + } +} diff --git a/vendor/github.com/cenkalti/backoff/v5/ticker.go b/vendor/github.com/cenkalti/backoff/v5/ticker.go new file mode 100644 index 0000000..f0d4b2a --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/ticker.go @@ -0,0 +1,83 @@ +package backoff + +import ( + "sync" + "time" +) + +// Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. +// +// Ticks will continue to arrive when the previous operation is still running, +// so operations that take a while to fail could run in quick succession. +type Ticker struct { + C <-chan time.Time + c chan time.Time + b BackOff + timer timer + stop chan struct{} + stopOnce sync.Once +} + +// NewTicker returns a new Ticker containing a channel that will send +// the time at times specified by the BackOff argument. Ticker is +// guaranteed to tick at least once. The channel is closed when Stop +// method is called or BackOff stops. It is not safe to manipulate the +// provided backoff policy (notably calling NextBackOff or Reset) +// while the ticker is running. +func NewTicker(b BackOff) *Ticker { + c := make(chan time.Time) + t := &Ticker{ + C: c, + c: c, + b: b, + timer: &defaultTimer{}, + stop: make(chan struct{}), + } + t.b.Reset() + go t.run() + return t +} + +// Stop turns off a ticker. After Stop, no more ticks will be sent. +func (t *Ticker) Stop() { + t.stopOnce.Do(func() { close(t.stop) }) +} + +func (t *Ticker) run() { + c := t.c + defer close(c) + + // Ticker is guaranteed to tick at least once. + afterC := t.send(time.Now()) + + for { + if afterC == nil { + return + } + + select { + case tick := <-afterC: + afterC = t.send(tick) + case <-t.stop: + t.c = nil // Prevent future ticks from being sent to the channel. + return + } + } +} + +func (t *Ticker) send(tick time.Time) <-chan time.Time { + select { + case t.c <- tick: + case <-t.stop: + return nil + } + + next := t.b.NextBackOff() + if next == Stop { + t.Stop() + return nil + } + + t.timer.Start(next) + return t.timer.C() +} diff --git a/vendor/github.com/cenkalti/backoff/v5/timer.go b/vendor/github.com/cenkalti/backoff/v5/timer.go new file mode 100644 index 0000000..a895309 --- /dev/null +++ b/vendor/github.com/cenkalti/backoff/v5/timer.go @@ -0,0 +1,35 @@ +package backoff + +import "time" + +type timer interface { + Start(duration time.Duration) + Stop() + C() <-chan time.Time +} + +// defaultTimer implements Timer interface using time.Timer +type defaultTimer struct { + timer *time.Timer +} + +// C returns the timers channel which receives the current time when the timer fires. +func (t *defaultTimer) C() <-chan time.Time { + return t.timer.C +} + +// Start starts the timer to fire after the given duration +func (t *defaultTimer) Start(duration time.Duration) { + if t.timer == nil { + t.timer = time.NewTimer(duration) + } else { + t.timer.Reset(duration) + } +} + +// Stop is called when the timer is not used anymore and resources may be freed. +func (t *defaultTimer) Stop() { + if t.timer != nil { + t.timer.Stop() + } +} diff --git a/vendor/github.com/cespare/xxhash/v2/LICENSE.txt b/vendor/github.com/cespare/xxhash/v2/LICENSE.txt new file mode 100644 index 0000000..24b5306 --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2016 Caleb Spare + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/cespare/xxhash/v2/README.md b/vendor/github.com/cespare/xxhash/v2/README.md new file mode 100644 index 0000000..33c8830 --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/README.md @@ -0,0 +1,74 @@ +# xxhash + +[![Go Reference](https://pkg.go.dev/badge/github.com/cespare/xxhash/v2.svg)](https://pkg.go.dev/github.com/cespare/xxhash/v2) +[![Test](https://github.com/cespare/xxhash/actions/workflows/test.yml/badge.svg)](https://github.com/cespare/xxhash/actions/workflows/test.yml) + +xxhash is a Go implementation of the 64-bit [xxHash] algorithm, XXH64. This is a +high-quality hashing algorithm that is much faster than anything in the Go +standard library. + +This package provides a straightforward API: + +``` +func Sum64(b []byte) uint64 +func Sum64String(s string) uint64 +type Digest struct{ ... } + func New() *Digest +``` + +The `Digest` type implements hash.Hash64. Its key methods are: + +``` +func (*Digest) Write([]byte) (int, error) +func (*Digest) WriteString(string) (int, error) +func (*Digest) Sum64() uint64 +``` + +The package is written with optimized pure Go and also contains even faster +assembly implementations for amd64 and arm64. If desired, the `purego` build tag +opts into using the Go code even on those architectures. + +[xxHash]: http://cyan4973.github.io/xxHash/ + +## Compatibility + +This package is in a module and the latest code is in version 2 of the module. +You need a version of Go with at least "minimal module compatibility" to use +github.com/cespare/xxhash/v2: + +* 1.9.7+ for Go 1.9 +* 1.10.3+ for Go 1.10 +* Go 1.11 or later + +I recommend using the latest release of Go. + +## Benchmarks + +Here are some quick benchmarks comparing the pure-Go and assembly +implementations of Sum64. + +| input size | purego | asm | +| ---------- | --------- | --------- | +| 4 B | 1.3 GB/s | 1.2 GB/s | +| 16 B | 2.9 GB/s | 3.5 GB/s | +| 100 B | 6.9 GB/s | 8.1 GB/s | +| 4 KB | 11.7 GB/s | 16.7 GB/s | +| 10 MB | 12.0 GB/s | 17.3 GB/s | + +These numbers were generated on Ubuntu 20.04 with an Intel Xeon Platinum 8252C +CPU using the following commands under Go 1.19.2: + +``` +benchstat <(go test -tags purego -benchtime 500ms -count 15 -bench 'Sum64$') +benchstat <(go test -benchtime 500ms -count 15 -bench 'Sum64$') +``` + +## Projects using this package + +- [InfluxDB](https://github.com/influxdata/influxdb) +- [Prometheus](https://github.com/prometheus/prometheus) +- [VictoriaMetrics](https://github.com/VictoriaMetrics/VictoriaMetrics) +- [FreeCache](https://github.com/coocood/freecache) +- [FastCache](https://github.com/VictoriaMetrics/fastcache) +- [Ristretto](https://github.com/dgraph-io/ristretto) +- [Badger](https://github.com/dgraph-io/badger) diff --git a/vendor/github.com/cespare/xxhash/v2/testall.sh b/vendor/github.com/cespare/xxhash/v2/testall.sh new file mode 100644 index 0000000..94b9c44 --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/testall.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -eu -o pipefail + +# Small convenience script for running the tests with various combinations of +# arch/tags. This assumes we're running on amd64 and have qemu available. + +go test ./... +go test -tags purego ./... +GOARCH=arm64 go test +GOARCH=arm64 go test -tags purego diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash.go b/vendor/github.com/cespare/xxhash/v2/xxhash.go new file mode 100644 index 0000000..78bddf1 --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash.go @@ -0,0 +1,243 @@ +// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described +// at http://cyan4973.github.io/xxHash/. +package xxhash + +import ( + "encoding/binary" + "errors" + "math/bits" +) + +const ( + prime1 uint64 = 11400714785074694791 + prime2 uint64 = 14029467366897019727 + prime3 uint64 = 1609587929392839161 + prime4 uint64 = 9650029242287828579 + prime5 uint64 = 2870177450012600261 +) + +// Store the primes in an array as well. +// +// The consts are used when possible in Go code to avoid MOVs but we need a +// contiguous array for the assembly code. +var primes = [...]uint64{prime1, prime2, prime3, prime4, prime5} + +// Digest implements hash.Hash64. +// +// Note that a zero-valued Digest is not ready to receive writes. +// Call Reset or create a Digest using New before calling other methods. +type Digest struct { + v1 uint64 + v2 uint64 + v3 uint64 + v4 uint64 + total uint64 + mem [32]byte + n int // how much of mem is used +} + +// New creates a new Digest with a zero seed. +func New() *Digest { + return NewWithSeed(0) +} + +// NewWithSeed creates a new Digest with the given seed. +func NewWithSeed(seed uint64) *Digest { + var d Digest + d.ResetWithSeed(seed) + return &d +} + +// Reset clears the Digest's state so that it can be reused. +// It uses a seed value of zero. +func (d *Digest) Reset() { + d.ResetWithSeed(0) +} + +// ResetWithSeed clears the Digest's state so that it can be reused. +// It uses the given seed to initialize the state. +func (d *Digest) ResetWithSeed(seed uint64) { + d.v1 = seed + prime1 + prime2 + d.v2 = seed + prime2 + d.v3 = seed + d.v4 = seed - prime1 + d.total = 0 + d.n = 0 +} + +// Size always returns 8 bytes. +func (d *Digest) Size() int { return 8 } + +// BlockSize always returns 32 bytes. +func (d *Digest) BlockSize() int { return 32 } + +// Write adds more data to d. It always returns len(b), nil. +func (d *Digest) Write(b []byte) (n int, err error) { + n = len(b) + d.total += uint64(n) + + memleft := d.mem[d.n&(len(d.mem)-1):] + + if d.n+n < 32 { + // This new data doesn't even fill the current block. + copy(memleft, b) + d.n += n + return + } + + if d.n > 0 { + // Finish off the partial block. + c := copy(memleft, b) + d.v1 = round(d.v1, u64(d.mem[0:8])) + d.v2 = round(d.v2, u64(d.mem[8:16])) + d.v3 = round(d.v3, u64(d.mem[16:24])) + d.v4 = round(d.v4, u64(d.mem[24:32])) + b = b[c:] + d.n = 0 + } + + if len(b) >= 32 { + // One or more full blocks left. + nw := writeBlocks(d, b) + b = b[nw:] + } + + // Store any remaining partial block. + copy(d.mem[:], b) + d.n = len(b) + + return +} + +// Sum appends the current hash to b and returns the resulting slice. +func (d *Digest) Sum(b []byte) []byte { + s := d.Sum64() + return append( + b, + byte(s>>56), + byte(s>>48), + byte(s>>40), + byte(s>>32), + byte(s>>24), + byte(s>>16), + byte(s>>8), + byte(s), + ) +} + +// Sum64 returns the current hash. +func (d *Digest) Sum64() uint64 { + var h uint64 + + if d.total >= 32 { + v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 + h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) + h = mergeRound(h, v1) + h = mergeRound(h, v2) + h = mergeRound(h, v3) + h = mergeRound(h, v4) + } else { + h = d.v3 + prime5 + } + + h += d.total + + b := d.mem[:d.n&(len(d.mem)-1)] + for ; len(b) >= 8; b = b[8:] { + k1 := round(0, u64(b[:8])) + h ^= k1 + h = rol27(h)*prime1 + prime4 + } + if len(b) >= 4 { + h ^= uint64(u32(b[:4])) * prime1 + h = rol23(h)*prime2 + prime3 + b = b[4:] + } + for ; len(b) > 0; b = b[1:] { + h ^= uint64(b[0]) * prime5 + h = rol11(h) * prime1 + } + + h ^= h >> 33 + h *= prime2 + h ^= h >> 29 + h *= prime3 + h ^= h >> 32 + + return h +} + +const ( + magic = "xxh\x06" + marshaledSize = len(magic) + 8*5 + 32 +) + +// MarshalBinary implements the encoding.BinaryMarshaler interface. +func (d *Digest) MarshalBinary() ([]byte, error) { + b := make([]byte, 0, marshaledSize) + b = append(b, magic...) + b = appendUint64(b, d.v1) + b = appendUint64(b, d.v2) + b = appendUint64(b, d.v3) + b = appendUint64(b, d.v4) + b = appendUint64(b, d.total) + b = append(b, d.mem[:d.n]...) + b = b[:len(b)+len(d.mem)-d.n] + return b, nil +} + +// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +func (d *Digest) UnmarshalBinary(b []byte) error { + if len(b) < len(magic) || string(b[:len(magic)]) != magic { + return errors.New("xxhash: invalid hash state identifier") + } + if len(b) != marshaledSize { + return errors.New("xxhash: invalid hash state size") + } + b = b[len(magic):] + b, d.v1 = consumeUint64(b) + b, d.v2 = consumeUint64(b) + b, d.v3 = consumeUint64(b) + b, d.v4 = consumeUint64(b) + b, d.total = consumeUint64(b) + copy(d.mem[:], b) + d.n = int(d.total % uint64(len(d.mem))) + return nil +} + +func appendUint64(b []byte, x uint64) []byte { + var a [8]byte + binary.LittleEndian.PutUint64(a[:], x) + return append(b, a[:]...) +} + +func consumeUint64(b []byte) ([]byte, uint64) { + x := u64(b) + return b[8:], x +} + +func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) } +func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) } + +func round(acc, input uint64) uint64 { + acc += input * prime2 + acc = rol31(acc) + acc *= prime1 + return acc +} + +func mergeRound(acc, val uint64) uint64 { + val = round(0, val) + acc ^= val + acc = acc*prime1 + prime4 + return acc +} + +func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) } +func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) } +func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) } +func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) } +func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) } +func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) } +func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) } +func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) } diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s new file mode 100644 index 0000000..3e8b132 --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash_amd64.s @@ -0,0 +1,209 @@ +//go:build !appengine && gc && !purego +// +build !appengine +// +build gc +// +build !purego + +#include "textflag.h" + +// Registers: +#define h AX +#define d AX +#define p SI // pointer to advance through b +#define n DX +#define end BX // loop end +#define v1 R8 +#define v2 R9 +#define v3 R10 +#define v4 R11 +#define x R12 +#define prime1 R13 +#define prime2 R14 +#define prime4 DI + +#define round(acc, x) \ + IMULQ prime2, x \ + ADDQ x, acc \ + ROLQ $31, acc \ + IMULQ prime1, acc + +// round0 performs the operation x = round(0, x). +#define round0(x) \ + IMULQ prime2, x \ + ROLQ $31, x \ + IMULQ prime1, x + +// mergeRound applies a merge round on the two registers acc and x. +// It assumes that prime1, prime2, and prime4 have been loaded. +#define mergeRound(acc, x) \ + round0(x) \ + XORQ x, acc \ + IMULQ prime1, acc \ + ADDQ prime4, acc + +// blockLoop processes as many 32-byte blocks as possible, +// updating v1, v2, v3, and v4. It assumes that there is at least one block +// to process. +#define blockLoop() \ +loop: \ + MOVQ +0(p), x \ + round(v1, x) \ + MOVQ +8(p), x \ + round(v2, x) \ + MOVQ +16(p), x \ + round(v3, x) \ + MOVQ +24(p), x \ + round(v4, x) \ + ADDQ $32, p \ + CMPQ p, end \ + JLE loop + +// func Sum64(b []byte) uint64 +TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 + // Load fixed primes. + MOVQ ·primes+0(SB), prime1 + MOVQ ·primes+8(SB), prime2 + MOVQ ·primes+24(SB), prime4 + + // Load slice. + MOVQ b_base+0(FP), p + MOVQ b_len+8(FP), n + LEAQ (p)(n*1), end + + // The first loop limit will be len(b)-32. + SUBQ $32, end + + // Check whether we have at least one block. + CMPQ n, $32 + JLT noBlocks + + // Set up initial state (v1, v2, v3, v4). + MOVQ prime1, v1 + ADDQ prime2, v1 + MOVQ prime2, v2 + XORQ v3, v3 + XORQ v4, v4 + SUBQ prime1, v4 + + blockLoop() + + MOVQ v1, h + ROLQ $1, h + MOVQ v2, x + ROLQ $7, x + ADDQ x, h + MOVQ v3, x + ROLQ $12, x + ADDQ x, h + MOVQ v4, x + ROLQ $18, x + ADDQ x, h + + mergeRound(h, v1) + mergeRound(h, v2) + mergeRound(h, v3) + mergeRound(h, v4) + + JMP afterBlocks + +noBlocks: + MOVQ ·primes+32(SB), h + +afterBlocks: + ADDQ n, h + + ADDQ $24, end + CMPQ p, end + JG try4 + +loop8: + MOVQ (p), x + ADDQ $8, p + round0(x) + XORQ x, h + ROLQ $27, h + IMULQ prime1, h + ADDQ prime4, h + + CMPQ p, end + JLE loop8 + +try4: + ADDQ $4, end + CMPQ p, end + JG try1 + + MOVL (p), x + ADDQ $4, p + IMULQ prime1, x + XORQ x, h + + ROLQ $23, h + IMULQ prime2, h + ADDQ ·primes+16(SB), h + +try1: + ADDQ $4, end + CMPQ p, end + JGE finalize + +loop1: + MOVBQZX (p), x + ADDQ $1, p + IMULQ ·primes+32(SB), x + XORQ x, h + ROLQ $11, h + IMULQ prime1, h + + CMPQ p, end + JL loop1 + +finalize: + MOVQ h, x + SHRQ $33, x + XORQ x, h + IMULQ prime2, h + MOVQ h, x + SHRQ $29, x + XORQ x, h + IMULQ ·primes+16(SB), h + MOVQ h, x + SHRQ $32, x + XORQ x, h + + MOVQ h, ret+24(FP) + RET + +// func writeBlocks(d *Digest, b []byte) int +TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 + // Load fixed primes needed for round. + MOVQ ·primes+0(SB), prime1 + MOVQ ·primes+8(SB), prime2 + + // Load slice. + MOVQ b_base+8(FP), p + MOVQ b_len+16(FP), n + LEAQ (p)(n*1), end + SUBQ $32, end + + // Load vN from d. + MOVQ s+0(FP), d + MOVQ 0(d), v1 + MOVQ 8(d), v2 + MOVQ 16(d), v3 + MOVQ 24(d), v4 + + // We don't need to check the loop condition here; this function is + // always called with at least one block of data to process. + blockLoop() + + // Copy vN back to d. + MOVQ v1, 0(d) + MOVQ v2, 8(d) + MOVQ v3, 16(d) + MOVQ v4, 24(d) + + // The number of bytes written is p minus the old base pointer. + SUBQ b_base+8(FP), p + MOVQ p, ret+32(FP) + + RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s b/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s new file mode 100644 index 0000000..7e3145a --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash_arm64.s @@ -0,0 +1,183 @@ +//go:build !appengine && gc && !purego +// +build !appengine +// +build gc +// +build !purego + +#include "textflag.h" + +// Registers: +#define digest R1 +#define h R2 // return value +#define p R3 // input pointer +#define n R4 // input length +#define nblocks R5 // n / 32 +#define prime1 R7 +#define prime2 R8 +#define prime3 R9 +#define prime4 R10 +#define prime5 R11 +#define v1 R12 +#define v2 R13 +#define v3 R14 +#define v4 R15 +#define x1 R20 +#define x2 R21 +#define x3 R22 +#define x4 R23 + +#define round(acc, x) \ + MADD prime2, acc, x, acc \ + ROR $64-31, acc \ + MUL prime1, acc + +// round0 performs the operation x = round(0, x). +#define round0(x) \ + MUL prime2, x \ + ROR $64-31, x \ + MUL prime1, x + +#define mergeRound(acc, x) \ + round0(x) \ + EOR x, acc \ + MADD acc, prime4, prime1, acc + +// blockLoop processes as many 32-byte blocks as possible, +// updating v1, v2, v3, and v4. It assumes that n >= 32. +#define blockLoop() \ + LSR $5, n, nblocks \ + PCALIGN $16 \ + loop: \ + LDP.P 16(p), (x1, x2) \ + LDP.P 16(p), (x3, x4) \ + round(v1, x1) \ + round(v2, x2) \ + round(v3, x3) \ + round(v4, x4) \ + SUB $1, nblocks \ + CBNZ nblocks, loop + +// func Sum64(b []byte) uint64 +TEXT ·Sum64(SB), NOSPLIT|NOFRAME, $0-32 + LDP b_base+0(FP), (p, n) + + LDP ·primes+0(SB), (prime1, prime2) + LDP ·primes+16(SB), (prime3, prime4) + MOVD ·primes+32(SB), prime5 + + CMP $32, n + CSEL LT, prime5, ZR, h // if n < 32 { h = prime5 } else { h = 0 } + BLT afterLoop + + ADD prime1, prime2, v1 + MOVD prime2, v2 + MOVD $0, v3 + NEG prime1, v4 + + blockLoop() + + ROR $64-1, v1, x1 + ROR $64-7, v2, x2 + ADD x1, x2 + ROR $64-12, v3, x3 + ROR $64-18, v4, x4 + ADD x3, x4 + ADD x2, x4, h + + mergeRound(h, v1) + mergeRound(h, v2) + mergeRound(h, v3) + mergeRound(h, v4) + +afterLoop: + ADD n, h + + TBZ $4, n, try8 + LDP.P 16(p), (x1, x2) + + round0(x1) + + // NOTE: here and below, sequencing the EOR after the ROR (using a + // rotated register) is worth a small but measurable speedup for small + // inputs. + ROR $64-27, h + EOR x1 @> 64-27, h, h + MADD h, prime4, prime1, h + + round0(x2) + ROR $64-27, h + EOR x2 @> 64-27, h, h + MADD h, prime4, prime1, h + +try8: + TBZ $3, n, try4 + MOVD.P 8(p), x1 + + round0(x1) + ROR $64-27, h + EOR x1 @> 64-27, h, h + MADD h, prime4, prime1, h + +try4: + TBZ $2, n, try2 + MOVWU.P 4(p), x2 + + MUL prime1, x2 + ROR $64-23, h + EOR x2 @> 64-23, h, h + MADD h, prime3, prime2, h + +try2: + TBZ $1, n, try1 + MOVHU.P 2(p), x3 + AND $255, x3, x1 + LSR $8, x3, x2 + + MUL prime5, x1 + ROR $64-11, h + EOR x1 @> 64-11, h, h + MUL prime1, h + + MUL prime5, x2 + ROR $64-11, h + EOR x2 @> 64-11, h, h + MUL prime1, h + +try1: + TBZ $0, n, finalize + MOVBU (p), x4 + + MUL prime5, x4 + ROR $64-11, h + EOR x4 @> 64-11, h, h + MUL prime1, h + +finalize: + EOR h >> 33, h + MUL prime2, h + EOR h >> 29, h + MUL prime3, h + EOR h >> 32, h + + MOVD h, ret+24(FP) + RET + +// func writeBlocks(d *Digest, b []byte) int +TEXT ·writeBlocks(SB), NOSPLIT|NOFRAME, $0-40 + LDP ·primes+0(SB), (prime1, prime2) + + // Load state. Assume v[1-4] are stored contiguously. + MOVD d+0(FP), digest + LDP 0(digest), (v1, v2) + LDP 16(digest), (v3, v4) + + LDP b_base+8(FP), (p, n) + + blockLoop() + + // Store updated state. + STP (v1, v2), 0(digest) + STP (v3, v4), 16(digest) + + BIC $31, n + MOVD n, ret+32(FP) + RET diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go b/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go new file mode 100644 index 0000000..78f95f2 --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash_asm.go @@ -0,0 +1,15 @@ +//go:build (amd64 || arm64) && !appengine && gc && !purego +// +build amd64 arm64 +// +build !appengine +// +build gc +// +build !purego + +package xxhash + +// Sum64 computes the 64-bit xxHash digest of b with a zero seed. +// +//go:noescape +func Sum64(b []byte) uint64 + +//go:noescape +func writeBlocks(d *Digest, b []byte) int diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_other.go b/vendor/github.com/cespare/xxhash/v2/xxhash_other.go new file mode 100644 index 0000000..118e49e --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash_other.go @@ -0,0 +1,76 @@ +//go:build (!amd64 && !arm64) || appengine || !gc || purego +// +build !amd64,!arm64 appengine !gc purego + +package xxhash + +// Sum64 computes the 64-bit xxHash digest of b with a zero seed. +func Sum64(b []byte) uint64 { + // A simpler version would be + // d := New() + // d.Write(b) + // return d.Sum64() + // but this is faster, particularly for small inputs. + + n := len(b) + var h uint64 + + if n >= 32 { + v1 := primes[0] + prime2 + v2 := prime2 + v3 := uint64(0) + v4 := -primes[0] + for len(b) >= 32 { + v1 = round(v1, u64(b[0:8:len(b)])) + v2 = round(v2, u64(b[8:16:len(b)])) + v3 = round(v3, u64(b[16:24:len(b)])) + v4 = round(v4, u64(b[24:32:len(b)])) + b = b[32:len(b):len(b)] + } + h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4) + h = mergeRound(h, v1) + h = mergeRound(h, v2) + h = mergeRound(h, v3) + h = mergeRound(h, v4) + } else { + h = prime5 + } + + h += uint64(n) + + for ; len(b) >= 8; b = b[8:] { + k1 := round(0, u64(b[:8])) + h ^= k1 + h = rol27(h)*prime1 + prime4 + } + if len(b) >= 4 { + h ^= uint64(u32(b[:4])) * prime1 + h = rol23(h)*prime2 + prime3 + b = b[4:] + } + for ; len(b) > 0; b = b[1:] { + h ^= uint64(b[0]) * prime5 + h = rol11(h) * prime1 + } + + h ^= h >> 33 + h *= prime2 + h ^= h >> 29 + h *= prime3 + h ^= h >> 32 + + return h +} + +func writeBlocks(d *Digest, b []byte) int { + v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4 + n := len(b) + for len(b) >= 32 { + v1 = round(v1, u64(b[0:8:len(b)])) + v2 = round(v2, u64(b[8:16:len(b)])) + v3 = round(v3, u64(b[16:24:len(b)])) + v4 = round(v4, u64(b[24:32:len(b)])) + b = b[32:len(b):len(b)] + } + d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4 + return n - len(b) +} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go new file mode 100644 index 0000000..05f5e7d --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash_safe.go @@ -0,0 +1,16 @@ +//go:build appengine +// +build appengine + +// This file contains the safe implementations of otherwise unsafe-using code. + +package xxhash + +// Sum64String computes the 64-bit xxHash digest of s with a zero seed. +func Sum64String(s string) uint64 { + return Sum64([]byte(s)) +} + +// WriteString adds more data to d. It always returns len(s), nil. +func (d *Digest) WriteString(s string) (n int, err error) { + return d.Write([]byte(s)) +} diff --git a/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go b/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go new file mode 100644 index 0000000..cf9d42a --- /dev/null +++ b/vendor/github.com/cespare/xxhash/v2/xxhash_unsafe.go @@ -0,0 +1,58 @@ +//go:build !appengine +// +build !appengine + +// This file encapsulates usage of unsafe. +// xxhash_safe.go contains the safe implementations. + +package xxhash + +import ( + "unsafe" +) + +// In the future it's possible that compiler optimizations will make these +// XxxString functions unnecessary by realizing that calls such as +// Sum64([]byte(s)) don't need to copy s. See https://go.dev/issue/2205. +// If that happens, even if we keep these functions they can be replaced with +// the trivial safe code. + +// NOTE: The usual way of doing an unsafe string-to-[]byte conversion is: +// +// var b []byte +// bh := (*reflect.SliceHeader)(unsafe.Pointer(&b)) +// bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data +// bh.Len = len(s) +// bh.Cap = len(s) +// +// Unfortunately, as of Go 1.15.3 the inliner's cost model assigns a high enough +// weight to this sequence of expressions that any function that uses it will +// not be inlined. Instead, the functions below use a different unsafe +// conversion designed to minimize the inliner weight and allow both to be +// inlined. There is also a test (TestInlining) which verifies that these are +// inlined. +// +// See https://github.com/golang/go/issues/42739 for discussion. + +// Sum64String computes the 64-bit xxHash digest of s with a zero seed. +// It may be faster than Sum64([]byte(s)) by avoiding a copy. +func Sum64String(s string) uint64 { + b := *(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)})) + return Sum64(b) +} + +// WriteString adds more data to d. It always returns len(s), nil. +// It may be faster than Write([]byte(s)) by avoiding a copy. +func (d *Digest) WriteString(s string) (n int, err error) { + d.Write(*(*[]byte)(unsafe.Pointer(&sliceHeader{s, len(s)}))) + // d.Write always returns len(s), nil. + // Ignoring the return output and returning these fixed values buys a + // savings of 6 in the inliner's cost model. + return len(s), nil +} + +// sliceHeader is similar to reflect.SliceHeader, but it assumes that the layout +// of the first two words is the same as the layout of a string. +type sliceHeader struct { + s string + cap int +} diff --git a/vendor/github.com/coder/websocket/.gitignore b/vendor/github.com/coder/websocket/.gitignore new file mode 100644 index 0000000..d1941b1 --- /dev/null +++ b/vendor/github.com/coder/websocket/.gitignore @@ -0,0 +1 @@ +PLAN.md diff --git a/vendor/github.com/coder/websocket/AGENTS.md b/vendor/github.com/coder/websocket/AGENTS.md new file mode 100644 index 0000000..711bc96 --- /dev/null +++ b/vendor/github.com/coder/websocket/AGENTS.md @@ -0,0 +1,159 @@ +# Agents + +This document helps AI agents work effectively in this codebase. It explains the philosophy, patterns, and pitfalls behind the code, so you can make good decisions on any task, not just scenarios explicitly covered. + +## Philosophy + +This is a minimal, idiomatic WebSocket library. Simplicity is a feature. + +Before adding code, articulate why it's necessary in one sentence. If you cannot justify the addition, it probably isn't needed. + +Before adding a dependency, don't. Tests requiring external packages are isolated in `internal/thirdparty`. + +## Workflow + +Every task follows phases. Do not skip phases; if you realize you missed something, return to the appropriate phase. + +**Making changes:** + +1. **Research** - Understand the problem and codebase before acting +2. **Plan** - Articulate your approach before implementing (when asked, or for complex changes) +3. **Implement** - Make changes in small, verifiable steps +4. **Verify** - Confirm correctness using external tools + +For trivial changes (typo fixes, comment updates), an abbreviated workflow is acceptable. + +## Research + +Research in sequential passes. Each pass has one focus. Don't skip ahead to code until you've completed the earlier passes. + +**Pass 1: Read the issue.** If you were given a link, read it now. Do not explore code, do not pass go. Fetch the linked issue or document first. Summarize what it asks for. If you cannot restate the problem, you are not ready to proceed. + +**Pass 2: Read linked references.** Follow every link in the issue: related issues, RFCs, external docs. Document what you learn. Code comments reference RFC 6455 (WebSocket), RFC 7692 (compression), and RFC 8441 (HTTP/2). + +**Pass 3: Trace the code.** Start from public API inward: `Accept` (server) or `Dial` (client) → `Conn` → `Reader`/`Writer`. Read tests for intent; the autobahn-testsuite (`autobahn_test.go`) validates protocol compliance. + +**Pass 4: Check both platforms.** Native Go files have `//go:build !js`. WASM lives in `ws_js.go`. Same API, different implementations. WASM wraps browser APIs and cannot control framing, compression, or masking. + +**Pass 5: Search exhaustively.** If the change affects a pattern used in multiple places, grep for all instances. Missing one creates inconsistent behavior. + +**Pass 6: Document unknowns.** List what you still don't know. Unknown unknowns become known unknowns when you ask "what am I still unsure about?" + +**After all passes:** Can you restate the problem in your own words? If not, return to Pass 1. Gaps in earlier passes will cause problems later. + +## Plan + +When asked to plan, write to `PLAN.md`. Write for someone else, not yourself; don't skip context you already know. + +**Pass 1: Document research.** Summarize what you learned in Research. Follow every reference; document findings so the implementer can verify. If the research section is empty, you haven't researched enough. + +**Pass 2: Consider approaches.** For non-trivial problems, enumerate at least two approaches. For each, note: what would change, what could go wrong, what's the tradeoff. + +**Pass 3: Detail the chosen approach.** Explain what and why, not step-by-step how. Point to specific files, functions, line numbers. Make claims verifiable. Leave room for the implementer to find a better solution. + +**Pass 4: List open questions.** What's still unclear? What assumptions are you making? What would change your approach? + +**After all passes:** Review from the implementer's perspective. Could they start work with only this document? If not, add what's missing. + +## Implement + +Implement in sequential passes. Don't write code until you've completed the verification passes. + +**Pass 1: Verify understanding.** Did you do your research? Can you state your approach in one sentence? If requirements are ambiguous, stop and ask. A wrong assumption wastes more time than a quick question. + +**Pass 2: Check scope.** Does this need to exist? Check if it already exists in the API. Is this the library's job or the user's job? The library handles protocol correctness; application concerns (reconnection, auth, routing) belong in user code. + +**Pass 3: Check invariants.** Walk through Key Invariants before writing code: + +- Reads: Will something still read from the connection? +- Pools: Will pooled objects be returned on all paths? +- Locks: Are you using context-aware `mu`, not `sync.Mutex`? +- Independence: Are you coupling reads and writes unnecessarily? + +**Pass 4: Implement.** Make the change. Every change needs a reason; if you can't articulate why it improves things, don't make it. Preserve existing comments unless you can prove they're wrong. + +**Pass 5: Verify examples.** Trace through usage examples as if writing real code. If an example wouldn't compile, the design is wrong. Check edge cases: what happens on error? On cancellation? + +**After all passes:** If feedback identifies a problem, fix that specific problem. Don't pivot to a new approach without articulating what failed and why the new approach avoids it. + +## Verify + +Verify using external signals. Self-assessment is unreliable; these tools are the ground truth. + +**Pass 1: Run tests.** `go test ./...` must pass. If tests fail, return to Research to understand why, not to Implement to "fix" it. + +**Pass 2: Run vet.** `go vet ./...` must report no issues. + +**Pass 3: Check platforms.** Code must compile on both native Go and WASM. API changes need both implementations; test that method signatures match. + +**Pass 4: Protocol compliance.** For protocol changes, run `AUTOBAHN=1 go test`. Compare wire bytes when implementations disagree; check against the RFC. + +**After all passes:** If any pass fails, fix the issue and restart from Pass 1. Don't consider a change complete until all passes succeed. + +## When Uncertain + +If confidence is low or requirements are ambiguous: + +1. State what you're uncertain about +2. Identify what information would resolve the uncertainty +3. Gather that information or ask for clarification + +Do not proceed with low-confidence assumptions. + +For complex changes, approach from multiple angles. If two approaches give different answers, that discrepancy demands resolution before proceeding. + +## Code Style + +Follow Go conventions: [Effective Go](https://go.dev/doc/effective_go), [Go Code Review Comments](https://go.dev/wiki/CodeReviewComments), and [Go Proverbs](https://go-proverbs.github.io/). Be concise, declarative, and factual. + +Never use emdash. Use commas, semicolons, or separate sentences. + +**Doc comments** start with the name and state what it does. Structure: `// [Name] [verb]s [what]. [Optional: when/why to use it].` Put useful information where users make decisions (usually the constructor, not methods). + +**Inline comments** are terse. Prefer end-of-line when short enough. + +**Explain why, not what.** The code shows what it does; comments should explain reasoning, non-obvious decisions, or edge cases. + +**Wrap comments** at ~80 characters, continuing naturally at word boundaries. + +**Naming matters.** Before proposing a name, stop and review existing names in the file. Ask: what would someone assume from this name? Does it fit with how similar things are named? A good name is accurate on its own and consistent in context. + +**Comment content:** + +- Add information beyond what the code shows (not tautologies) +- State directly: "Returns X" (not "Note that this returns X") +- Drop filler: "basically", "actually", "really" add nothing + +## Key Invariants + +**Always read from connections.** Control frames (ping, pong, close) arrive on the read path. A connection that never reads will miss them and misbehave. `CloseRead` exists for write-only patterns. + +**Pooled objects must be returned.** `flate.Writer` is ~1.2MB. Leaking them causes memory growth. Follow `get*()` / `put*()` patterns; return on all paths including errors. + +**Locks must respect context.** The `mu` type in `conn.go` unblocks when context cancels or connection closes. Using `sync.Mutex` for user-facing operations would block forever on stuck connections. + +**Reads and writes are independent.** They have separate locks (`readMu`, `writeFrameMu`) and can happen concurrently. Keep them decoupled. + +**Masking is asymmetric.** Clients mask payloads; servers don't. The mask is applied into the bufio.Writer buffer, not in-place on source bytes. + +## Commits and PRs + +Use conventional commits: `type(scope): description`. Scope is optional but include it when changes are constrained to a single file or directory. + +**Choose precise verbs:** `add` (new functionality), `fix` (broken behavior), `prevent` (undesirable state), `allow` (enable action), `handle` (edge cases), `improve` (performance/quality), `use` (change approach), `skip` (bypass), `remove` (delete), `rewrite` (substantial rework). + +**Before writing the commit message**, articulate what was wrong with the previous behavior and why this change fixes it. The commit message captures this reasoning. + +**Commit messages explain why.** State what was wrong, why it mattered, and why this solution was chosen. One to three sentences. Keep the tone neutral. + +**PR descriptions are for humans.** Explain what reviewers can't see: the why, alternatives considered, and tradeoffs made. Show evidence (logs, benchmarks, screenshots). Be explicit about what the PR doesn't do. + +**Link issues:** `Fixes #123` (PR resolves it), `Refs #123` (related), `Updates #123` (partial progress). + +## RFC References + +- RFC 6455: The WebSocket Protocol +- RFC 7692: Compression Extensions for WebSocket (permessage-deflate) +- RFC 8441: Bootstrapping WebSockets with HTTP/2 + +Section numbers in code comments refer to these RFCs. diff --git a/vendor/github.com/coder/websocket/LICENSE.txt b/vendor/github.com/coder/websocket/LICENSE.txt new file mode 100644 index 0000000..7e79329 --- /dev/null +++ b/vendor/github.com/coder/websocket/LICENSE.txt @@ -0,0 +1,13 @@ +Copyright (c) 2025 Coder + +Permission to use, copy, modify, and distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/coder/websocket/Makefile b/vendor/github.com/coder/websocket/Makefile new file mode 100644 index 0000000..a3e4a20 --- /dev/null +++ b/vendor/github.com/coder/websocket/Makefile @@ -0,0 +1,18 @@ +.PHONY: all +all: fmt lint test + +.PHONY: fmt +fmt: + ./ci/fmt.sh + +.PHONY: lint +lint: + ./ci/lint.sh + +.PHONY: test +test: + ./ci/test.sh + +.PHONY: bench +bench: + ./ci/bench.sh \ No newline at end of file diff --git a/vendor/github.com/coder/websocket/README.md b/vendor/github.com/coder/websocket/README.md new file mode 100644 index 0000000..3f174d5 --- /dev/null +++ b/vendor/github.com/coder/websocket/README.md @@ -0,0 +1,160 @@ +# websocket + +[![Go Reference](https://pkg.go.dev/badge/github.com/coder/websocket.svg)](https://pkg.go.dev/github.com/coder/websocket) +[![Go Coverage](https://coder.github.io/websocket/coverage.svg)](https://coder.github.io/websocket/coverage.html) + +websocket is a minimal and idiomatic WebSocket library for Go. + +## Install + +```sh +go get github.com/coder/websocket +``` + +> [!NOTE] +> Coder now maintains this project as explained in [this blog post](https://coder.com/blog/websocket). +> We're grateful to [nhooyr](https://github.com/nhooyr) for authoring and maintaining this project from +> 2019 to 2024. + +## Highlights + +- Minimal and idiomatic API +- First class [context.Context](https://blog.golang.org/context) support +- Fully passes the WebSocket [autobahn-testsuite](https://github.com/crossbario/autobahn-testsuite) +- [Zero dependencies](https://pkg.go.dev/github.com/coder/websocket?tab=imports) +- JSON helpers in the [wsjson](https://pkg.go.dev/github.com/coder/websocket/wsjson) subpackage +- Zero alloc reads and writes +- Concurrent writes +- [Close handshake](https://pkg.go.dev/github.com/coder/websocket#Conn.Close) +- [net.Conn](https://pkg.go.dev/github.com/coder/websocket#NetConn) wrapper +- [Ping pong](https://pkg.go.dev/github.com/coder/websocket#Conn.Ping) API +- [RFC 7692](https://tools.ietf.org/html/rfc7692) permessage-deflate compression +- [CloseRead](https://pkg.go.dev/github.com/coder/websocket#Conn.CloseRead) helper for write only connections +- Compile to [Wasm](https://pkg.go.dev/github.com/coder/websocket#hdr-Wasm) + +## Roadmap + +See GitHub issues for minor issues but the major future enhancements are: + +- [ ] Perfect examples [#217](https://github.com/coder/websocket/issues/217) +- [ ] wstest.Pipe for in memory testing [#340](https://github.com/coder/websocket/issues/340) +- [ ] Ping pong heartbeat helper [#267](https://github.com/coder/websocket/issues/267) +- [ ] Ping pong instrumentation callbacks [#246](https://github.com/coder/websocket/issues/246) +- [ ] Graceful shutdown helpers [#209](https://github.com/coder/websocket/issues/209) +- [ ] Assembly for WebSocket masking [#16](https://github.com/coder/websocket/issues/16) + - WIP at [#326](https://github.com/coder/websocket/pull/326), about 3x faster +- [ ] HTTP/2 [#4](https://github.com/coder/websocket/issues/4) +- [ ] The holy grail [#402](https://github.com/coder/websocket/issues/402) + +## Examples + +For a production quality example that demonstrates the complete API, see the +[echo example](./internal/examples/echo). + +For a full stack example, see the [chat example](./internal/examples/chat). + +### Server + +```go +http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) { + c, err := websocket.Accept(w, r, nil) + if err != nil { + // ... + } + defer c.CloseNow() + + // Set the context as needed. Use of r.Context() is not recommended + // to avoid surprising behavior (see http.Hijacker). + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + var v any + err = wsjson.Read(ctx, c, &v) + if err != nil { + // ... + } + + log.Printf("received: %v", v) + + c.Close(websocket.StatusNormalClosure, "") +}) +``` + +### Client + +```go +ctx, cancel := context.WithTimeout(context.Background(), time.Minute) +defer cancel() + +c, _, err := websocket.Dial(ctx, "ws://localhost:8080", nil) +if err != nil { + // ... +} +defer c.CloseNow() + +err = wsjson.Write(ctx, c, "hi") +if err != nil { + // ... +} + +c.Close(websocket.StatusNormalClosure, "") +``` + +## Comparison + +### gorilla/websocket + +Advantages of [gorilla/websocket](https://github.com/gorilla/websocket): + +- Mature and widely used +- [Prepared writes](https://pkg.go.dev/github.com/gorilla/websocket#PreparedMessage) +- Configurable [buffer sizes](https://pkg.go.dev/github.com/gorilla/websocket#hdr-Buffers) + +Advantages of github.com/coder/websocket: + +- Minimal and idiomatic API + - Compare godoc of [github.com/coder/websocket](https://pkg.go.dev/github.com/coder/websocket) with [gorilla/websocket](https://pkg.go.dev/github.com/gorilla/websocket) side by side. +- [net.Conn](https://pkg.go.dev/github.com/coder/websocket#NetConn) wrapper +- Zero alloc reads and writes ([gorilla/websocket#535](https://github.com/gorilla/websocket/issues/535)) +- Full [context.Context](https://blog.golang.org/context) support +- Dial uses [net/http.Client](https://golang.org/pkg/net/http/#Client) + - Will enable easy HTTP/2 support in the future + - Gorilla writes directly to a net.Conn and so duplicates features of net/http.Client. +- Concurrent writes +- Close handshake ([gorilla/websocket#448](https://github.com/gorilla/websocket/issues/448)) +- Idiomatic [ping pong](https://pkg.go.dev/github.com/coder/websocket#Conn.Ping) API + - Gorilla requires registering a pong callback before sending a Ping +- Can target Wasm ([gorilla/websocket#432](https://github.com/gorilla/websocket/issues/432)) +- Transparent message buffer reuse with [wsjson](https://pkg.go.dev/github.com/coder/websocket/wsjson) subpackage +- [1.75x](https://github.com/coder/websocket/releases/tag/v1.7.4) faster WebSocket masking implementation in pure Go + - Gorilla's implementation is slower and uses [unsafe](https://golang.org/pkg/unsafe/). + Soon we'll have assembly and be 3x faster [#326](https://github.com/coder/websocket/pull/326) +- Full [permessage-deflate](https://tools.ietf.org/html/rfc7692) compression extension support + - Gorilla only supports no context takeover mode +- [CloseRead](https://pkg.go.dev/github.com/coder/websocket#Conn.CloseRead) helper for write only connections ([gorilla/websocket#492](https://github.com/gorilla/websocket/issues/492)) + +#### golang.org/x/net/websocket + +[golang.org/x/net/websocket](https://pkg.go.dev/golang.org/x/net/websocket) is deprecated. +See [golang/go/issues/18152](https://github.com/golang/go/issues/18152). + +The [net.Conn](https://pkg.go.dev/github.com/coder/websocket#NetConn) can help in transitioning +to github.com/coder/websocket. + +#### gobwas/ws + +[gobwas/ws](https://github.com/gobwas/ws) has an extremely flexible API that allows it to be used +in an event driven style for performance. See the author's [blog post](https://medium.freecodecamp.org/million-websockets-and-go-cc58418460bb). + +However it is quite bloated. See https://pkg.go.dev/github.com/gobwas/ws + +When writing idiomatic Go, github.com/coder/websocket will be faster and easier to use. + +#### lesismal/nbio + +[lesismal/nbio](https://github.com/lesismal/nbio) is similar to gobwas/ws in that the API is +event driven for performance reasons. + +However it is quite bloated. See https://pkg.go.dev/github.com/lesismal/nbio + +When writing idiomatic Go, github.com/coder/websocket will be faster and easier to use. diff --git a/vendor/github.com/coder/websocket/accept.go b/vendor/github.com/coder/websocket/accept.go new file mode 100644 index 0000000..bcfd38e --- /dev/null +++ b/vendor/github.com/coder/websocket/accept.go @@ -0,0 +1,378 @@ +//go:build !js + +package websocket + +import ( + "bytes" + "context" + "crypto/sha1" + "encoding/base64" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/textproto" + "net/url" + "path" + "strings" + + "github.com/coder/websocket/internal/errd" +) + +// AcceptOptions represents Accept's options. +type AcceptOptions struct { + // Subprotocols lists the WebSocket subprotocols that Accept will negotiate with the client. + // The empty subprotocol will always be negotiated as per RFC 6455. If you would like to + // reject it, close the connection when c.Subprotocol() == "". + Subprotocols []string + + // InsecureSkipVerify is used to disable Accept's origin verification behaviour. + // + // You probably want to use OriginPatterns instead. + InsecureSkipVerify bool + + // OriginPatterns lists the host patterns for authorized origins. + // The request host is always authorized. + // Use this to enable cross origin WebSockets. + // + // i.e javascript running on example.com wants to access a WebSocket server at chat.example.com. + // In such a case, example.com is the origin and chat.example.com is the request host. + // One would set this field to []string{"example.com"} to authorize example.com to connect. + // + // Each pattern is matched case insensitively with path.Match (see + // https://golang.org/pkg/path/#Match). By default, it is matched + // against the request origin host. If the pattern contains a URI + // scheme ("://"), it will be matched against "scheme://host". + // + // Please ensure you understand the ramifications of enabling this. + // If used incorrectly your WebSocket server will be open to CSRF attacks. + // + // Do not use * as a pattern to allow any origin, prefer to use InsecureSkipVerify instead + // to bring attention to the danger of such a setting. + OriginPatterns []string + + // CompressionMode controls the compression mode. + // Defaults to CompressionDisabled. + // + // See docs on CompressionMode for details. + CompressionMode CompressionMode + + // CompressionThreshold controls the minimum size of a message before compression is applied. + // + // Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes + // for CompressionContextTakeover. + CompressionThreshold int + + // OnPingReceived is an optional callback invoked synchronously when a ping frame is received. + // + // The payload contains the application data of the ping frame. + // If the callback returns false, the subsequent pong frame will not be sent. + // To avoid blocking, any expensive processing should be performed asynchronously using a goroutine. + OnPingReceived func(ctx context.Context, payload []byte) bool + + // OnPongReceived is an optional callback invoked synchronously when a pong frame is received. + // + // The payload contains the application data of the pong frame. + // To avoid blocking, any expensive processing should be performed asynchronously using a goroutine. + // + // Unlike OnPingReceived, this callback does not return a value because a pong frame + // is a response to a ping and does not trigger any further frame transmission. + OnPongReceived func(ctx context.Context, payload []byte) +} + +func (opts *AcceptOptions) cloneWithDefaults() *AcceptOptions { + var o AcceptOptions + if opts != nil { + o = *opts + } + return &o +} + +// Accept accepts a WebSocket handshake from a client and upgrades the +// connection to a WebSocket. +// +// Accept will not allow cross origin requests by default. +// See the InsecureSkipVerify and OriginPatterns options to allow cross origin requests. +// +// Accept will write a response to w on all errors. +// +// Note that using the http.Request Context after Accept returns may lead to +// unexpected behavior (see http.Hijacker). +func Accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (*Conn, error) { + return accept(w, r, opts) +} + +func accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (_ *Conn, err error) { + defer errd.Wrap(&err, "failed to accept WebSocket connection") + + errCode, err := verifyClientRequest(w, r) + if err != nil { + http.Error(w, err.Error(), errCode) + return nil, err + } + + opts = opts.cloneWithDefaults() + if !opts.InsecureSkipVerify { + err = authenticateOrigin(r, opts.OriginPatterns) + if err != nil { + if errors.Is(err, path.ErrBadPattern) { + log.Printf("websocket: %v", err) + err = errors.New(http.StatusText(http.StatusForbidden)) + } + http.Error(w, err.Error(), http.StatusForbidden) + return nil, err + } + } + + hj, ok := hijacker(w) + if !ok { + err = errors.New("http.ResponseWriter does not implement http.Hijacker") + http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented) + return nil, err + } + + w.Header().Set("Upgrade", "websocket") + w.Header().Set("Connection", "Upgrade") + + key := r.Header.Get("Sec-WebSocket-Key") + w.Header().Set("Sec-WebSocket-Accept", secWebSocketAccept(key)) + + subproto := selectSubprotocol(r, opts.Subprotocols) + if subproto != "" { + w.Header().Set("Sec-WebSocket-Protocol", subproto) + } + + copts, ok := selectDeflate(websocketExtensions(r.Header), opts.CompressionMode) + if ok { + w.Header().Set("Sec-WebSocket-Extensions", copts.String()) + } + + w.WriteHeader(http.StatusSwitchingProtocols) + // See https://github.com/nhooyr/websocket/issues/166 + if ginWriter, ok := w.(interface { + WriteHeaderNow() + }); ok { + ginWriter.WriteHeaderNow() + } + + netConn, brw, err := hj.Hijack() + if err != nil { + err = fmt.Errorf("failed to hijack connection: %w", err) + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return nil, err + } + + // https://github.com/golang/go/issues/32314 + b, _ := brw.Reader.Peek(brw.Reader.Buffered()) + brw.Reader.Reset(io.MultiReader(bytes.NewReader(b), netConn)) + + return newConn(connConfig{ + subprotocol: w.Header().Get("Sec-WebSocket-Protocol"), + rwc: netConn, + client: false, + copts: copts, + flateThreshold: opts.CompressionThreshold, + onPingReceived: opts.OnPingReceived, + onPongReceived: opts.OnPongReceived, + + br: brw.Reader, + bw: brw.Writer, + }), nil +} + +func verifyClientRequest(w http.ResponseWriter, r *http.Request) (errCode int, _ error) { + if !r.ProtoAtLeast(1, 1) { + return http.StatusUpgradeRequired, fmt.Errorf("WebSocket protocol violation: handshake request must be at least HTTP/1.1: %q", r.Proto) + } + + if !headerContainsTokenIgnoreCase(r.Header, "Connection", "Upgrade") { + w.Header().Set("Connection", "Upgrade") + w.Header().Set("Upgrade", "websocket") + return http.StatusUpgradeRequired, fmt.Errorf("WebSocket protocol violation: Connection header %q does not contain Upgrade", r.Header.Get("Connection")) + } + + if !headerContainsTokenIgnoreCase(r.Header, "Upgrade", "websocket") { + w.Header().Set("Connection", "Upgrade") + w.Header().Set("Upgrade", "websocket") + return http.StatusUpgradeRequired, fmt.Errorf("WebSocket protocol violation: Upgrade header %q does not contain websocket", r.Header.Get("Upgrade")) + } + + if r.Method != "GET" { + return http.StatusMethodNotAllowed, fmt.Errorf("WebSocket protocol violation: handshake request method is not GET but %q", r.Method) + } + + if r.Header.Get("Sec-WebSocket-Version") != "13" { + w.Header().Set("Sec-WebSocket-Version", "13") + return http.StatusBadRequest, fmt.Errorf("unsupported WebSocket protocol version (only 13 is supported): %q", r.Header.Get("Sec-WebSocket-Version")) + } + + websocketSecKeys := r.Header.Values("Sec-WebSocket-Key") + if len(websocketSecKeys) == 0 { + return http.StatusBadRequest, errors.New("WebSocket protocol violation: missing Sec-WebSocket-Key") + } + + if len(websocketSecKeys) > 1 { + return http.StatusBadRequest, errors.New("WebSocket protocol violation: multiple Sec-WebSocket-Key headers") + } + + // The RFC states to remove any leading or trailing whitespace. + websocketSecKey := strings.TrimSpace(websocketSecKeys[0]) + if v, err := base64.StdEncoding.DecodeString(websocketSecKey); err != nil || len(v) != 16 { + return http.StatusBadRequest, fmt.Errorf("WebSocket protocol violation: invalid Sec-WebSocket-Key %q, must be a 16 byte base64 encoded string", websocketSecKey) + } + + return 0, nil +} + +func authenticateOrigin(r *http.Request, originHosts []string) error { + origin := r.Header.Get("Origin") + if origin == "" { + return nil + } + + u, err := url.Parse(origin) + if err != nil { + return fmt.Errorf("failed to parse Origin header %q: %w", origin, err) + } + + if strings.EqualFold(r.Host, u.Host) { + return nil + } + + for _, hostPattern := range originHosts { + target := u.Host + if strings.Contains(hostPattern, "://") { + target = u.Scheme + "://" + u.Host + } + matched, err := match(hostPattern, target) + if err != nil { + return fmt.Errorf("failed to parse path pattern %q: %w", hostPattern, err) + } + if matched { + return nil + } + } + if u.Host == "" { + return fmt.Errorf("request Origin %q is not a valid URL with a host", origin) + } + return fmt.Errorf("request Origin %q is not authorized for Host %q", u.Host, r.Host) +} + +func match(pattern, s string) (bool, error) { + return path.Match(strings.ToLower(pattern), strings.ToLower(s)) +} + +func selectSubprotocol(r *http.Request, subprotocols []string) string { + cps := headerTokens(r.Header, "Sec-WebSocket-Protocol") + for _, sp := range subprotocols { + for _, cp := range cps { + if strings.EqualFold(sp, cp) { + return cp + } + } + } + return "" +} + +func selectDeflate(extensions []websocketExtension, mode CompressionMode) (*compressionOptions, bool) { + if mode == CompressionDisabled { + return nil, false + } + for _, ext := range extensions { + switch ext.name { + // We used to implement x-webkit-deflate-frame too for Safari but Safari has bugs... + // See https://github.com/nhooyr/websocket/issues/218 + case "permessage-deflate": + copts, ok := acceptDeflate(ext, mode) + if ok { + return copts, true + } + } + } + return nil, false +} + +func acceptDeflate(ext websocketExtension, mode CompressionMode) (*compressionOptions, bool) { + copts := mode.opts() + for _, p := range ext.params { + switch p { + case "client_no_context_takeover": + copts.clientNoContextTakeover = true + continue + case "server_no_context_takeover": + copts.serverNoContextTakeover = true + continue + case "client_max_window_bits", + "server_max_window_bits=15": + continue + } + + if strings.HasPrefix(p, "client_max_window_bits=") { + // We can't adjust the deflate window, but decoding with a larger window is acceptable. + continue + } + return nil, false + } + return copts, true +} + +func headerContainsTokenIgnoreCase(h http.Header, key, token string) bool { + for _, t := range headerTokens(h, key) { + if strings.EqualFold(t, token) { + return true + } + } + return false +} + +type websocketExtension struct { + name string + params []string +} + +func websocketExtensions(h http.Header) []websocketExtension { + var exts []websocketExtension + extStrs := headerTokens(h, "Sec-WebSocket-Extensions") + for _, extStr := range extStrs { + if extStr == "" { + continue + } + + vals := strings.Split(extStr, ";") + for i := range vals { + vals[i] = strings.TrimSpace(vals[i]) + } + + e := websocketExtension{ + name: vals[0], + params: vals[1:], + } + + exts = append(exts, e) + } + return exts +} + +func headerTokens(h http.Header, key string) []string { + key = textproto.CanonicalMIMEHeaderKey(key) + var tokens []string + for _, v := range h[key] { + v = strings.TrimSpace(v) + for _, t := range strings.Split(v, ",") { + t = strings.TrimSpace(t) + tokens = append(tokens, t) + } + } + return tokens +} + +var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11") + +func secWebSocketAccept(secWebSocketKey string) string { + h := sha1.New() + h.Write([]byte(secWebSocketKey)) + h.Write(keyGUID) + + return base64.StdEncoding.EncodeToString(h.Sum(nil)) +} diff --git a/vendor/github.com/coder/websocket/close.go b/vendor/github.com/coder/websocket/close.go new file mode 100644 index 0000000..fcc6806 --- /dev/null +++ b/vendor/github.com/coder/websocket/close.go @@ -0,0 +1,335 @@ +//go:build !js + +package websocket + +import ( + "context" + "encoding/binary" + "errors" + "fmt" + "net" + "time" + + "github.com/coder/websocket/internal/errd" +) + +// StatusCode represents a WebSocket status code. +// https://tools.ietf.org/html/rfc6455#section-7.4 +type StatusCode int + +// https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number +// +// These are only the status codes defined by the protocol. +// +// You can define custom codes in the 3000-4999 range. +// The 3000-3999 range is reserved for use by libraries, frameworks and applications. +// The 4000-4999 range is reserved for private use. +const ( + StatusNormalClosure StatusCode = 1000 + StatusGoingAway StatusCode = 1001 + StatusProtocolError StatusCode = 1002 + StatusUnsupportedData StatusCode = 1003 + + // 1004 is reserved and so unexported. + statusReserved StatusCode = 1004 + + // StatusNoStatusRcvd cannot be sent in a close message. + // It is reserved for when a close message is received without + // a status code. + StatusNoStatusRcvd StatusCode = 1005 + + // StatusAbnormalClosure is exported for use only with Wasm. + // In non Wasm Go, the returned error will indicate whether the + // connection was closed abnormally. + StatusAbnormalClosure StatusCode = 1006 + + StatusInvalidFramePayloadData StatusCode = 1007 + StatusPolicyViolation StatusCode = 1008 + StatusMessageTooBig StatusCode = 1009 + StatusMandatoryExtension StatusCode = 1010 + StatusInternalError StatusCode = 1011 + StatusServiceRestart StatusCode = 1012 + StatusTryAgainLater StatusCode = 1013 + StatusBadGateway StatusCode = 1014 + + // StatusTLSHandshake is only exported for use with Wasm. + // In non Wasm Go, the returned error will indicate whether there was + // a TLS handshake failure. + StatusTLSHandshake StatusCode = 1015 +) + +// CloseError is returned when the connection is closed with a status and reason. +// +// Use Go 1.13's errors.As to check for this error. +// Also see the CloseStatus helper. +type CloseError struct { + Code StatusCode + Reason string +} + +func (ce CloseError) Error() string { + return fmt.Sprintf("status = %v and reason = %q", ce.Code, ce.Reason) +} + +// CloseStatus is a convenience wrapper around Go 1.13's errors.As to grab +// the status code from a CloseError. +// +// -1 will be returned if the passed error is nil or not a CloseError. +func CloseStatus(err error) StatusCode { + var ce CloseError + if errors.As(err, &ce) { + return ce.Code + } + return -1 +} + +// Close performs the WebSocket close handshake with the given status code and reason. +// +// It will write a WebSocket close frame with a timeout of 5s and then wait 5s for +// the peer to send a close frame. +// All data messages received from the peer during the close handshake will be discarded. +// +// The connection can only be closed once. Additional calls to Close +// are no-ops. +// +// The maximum length of reason must be 125 bytes. Avoid sending a dynamic reason. +// +// Close will unblock all goroutines interacting with the connection once +// complete. +func (c *Conn) Close(code StatusCode, reason string) (err error) { + defer errd.Wrap(&err, "failed to close WebSocket") + + if c.casClosing() { + err = c.waitGoroutines() + if err != nil { + return err + } + return net.ErrClosed + } + defer func() { + if errors.Is(err, net.ErrClosed) { + err = nil + } + }() + + err = c.closeHandshake(code, reason) + + err2 := c.close() + if err == nil && err2 != nil { + err = err2 + } + + err2 = c.waitGoroutines() + if err == nil && err2 != nil { + err = err2 + } + + return err +} + +// CloseNow closes the WebSocket connection without attempting a close handshake. +// Use when you do not want the overhead of the close handshake. +func (c *Conn) CloseNow() (err error) { + defer errd.Wrap(&err, "failed to immediately close WebSocket") + + if c.casClosing() { + err = c.waitGoroutines() + if err != nil { + return err + } + return net.ErrClosed + } + defer func() { + if errors.Is(err, net.ErrClosed) { + err = nil + } + }() + + err = c.close() + + err2 := c.waitGoroutines() + if err == nil && err2 != nil { + err = err2 + } + return err +} + +func (c *Conn) closeHandshake(code StatusCode, reason string) error { + err := c.writeClose(code, reason) + if err != nil { + return err + } + + err = c.waitCloseHandshake() + if CloseStatus(err) != code { + return err + } + return nil +} + +func (c *Conn) writeClose(code StatusCode, reason string) error { + ce := CloseError{ + Code: code, + Reason: reason, + } + + var p []byte + var err error + if ce.Code != StatusNoStatusRcvd { + p, err = ce.bytes() + if err != nil { + return err + } + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + + err = c.writeControl(ctx, opClose, p) + // If the connection closed as we're writing we ignore the error as we might + // have written the close frame, the peer responded and then someone else read it + // and closed the connection. + if err != nil && !errors.Is(err, net.ErrClosed) { + return err + } + return nil +} + +func (c *Conn) waitCloseHandshake() error { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + + err := c.readMu.lock(ctx) + if err != nil { + return err + } + defer c.readMu.unlock() + + for i := int64(0); i < c.msgReader.payloadLength; i++ { + _, err := c.br.ReadByte() + if err != nil { + return err + } + } + + for { + h, err := c.readLoop(ctx) + if err != nil { + return err + } + + for i := int64(0); i < h.payloadLength; i++ { + _, err := c.br.ReadByte() + if err != nil { + return err + } + } + } +} + +func (c *Conn) waitGoroutines() error { + t := time.NewTimer(time.Second * 15) + defer t.Stop() + + c.closeReadMu.Lock() + closeRead := c.closeReadCtx != nil + c.closeReadMu.Unlock() + if closeRead { + select { + case <-c.closeReadDone: + case <-t.C: + return errors.New("failed to wait for close read goroutine to exit") + } + } + + select { + case <-c.closed: + case <-t.C: + return errors.New("failed to wait for connection to be closed") + } + + return nil +} + +func parseClosePayload(p []byte) (CloseError, error) { + if len(p) == 0 { + return CloseError{ + Code: StatusNoStatusRcvd, + }, nil + } + + if len(p) < 2 { + return CloseError{}, fmt.Errorf("close payload %q too small, cannot even contain the 2 byte status code", p) + } + + ce := CloseError{ + Code: StatusCode(binary.BigEndian.Uint16(p)), + Reason: string(p[2:]), + } + + if !validWireCloseCode(ce.Code) { + return CloseError{}, fmt.Errorf("invalid status code %v", ce.Code) + } + + return ce, nil +} + +// See http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number +// and https://tools.ietf.org/html/rfc6455#section-7.4.1 +func validWireCloseCode(code StatusCode) bool { + switch code { + case statusReserved, StatusNoStatusRcvd, StatusAbnormalClosure, StatusTLSHandshake: + return false + } + + if code >= StatusNormalClosure && code <= StatusBadGateway { + return true + } + if code >= 3000 && code <= 4999 { + return true + } + + return false +} + +func (ce CloseError) bytes() ([]byte, error) { + p, err := ce.bytesErr() + if err != nil { + err = fmt.Errorf("failed to marshal close frame: %w", err) + ce = CloseError{ + Code: StatusInternalError, + } + p, _ = ce.bytesErr() + } + return p, err +} + +const maxCloseReason = maxControlPayload - 2 + +func (ce CloseError) bytesErr() ([]byte, error) { + if len(ce.Reason) > maxCloseReason { + return nil, fmt.Errorf("reason string max is %v but got %q with length %v", maxCloseReason, ce.Reason, len(ce.Reason)) + } + + if !validWireCloseCode(ce.Code) { + return nil, fmt.Errorf("status code %v cannot be set", ce.Code) + } + + buf := make([]byte, 2+len(ce.Reason)) + binary.BigEndian.PutUint16(buf, uint16(ce.Code)) + copy(buf[2:], ce.Reason) + return buf, nil +} + +func (c *Conn) casClosing() bool { + return c.closing.Swap(true) +} + +func (c *Conn) isClosed() bool { + select { + case <-c.closed: + return true + default: + return false + } +} diff --git a/vendor/github.com/coder/websocket/compress.go b/vendor/github.com/coder/websocket/compress.go new file mode 100644 index 0000000..41bd5bd --- /dev/null +++ b/vendor/github.com/coder/websocket/compress.go @@ -0,0 +1,234 @@ +//go:build !js + +package websocket + +import ( + "compress/flate" + "io" + "sync" +) + +// CompressionMode represents the modes available to the permessage-deflate extension. +// See https://tools.ietf.org/html/rfc7692 +// +// Works in all modern browsers except Safari which does not implement the permessage-deflate extension. +// +// Compression is only used if the peer supports the mode selected. +type CompressionMode int + +const ( + // CompressionDisabled disables the negotiation of the permessage-deflate extension. + // + // This is the default. Do not enable compression without benchmarking for your particular use case first. + CompressionDisabled CompressionMode = iota + + // CompressionContextTakeover compresses each message greater than 128 bytes reusing the 32 KB sliding window from + // previous messages. i.e compression context across messages is preserved. + // + // As most WebSocket protocols are text based and repetitive, this compression mode can be very efficient. + // + // The memory overhead is a fixed 32 KB sliding window, a fixed 1.2 MB flate.Writer and a sync.Pool of 40 KB flate.Reader's + // that are used when reading and then returned. + // + // Thus, it uses more memory than CompressionNoContextTakeover but compresses more efficiently. + // + // If the peer does not support CompressionContextTakeover then we will fall back to CompressionNoContextTakeover. + CompressionContextTakeover + + // CompressionNoContextTakeover compresses each message greater than 512 bytes. Each message is compressed with + // a new 1.2 MB flate.Writer pulled from a sync.Pool. Each message is read with a 40 KB flate.Reader pulled from + // a sync.Pool. + // + // This means less efficient compression as the sliding window from previous messages will not be used but the + // memory overhead will be lower as there will be no fixed cost for the flate.Writer nor the 32 KB sliding window. + // Especially if the connections are long lived and seldom written to. + // + // Thus, it uses less memory than CompressionContextTakeover but compresses less efficiently. + // + // If the peer does not support CompressionNoContextTakeover then we will fall back to CompressionDisabled. + CompressionNoContextTakeover +) + +func (m CompressionMode) opts() *compressionOptions { + return &compressionOptions{ + clientNoContextTakeover: m == CompressionNoContextTakeover, + serverNoContextTakeover: m == CompressionNoContextTakeover, + } +} + +type compressionOptions struct { + clientNoContextTakeover bool + serverNoContextTakeover bool +} + +func (copts *compressionOptions) String() string { + s := "permessage-deflate" + if copts.clientNoContextTakeover { + s += "; client_no_context_takeover" + } + if copts.serverNoContextTakeover { + s += "; server_no_context_takeover" + } + return s +} + +// These bytes are required to get flate.Reader to return. +// They are removed when sending to avoid the overhead as +// WebSocket framing tell's when the message has ended but then +// we need to add them back otherwise flate.Reader keeps +// trying to read more bytes. +const deflateMessageTail = "\x00\x00\xff\xff" + +type trimLastFourBytesWriter struct { + w io.Writer + tail []byte +} + +func (tw *trimLastFourBytesWriter) reset() { + if tw != nil && tw.tail != nil { + tw.tail = tw.tail[:0] + } +} + +func (tw *trimLastFourBytesWriter) Write(p []byte) (int, error) { + if tw.tail == nil { + tw.tail = make([]byte, 0, 4) + } + + extra := len(tw.tail) + len(p) - 4 + + if extra <= 0 { + tw.tail = append(tw.tail, p...) + return len(p), nil + } + + // Now we need to write as many extra bytes as we can from the previous tail. + if extra > len(tw.tail) { + extra = len(tw.tail) + } + if extra > 0 { + _, err := tw.w.Write(tw.tail[:extra]) + if err != nil { + return 0, err + } + + // Shift remaining bytes in tail over. + n := copy(tw.tail, tw.tail[extra:]) + tw.tail = tw.tail[:n] + } + + // If p is less than or equal to 4 bytes, + // all of it is is part of the tail. + if len(p) <= 4 { + tw.tail = append(tw.tail, p...) + return len(p), nil + } + + // Otherwise, only the last 4 bytes are. + tw.tail = append(tw.tail, p[len(p)-4:]...) + + p = p[:len(p)-4] + n, err := tw.w.Write(p) + return n + 4, err +} + +var flateReaderPool sync.Pool + +func getFlateReader(r io.Reader, dict []byte) io.Reader { + fr, ok := flateReaderPool.Get().(io.Reader) + if !ok { + return flate.NewReaderDict(r, dict) + } + fr.(flate.Resetter).Reset(r, dict) + return fr +} + +func putFlateReader(fr io.Reader) { + flateReaderPool.Put(fr) +} + +var flateWriterPool sync.Pool + +func getFlateWriter(w io.Writer) *flate.Writer { + fw, ok := flateWriterPool.Get().(*flate.Writer) + if !ok { + fw, _ = flate.NewWriter(w, flate.BestSpeed) + return fw + } + fw.Reset(w) + return fw +} + +func putFlateWriter(w *flate.Writer) { + flateWriterPool.Put(w) +} + +type slidingWindow struct { + buf []byte +} + +var ( + swPoolMu sync.RWMutex + swPool = map[int]*sync.Pool{} +) + +func slidingWindowPool(n int) *sync.Pool { + swPoolMu.RLock() + p, ok := swPool[n] + swPoolMu.RUnlock() + if ok { + return p + } + + p = &sync.Pool{} + + swPoolMu.Lock() + swPool[n] = p + swPoolMu.Unlock() + + return p +} + +func (sw *slidingWindow) init(n int) { + if sw.buf != nil { + return + } + + if n == 0 { + n = 32768 + } + + p := slidingWindowPool(n) + sw2, ok := p.Get().(*slidingWindow) + if ok { + *sw = *sw2 + } else { + sw.buf = make([]byte, 0, n) + } +} + +func (sw *slidingWindow) close() { + sw.buf = sw.buf[:0] + swPoolMu.Lock() + swPool[cap(sw.buf)].Put(sw) + swPoolMu.Unlock() +} + +func (sw *slidingWindow) write(p []byte) { + if len(p) >= cap(sw.buf) { + sw.buf = sw.buf[:cap(sw.buf)] + p = p[len(p)-cap(sw.buf):] + copy(sw.buf, p) + return + } + + left := cap(sw.buf) - len(sw.buf) + if left < len(p) { + // We need to shift spaceNeeded bytes from the end to make room for p at the end. + spaceNeeded := len(p) - left + copy(sw.buf, sw.buf[spaceNeeded:]) + sw.buf = sw.buf[:len(sw.buf)-spaceNeeded] + } + + sw.buf = append(sw.buf, p...) +} diff --git a/vendor/github.com/coder/websocket/conn.go b/vendor/github.com/coder/websocket/conn.go new file mode 100644 index 0000000..bfc78aa --- /dev/null +++ b/vendor/github.com/coder/websocket/conn.go @@ -0,0 +1,316 @@ +//go:build !js + +package websocket + +import ( + "bufio" + "context" + "fmt" + "io" + "net" + "runtime" + "strconv" + "sync" + "sync/atomic" +) + +// MessageType represents the type of a WebSocket message. +// See https://tools.ietf.org/html/rfc6455#section-5.6 +type MessageType int + +// MessageType constants. +const ( + // MessageText is for UTF-8 encoded text messages like JSON. + MessageText MessageType = iota + 1 + // MessageBinary is for binary messages like protobufs. + MessageBinary +) + +// Conn represents a WebSocket connection. +// All methods may be called concurrently except for Reader and Read. +// +// You must always read from the connection. Otherwise control +// frames will not be handled. See Reader and CloseRead. +// +// Be sure to call Close on the connection when you +// are finished with it to release associated resources. +// +// On any error from any method, the connection is closed +// with an appropriate reason. +// +// This applies to context expirations as well unfortunately. +// See https://github.com/nhooyr/websocket/issues/242#issuecomment-633182220 +type Conn struct { + noCopy noCopy + + subprotocol string + rwc io.ReadWriteCloser + client bool + copts *compressionOptions + flateThreshold int + br *bufio.Reader + bw *bufio.Writer + + readTimeoutStop atomic.Pointer[func() bool] + writeTimeoutStop atomic.Pointer[func() bool] + + // Read state. + readMu *mu + readHeaderBuf [8]byte + readControlBuf [maxControlPayload]byte + msgReader *msgReader + + // Write state. + msgWriter *msgWriter + writeFrameMu *mu + writeBuf []byte + writeHeaderBuf [8]byte + writeHeader header + + // Close handshake state. + closeStateMu sync.RWMutex + closeReceivedErr error + closeSentErr error + + // CloseRead state. + closeReadMu sync.Mutex + closeReadCtx context.Context + closeReadDone chan struct{} + + closing atomic.Bool + closeMu sync.Mutex // Protects following. + closed chan struct{} + + pingCounter atomic.Int64 + activePingsMu sync.Mutex + activePings map[string]chan<- struct{} + onPingReceived func(context.Context, []byte) bool + onPongReceived func(context.Context, []byte) +} + +type connConfig struct { + subprotocol string + rwc io.ReadWriteCloser + client bool + copts *compressionOptions + flateThreshold int + onPingReceived func(context.Context, []byte) bool + onPongReceived func(context.Context, []byte) + + br *bufio.Reader + bw *bufio.Writer +} + +func newConn(cfg connConfig) *Conn { + c := &Conn{ + subprotocol: cfg.subprotocol, + rwc: cfg.rwc, + client: cfg.client, + copts: cfg.copts, + flateThreshold: cfg.flateThreshold, + + br: cfg.br, + bw: cfg.bw, + + closed: make(chan struct{}), + activePings: make(map[string]chan<- struct{}), + onPingReceived: cfg.onPingReceived, + onPongReceived: cfg.onPongReceived, + } + + c.readMu = newMu(c) + c.writeFrameMu = newMu(c) + + c.msgReader = newMsgReader(c) + + c.msgWriter = newMsgWriter(c) + if c.client { + c.writeBuf = extractBufioWriterBuf(c.bw, c.rwc) + } + + if c.flate() && c.flateThreshold == 0 { + c.flateThreshold = 128 + if !c.msgWriter.flateContextTakeover() { + c.flateThreshold = 512 + } + } + + runtime.SetFinalizer(c, func(c *Conn) { + c.close() + }) + + return c +} + +// Subprotocol returns the negotiated subprotocol. +// An empty string means the default protocol. +func (c *Conn) Subprotocol() string { + return c.subprotocol +} + +func (c *Conn) close() error { + c.closeMu.Lock() + defer c.closeMu.Unlock() + + if c.isClosed() { + return net.ErrClosed + } + runtime.SetFinalizer(c, nil) + close(c.closed) + + // Have to close after c.closed is closed to ensure any goroutine that wakes up + // from the connection being closed also sees that c.closed is closed and returns + // closeErr. + err := c.rwc.Close() + // With the close of rwc, these become safe to close. + c.msgWriter.close() + c.msgReader.close() + return err +} + +func (c *Conn) setupWriteTimeout(ctx context.Context) bool { + if ctx.Done() == nil { + return false + } + + stop := context.AfterFunc(ctx, func() { + c.clearWriteTimeout() + c.close() + }) + swapTimeoutStop(&c.writeTimeoutStop, &stop) + return true +} + +func (c *Conn) clearWriteTimeout() { + swapTimeoutStop(&c.writeTimeoutStop, nil) +} + +func (c *Conn) setupReadTimeout(ctx context.Context) bool { + if ctx.Done() == nil { + return false + } + + stop := context.AfterFunc(ctx, func() { + c.clearReadTimeout() + c.close() + }) + swapTimeoutStop(&c.readTimeoutStop, &stop) + return true +} + +func (c *Conn) clearReadTimeout() { + swapTimeoutStop(&c.readTimeoutStop, nil) +} + +func swapTimeoutStop(p *atomic.Pointer[func() bool], newStop *func() bool) { + oldStop := p.Swap(newStop) + if oldStop != nil { + (*oldStop)() + } +} + +func (c *Conn) flate() bool { + return c.copts != nil +} + +// Ping sends a ping to the peer and waits for a pong. +// Use this to measure latency or ensure the peer is responsive. +// Ping must be called concurrently with Reader as it does +// not read from the connection but instead waits for a Reader call +// to read the pong. +// +// TCP Keepalives should suffice for most use cases. +func (c *Conn) Ping(ctx context.Context) error { + p := c.pingCounter.Add(1) + + err := c.ping(ctx, strconv.FormatInt(p, 10)) + if err != nil { + return fmt.Errorf("failed to ping: %w", err) + } + return nil +} + +func (c *Conn) ping(ctx context.Context, p string) error { + pong := make(chan struct{}, 1) + + c.activePingsMu.Lock() + c.activePings[p] = pong + c.activePingsMu.Unlock() + + defer func() { + c.activePingsMu.Lock() + delete(c.activePings, p) + c.activePingsMu.Unlock() + }() + + err := c.writeControl(ctx, opPing, []byte(p)) + if err != nil { + return err + } + + select { + case <-c.closed: + return net.ErrClosed + case <-ctx.Done(): + return fmt.Errorf("failed to wait for pong: %w", ctx.Err()) + case <-pong: + return nil + } +} + +type mu struct { + c *Conn + ch chan struct{} +} + +func newMu(c *Conn) *mu { + return &mu{ + c: c, + ch: make(chan struct{}, 1), + } +} + +func (m *mu) forceLock() { + m.ch <- struct{}{} +} + +func (m *mu) tryLock() bool { + select { + case m.ch <- struct{}{}: + return true + default: + return false + } +} + +func (m *mu) lock(ctx context.Context) error { + select { + case <-m.c.closed: + return net.ErrClosed + case <-ctx.Done(): + return fmt.Errorf("failed to acquire lock: %w", ctx.Err()) + case m.ch <- struct{}{}: + // To make sure the connection is certainly alive. + // As it's possible the send on m.ch was selected + // over the receive on closed. + select { + case <-m.c.closed: + // Make sure to release. + m.unlock() + return net.ErrClosed + default: + } + return nil + } +} + +func (m *mu) unlock() { + select { + case <-m.ch: + default: + } +} + +type noCopy struct{} + +func (*noCopy) Lock() {} diff --git a/vendor/github.com/coder/websocket/dial.go b/vendor/github.com/coder/websocket/dial.go new file mode 100644 index 0000000..f5e4544 --- /dev/null +++ b/vendor/github.com/coder/websocket/dial.go @@ -0,0 +1,347 @@ +//go:build !js + +package websocket + +import ( + "bufio" + "bytes" + "context" + "crypto/rand" + "encoding/base64" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "time" + + "github.com/coder/websocket/internal/errd" +) + +// DialOptions represents Dial's options. +type DialOptions struct { + // HTTPClient is used for the connection. + // Its Transport must return writable bodies for WebSocket handshakes. + // http.Transport does beginning with Go 1.12. + HTTPClient *http.Client + + // HTTPHeader specifies the HTTP headers included in the handshake request. + HTTPHeader http.Header + + // Host optionally overrides the Host HTTP header to send. If empty, the value + // of URL.Host will be used. + Host string + + // Subprotocols lists the WebSocket subprotocols to negotiate with the server. + Subprotocols []string + + // CompressionMode controls the compression mode. + // Defaults to CompressionDisabled. + // + // See docs on CompressionMode for details. + CompressionMode CompressionMode + + // CompressionThreshold controls the minimum size of a message before compression is applied. + // + // Defaults to 512 bytes for CompressionNoContextTakeover and 128 bytes + // for CompressionContextTakeover. + CompressionThreshold int + + // OnPingReceived is an optional callback invoked synchronously when a ping frame is received. + // + // The payload contains the application data of the ping frame. + // If the callback returns false, the subsequent pong frame will not be sent. + // To avoid blocking, any expensive processing should be performed asynchronously using a goroutine. + OnPingReceived func(ctx context.Context, payload []byte) bool + + // OnPongReceived is an optional callback invoked synchronously when a pong frame is received. + // + // The payload contains the application data of the pong frame. + // To avoid blocking, any expensive processing should be performed asynchronously using a goroutine. + // + // Unlike OnPingReceived, this callback does not return a value because a pong frame + // is a response to a ping and does not trigger any further frame transmission. + OnPongReceived func(ctx context.Context, payload []byte) +} + +func (opts *DialOptions) cloneWithDefaults(ctx context.Context) (context.Context, context.CancelFunc, *DialOptions) { + var cancel context.CancelFunc + + var o DialOptions + if opts != nil { + o = *opts + } + if o.HTTPClient == nil { + o.HTTPClient = http.DefaultClient + } + if o.HTTPClient.Timeout > 0 { + ctx, cancel = context.WithTimeout(ctx, o.HTTPClient.Timeout) + + newClient := *o.HTTPClient + newClient.Timeout = 0 + o.HTTPClient = &newClient + } + if o.HTTPHeader == nil { + o.HTTPHeader = http.Header{} + } + newClient := *o.HTTPClient + oldCheckRedirect := o.HTTPClient.CheckRedirect + newClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { + switch req.URL.Scheme { + case "ws": + req.URL.Scheme = "http" + case "wss": + req.URL.Scheme = "https" + } + if oldCheckRedirect != nil { + return oldCheckRedirect(req, via) + } + return nil + } + o.HTTPClient = &newClient + + return ctx, cancel, &o +} + +// Dial performs a WebSocket handshake on url. +// +// The response is the WebSocket handshake response from the server. +// You never need to close resp.Body yourself. +// +// If an error occurs, the returned response may be non nil. +// However, you can only read the first 1024 bytes of the body. +// +// This function requires at least Go 1.12 as it uses a new feature +// in net/http to perform WebSocket handshakes. +// See docs on the HTTPClient option and https://github.com/golang/go/issues/26937#issuecomment-415855861 +// +// URLs with http/https schemes will work and are interpreted as ws/wss. +func Dial(ctx context.Context, u string, opts *DialOptions) (*Conn, *http.Response, error) { + return dial(ctx, u, opts, nil) +} + +func dial(ctx context.Context, urls string, opts *DialOptions, rand io.Reader) (_ *Conn, _ *http.Response, err error) { + defer errd.Wrap(&err, "failed to WebSocket dial") + + var cancel context.CancelFunc + ctx, cancel, opts = opts.cloneWithDefaults(ctx) + if cancel != nil { + defer cancel() + } + + secWebSocketKey, err := secWebSocketKey(rand) + if err != nil { + return nil, nil, fmt.Errorf("failed to generate Sec-WebSocket-Key: %w", err) + } + + var copts *compressionOptions + if opts.CompressionMode != CompressionDisabled { + copts = opts.CompressionMode.opts() + } + + resp, err := handshakeRequest(ctx, urls, opts, copts, secWebSocketKey) + if err != nil { + return nil, resp, err + } + respBody := resp.Body + resp.Body = nil + defer func() { + if err != nil { + // We read a bit of the body for easier debugging. + r := io.LimitReader(respBody, 1024) + + timer := time.AfterFunc(time.Second*3, func() { + respBody.Close() + }) + defer timer.Stop() + + b, _ := io.ReadAll(r) + respBody.Close() + resp.Body = io.NopCloser(bytes.NewReader(b)) + } + }() + + copts, err = verifyServerResponse(opts, copts, secWebSocketKey, resp) + if err != nil { + return nil, resp, err + } + + rwc, ok := respBody.(io.ReadWriteCloser) + if !ok { + return nil, resp, fmt.Errorf("response body is not a io.ReadWriteCloser: %T", respBody) + } + + return newConn(connConfig{ + subprotocol: resp.Header.Get("Sec-WebSocket-Protocol"), + rwc: rwc, + client: true, + copts: copts, + flateThreshold: opts.CompressionThreshold, + onPingReceived: opts.OnPingReceived, + onPongReceived: opts.OnPongReceived, + br: getBufioReader(rwc), + bw: getBufioWriter(rwc), + }), resp, nil +} + +func handshakeRequest(ctx context.Context, urls string, opts *DialOptions, copts *compressionOptions, secWebSocketKey string) (*http.Response, error) { + u, err := url.Parse(urls) + if err != nil { + return nil, fmt.Errorf("failed to parse url: %w", err) + } + + switch u.Scheme { + case "ws": + u.Scheme = "http" + case "wss": + u.Scheme = "https" + case "http", "https": + default: + return nil, fmt.Errorf("unexpected url scheme: %q", u.Scheme) + } + + req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil) + if err != nil { + return nil, fmt.Errorf("failed to create new http request: %w", err) + } + if len(opts.Host) > 0 { + req.Host = opts.Host + } + req.Header = opts.HTTPHeader.Clone() + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + req.Header.Set("Sec-WebSocket-Version", "13") + req.Header.Set("Sec-WebSocket-Key", secWebSocketKey) + if len(opts.Subprotocols) > 0 { + req.Header.Set("Sec-WebSocket-Protocol", strings.Join(opts.Subprotocols, ",")) + } + if copts != nil { + req.Header.Set("Sec-WebSocket-Extensions", copts.String()) + } + + resp, err := opts.HTTPClient.Do(req) + if err != nil { + return nil, fmt.Errorf("failed to send handshake request: %w", err) + } + return resp, nil +} + +func secWebSocketKey(rr io.Reader) (string, error) { + if rr == nil { + rr = rand.Reader + } + b := make([]byte, 16) + _, err := io.ReadFull(rr, b) + if err != nil { + return "", fmt.Errorf("failed to read random data from rand.Reader: %w", err) + } + return base64.StdEncoding.EncodeToString(b), nil +} + +func verifyServerResponse(opts *DialOptions, copts *compressionOptions, secWebSocketKey string, resp *http.Response) (*compressionOptions, error) { + if resp.StatusCode != http.StatusSwitchingProtocols { + return nil, fmt.Errorf("expected handshake response status code %v but got %v", http.StatusSwitchingProtocols, resp.StatusCode) + } + + if !headerContainsTokenIgnoreCase(resp.Header, "Connection", "Upgrade") { + return nil, fmt.Errorf("WebSocket protocol violation: Connection header %q does not contain Upgrade", resp.Header.Get("Connection")) + } + + if !headerContainsTokenIgnoreCase(resp.Header, "Upgrade", "WebSocket") { + return nil, fmt.Errorf("WebSocket protocol violation: Upgrade header %q does not contain websocket", resp.Header.Get("Upgrade")) + } + + if resp.Header.Get("Sec-WebSocket-Accept") != secWebSocketAccept(secWebSocketKey) { + return nil, fmt.Errorf("WebSocket protocol violation: invalid Sec-WebSocket-Accept %q, key %q", + resp.Header.Get("Sec-WebSocket-Accept"), + secWebSocketKey, + ) + } + + err := verifySubprotocol(opts.Subprotocols, resp) + if err != nil { + return nil, err + } + + return verifyServerExtensions(copts, resp.Header) +} + +func verifySubprotocol(subprotos []string, resp *http.Response) error { + proto := resp.Header.Get("Sec-WebSocket-Protocol") + if proto == "" { + return nil + } + + for _, sp2 := range subprotos { + if strings.EqualFold(sp2, proto) { + return nil + } + } + + return fmt.Errorf("WebSocket protocol violation: unexpected Sec-WebSocket-Protocol from server: %q", proto) +} + +func verifyServerExtensions(copts *compressionOptions, h http.Header) (*compressionOptions, error) { + exts := websocketExtensions(h) + if len(exts) == 0 { + return nil, nil + } + + ext := exts[0] + if ext.name != "permessage-deflate" || len(exts) > 1 || copts == nil { + return nil, fmt.Errorf("WebSocket protcol violation: unsupported extensions from server: %+v", exts[1:]) + } + + _copts := *copts + copts = &_copts + + for _, p := range ext.params { + switch p { + case "client_no_context_takeover": + copts.clientNoContextTakeover = true + continue + case "server_no_context_takeover": + copts.serverNoContextTakeover = true + continue + } + if strings.HasPrefix(p, "server_max_window_bits=") { + // We can't adjust the deflate window, but decoding with a larger window is acceptable. + continue + } + + return nil, fmt.Errorf("unsupported permessage-deflate parameter: %q", p) + } + + return copts, nil +} + +var bufioReaderPool sync.Pool + +func getBufioReader(r io.Reader) *bufio.Reader { + br, ok := bufioReaderPool.Get().(*bufio.Reader) + if !ok { + return bufio.NewReader(r) + } + br.Reset(r) + return br +} + +func putBufioReader(br *bufio.Reader) { + bufioReaderPool.Put(br) +} + +var bufioWriterPool sync.Pool + +func getBufioWriter(w io.Writer) *bufio.Writer { + bw, ok := bufioWriterPool.Get().(*bufio.Writer) + if !ok { + return bufio.NewWriter(w) + } + bw.Reset(w) + return bw +} + +func putBufioWriter(bw *bufio.Writer) { + bufioWriterPool.Put(bw) +} diff --git a/vendor/github.com/coder/websocket/doc.go b/vendor/github.com/coder/websocket/doc.go new file mode 100644 index 0000000..0c7f831 --- /dev/null +++ b/vendor/github.com/coder/websocket/doc.go @@ -0,0 +1,33 @@ +//go:build !js + +// Package websocket implements the RFC 6455 WebSocket protocol. +// +// https://tools.ietf.org/html/rfc6455 +// +// Use Dial to dial a WebSocket server. +// +// Use Accept to accept a WebSocket client. +// +// Conn represents the resulting WebSocket connection. +// +// The examples are the best way to understand how to correctly use the library. +// +// The wsjson subpackage contain helpers for JSON and protobuf messages. +// +// More documentation at https://github.com/coder/websocket. +// +// # Wasm +// +// The client side supports compiling to Wasm. +// It wraps the WebSocket browser API. +// +// See https://developer.mozilla.org/en-US/docs/Web/API/WebSocket +// +// Some important caveats to be aware of: +// +// - Accept always errors out +// - Conn.Ping is no-op +// - Conn.CloseNow is Close(StatusGoingAway, "") +// - HTTPClient, HTTPHeader and CompressionMode in DialOptions are no-op +// - *http.Response from Dial is &http.Response{} with a 101 status code on success +package websocket // import "github.com/coder/websocket" diff --git a/vendor/github.com/coder/websocket/errors.go b/vendor/github.com/coder/websocket/errors.go new file mode 100644 index 0000000..bf4fc2b --- /dev/null +++ b/vendor/github.com/coder/websocket/errors.go @@ -0,0 +1,8 @@ +package websocket + +import ( + "errors" +) + +// ErrMessageTooBig is returned when a message exceeds the read limit. +var ErrMessageTooBig = errors.New("websocket: message too big") diff --git a/vendor/github.com/coder/websocket/frame.go b/vendor/github.com/coder/websocket/frame.go new file mode 100644 index 0000000..e7ab76b --- /dev/null +++ b/vendor/github.com/coder/websocket/frame.go @@ -0,0 +1,173 @@ +//go:build !js + +package websocket + +import ( + "bufio" + "encoding/binary" + "fmt" + "io" + "math" + + "github.com/coder/websocket/internal/errd" +) + +// opcode represents a WebSocket opcode. +type opcode int + +// https://tools.ietf.org/html/rfc6455#section-11.8. +const ( + opContinuation opcode = iota + opText + opBinary + // 3 - 7 are reserved for further non-control frames. + _ + _ + _ + _ + _ + opClose + opPing + opPong + // 11-16 are reserved for further control frames. +) + +// header represents a WebSocket frame header. +// See https://tools.ietf.org/html/rfc6455#section-5.2. +type header struct { + fin bool + rsv1 bool + rsv2 bool + rsv3 bool + opcode opcode + + payloadLength int64 + + masked bool + maskKey uint32 +} + +// readFrameHeader reads a header from the reader. +// See https://tools.ietf.org/html/rfc6455#section-5.2. +func readFrameHeader(r *bufio.Reader, readBuf []byte) (h header, err error) { + defer errd.Wrap(&err, "failed to read frame header") + + b, err := r.ReadByte() + if err != nil { + return header{}, err + } + + h.fin = b&(1<<7) != 0 + h.rsv1 = b&(1<<6) != 0 + h.rsv2 = b&(1<<5) != 0 + h.rsv3 = b&(1<<4) != 0 + + h.opcode = opcode(b & 0xf) + + b, err = r.ReadByte() + if err != nil { + return header{}, err + } + + h.masked = b&(1<<7) != 0 + + payloadLength := b &^ (1 << 7) + switch { + case payloadLength < 126: + h.payloadLength = int64(payloadLength) + case payloadLength == 126: + _, err = io.ReadFull(r, readBuf[:2]) + h.payloadLength = int64(binary.BigEndian.Uint16(readBuf)) + case payloadLength == 127: + _, err = io.ReadFull(r, readBuf) + h.payloadLength = int64(binary.BigEndian.Uint64(readBuf)) + } + if err != nil { + return header{}, err + } + + if h.payloadLength < 0 { + return header{}, fmt.Errorf("received negative payload length: %v", h.payloadLength) + } + + if h.masked { + _, err = io.ReadFull(r, readBuf[:4]) + if err != nil { + return header{}, err + } + h.maskKey = binary.LittleEndian.Uint32(readBuf) + } + + return h, nil +} + +// maxControlPayload is the maximum length of a control frame payload. +// See https://tools.ietf.org/html/rfc6455#section-5.5. +const maxControlPayload = 125 + +// writeFrameHeader writes the bytes of the header to w. +// See https://tools.ietf.org/html/rfc6455#section-5.2 +func writeFrameHeader(h header, w *bufio.Writer, buf []byte) (err error) { + defer errd.Wrap(&err, "failed to write frame header") + + var b byte + if h.fin { + b |= 1 << 7 + } + if h.rsv1 { + b |= 1 << 6 + } + if h.rsv2 { + b |= 1 << 5 + } + if h.rsv3 { + b |= 1 << 4 + } + + b |= byte(h.opcode) + + err = w.WriteByte(b) + if err != nil { + return err + } + + lengthByte := byte(0) + if h.masked { + lengthByte |= 1 << 7 + } + + switch { + case h.payloadLength > math.MaxUint16: + lengthByte |= 127 + case h.payloadLength > 125: + lengthByte |= 126 + case h.payloadLength >= 0: + lengthByte |= byte(h.payloadLength) + } + err = w.WriteByte(lengthByte) + if err != nil { + return err + } + + switch { + case h.payloadLength > math.MaxUint16: + binary.BigEndian.PutUint64(buf, uint64(h.payloadLength)) + _, err = w.Write(buf) + case h.payloadLength > 125: + binary.BigEndian.PutUint16(buf, uint16(h.payloadLength)) + _, err = w.Write(buf[:2]) + } + if err != nil { + return err + } + + if h.masked { + binary.LittleEndian.PutUint32(buf, h.maskKey) + _, err = w.Write(buf[:4]) + if err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/coder/websocket/hijack.go b/vendor/github.com/coder/websocket/hijack.go new file mode 100644 index 0000000..9cce45c --- /dev/null +++ b/vendor/github.com/coder/websocket/hijack.go @@ -0,0 +1,33 @@ +//go:build !js + +package websocket + +import ( + "net/http" +) + +type rwUnwrapper interface { + Unwrap() http.ResponseWriter +} + +// hijacker returns the Hijacker interface of the http.ResponseWriter. +// It follows the Unwrap method of the http.ResponseWriter if available, +// matching the behavior of http.ResponseController. If the Hijacker +// interface is not found, it returns false. +// +// Since the http.ResponseController is not available in Go 1.19, and +// does not support checking the presence of the Hijacker interface, +// this function is used to provide a consistent way to check for the +// Hijacker interface across Go versions. +func hijacker(rw http.ResponseWriter) (http.Hijacker, bool) { + for { + switch t := rw.(type) { + case http.Hijacker: + return t, true + case rwUnwrapper: + rw = t.Unwrap() + default: + return nil, false + } + } +} diff --git a/vendor/github.com/coder/websocket/internal/bpool/bpool.go b/vendor/github.com/coder/websocket/internal/bpool/bpool.go new file mode 100644 index 0000000..12cf577 --- /dev/null +++ b/vendor/github.com/coder/websocket/internal/bpool/bpool.go @@ -0,0 +1,25 @@ +package bpool + +import ( + "bytes" + "sync" +) + +var bpool = sync.Pool{ + New: func() any { + return &bytes.Buffer{} + }, +} + +// Get returns a buffer from the pool or creates a new one if +// the pool is empty. +func Get() *bytes.Buffer { + b := bpool.Get() + return b.(*bytes.Buffer) +} + +// Put returns a buffer into the pool. +func Put(b *bytes.Buffer) { + b.Reset() + bpool.Put(b) +} diff --git a/vendor/github.com/coder/websocket/internal/errd/wrap.go b/vendor/github.com/coder/websocket/internal/errd/wrap.go new file mode 100644 index 0000000..c80d0a6 --- /dev/null +++ b/vendor/github.com/coder/websocket/internal/errd/wrap.go @@ -0,0 +1,14 @@ +package errd + +import ( + "fmt" +) + +// Wrap wraps err with fmt.Errorf if err is non nil. +// Intended for use with defer and a named error return. +// Inspired by https://github.com/golang/go/issues/32676. +func Wrap(err *error, f string, v ...any) { + if *err != nil { + *err = fmt.Errorf(f+": %w", append(v, *err)...) + } +} diff --git a/vendor/github.com/coder/websocket/internal/util/util.go b/vendor/github.com/coder/websocket/internal/util/util.go new file mode 100644 index 0000000..aa21070 --- /dev/null +++ b/vendor/github.com/coder/websocket/internal/util/util.go @@ -0,0 +1,15 @@ +package util + +// WriterFunc is used to implement one off io.Writers. +type WriterFunc func(p []byte) (int, error) + +func (f WriterFunc) Write(p []byte) (int, error) { + return f(p) +} + +// ReaderFunc is used to implement one off io.Readers. +type ReaderFunc func(p []byte) (int, error) + +func (f ReaderFunc) Read(p []byte) (int, error) { + return f(p) +} diff --git a/vendor/github.com/coder/websocket/internal/wsjs/wsjs_js.go b/vendor/github.com/coder/websocket/internal/wsjs/wsjs_js.go new file mode 100644 index 0000000..45ecf49 --- /dev/null +++ b/vendor/github.com/coder/websocket/internal/wsjs/wsjs_js.go @@ -0,0 +1,169 @@ +//go:build js +// +build js + +// Package wsjs implements typed access to the browser javascript WebSocket API. +// +// https://developer.mozilla.org/en-US/docs/Web/API/WebSocket +package wsjs + +import ( + "syscall/js" +) + +func handleJSError(err *error, onErr func()) { + r := recover() + + if jsErr, ok := r.(js.Error); ok { + *err = jsErr + + if onErr != nil { + onErr() + } + return + } + + if r != nil { + panic(r) + } +} + +// New is a wrapper around the javascript WebSocket constructor. +func New(url string, protocols []string) (c WebSocket, err error) { + defer handleJSError(&err, func() { + c = WebSocket{} + }) + + jsProtocols := make([]any, len(protocols)) + for i, p := range protocols { + jsProtocols[i] = p + } + + c = WebSocket{ + v: js.Global().Get("WebSocket").New(url, jsProtocols), + } + + c.setBinaryType("arraybuffer") + + return c, nil +} + +// WebSocket is a wrapper around a javascript WebSocket object. +type WebSocket struct { + v js.Value +} + +func (c WebSocket) setBinaryType(typ string) { + c.v.Set("binaryType", string(typ)) +} + +func (c WebSocket) addEventListener(eventType string, fn func(e js.Value)) func() { + f := js.FuncOf(func(this js.Value, args []js.Value) any { + fn(args[0]) + return nil + }) + c.v.Call("addEventListener", eventType, f) + + return func() { + c.v.Call("removeEventListener", eventType, f) + f.Release() + } +} + +// CloseEvent is the type passed to a WebSocket close handler. +type CloseEvent struct { + Code uint16 + Reason string + WasClean bool +} + +// OnClose registers a function to be called when the WebSocket is closed. +func (c WebSocket) OnClose(fn func(CloseEvent)) (remove func()) { + return c.addEventListener("close", func(e js.Value) { + ce := CloseEvent{ + Code: uint16(e.Get("code").Int()), + Reason: e.Get("reason").String(), + WasClean: e.Get("wasClean").Bool(), + } + fn(ce) + }) +} + +// OnError registers a function to be called when there is an error +// with the WebSocket. +func (c WebSocket) OnError(fn func(e js.Value)) (remove func()) { + return c.addEventListener("error", fn) +} + +// MessageEvent is the type passed to a message handler. +type MessageEvent struct { + // string or []byte. + Data any + + // There are more fields to the interface but we don't use them. + // See https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent +} + +// OnMessage registers a function to be called when the WebSocket receives a message. +func (c WebSocket) OnMessage(fn func(m MessageEvent)) (remove func()) { + return c.addEventListener("message", func(e js.Value) { + var data any + + arrayBuffer := e.Get("data") + if arrayBuffer.Type() == js.TypeString { + data = arrayBuffer.String() + } else { + data = extractArrayBuffer(arrayBuffer) + } + + me := MessageEvent{ + Data: data, + } + fn(me) + }) +} + +// Subprotocol returns the WebSocket subprotocol in use. +func (c WebSocket) Subprotocol() string { + return c.v.Get("protocol").String() +} + +// OnOpen registers a function to be called when the WebSocket is opened. +func (c WebSocket) OnOpen(fn func(e js.Value)) (remove func()) { + return c.addEventListener("open", fn) +} + +// Close closes the WebSocket with the given code and reason. +func (c WebSocket) Close(code int, reason string) (err error) { + defer handleJSError(&err, nil) + c.v.Call("close", code, reason) + return err +} + +// SendText sends the given string as a text message +// on the WebSocket. +func (c WebSocket) SendText(v string) (err error) { + defer handleJSError(&err, nil) + c.v.Call("send", v) + return err +} + +// SendBytes sends the given message as a binary message +// on the WebSocket. +func (c WebSocket) SendBytes(v []byte) (err error) { + defer handleJSError(&err, nil) + c.v.Call("send", uint8Array(v)) + return err +} + +func extractArrayBuffer(arrayBuffer js.Value) []byte { + uint8Array := js.Global().Get("Uint8Array").New(arrayBuffer) + dst := make([]byte, uint8Array.Length()) + js.CopyBytesToGo(dst, uint8Array) + return dst +} + +func uint8Array(src []byte) js.Value { + uint8Array := js.Global().Get("Uint8Array").New(len(src)) + js.CopyBytesToJS(uint8Array, src) + return uint8Array +} diff --git a/vendor/github.com/coder/websocket/mask.go b/vendor/github.com/coder/websocket/mask.go new file mode 100644 index 0000000..7bc0c8d --- /dev/null +++ b/vendor/github.com/coder/websocket/mask.go @@ -0,0 +1,128 @@ +package websocket + +import ( + "encoding/binary" + "math/bits" +) + +// maskGo applies the WebSocket masking algorithm to p +// with the given key. +// See https://tools.ietf.org/html/rfc6455#section-5.3 +// +// The returned value is the correctly rotated key to +// to continue to mask/unmask the message. +// +// It is optimized for LittleEndian and expects the key +// to be in little endian. +// +// See https://github.com/golang/go/issues/31586 +func maskGo(b []byte, key uint32) uint32 { + if len(b) >= 8 { + key64 := uint64(key)<<32 | uint64(key) + + // At some point in the future we can clean these unrolled loops up. + // See https://github.com/golang/go/issues/31586#issuecomment-487436401 + + // Then we xor until b is less than 128 bytes. + for len(b) >= 128 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + v = binary.LittleEndian.Uint64(b[16:24]) + binary.LittleEndian.PutUint64(b[16:24], v^key64) + v = binary.LittleEndian.Uint64(b[24:32]) + binary.LittleEndian.PutUint64(b[24:32], v^key64) + v = binary.LittleEndian.Uint64(b[32:40]) + binary.LittleEndian.PutUint64(b[32:40], v^key64) + v = binary.LittleEndian.Uint64(b[40:48]) + binary.LittleEndian.PutUint64(b[40:48], v^key64) + v = binary.LittleEndian.Uint64(b[48:56]) + binary.LittleEndian.PutUint64(b[48:56], v^key64) + v = binary.LittleEndian.Uint64(b[56:64]) + binary.LittleEndian.PutUint64(b[56:64], v^key64) + v = binary.LittleEndian.Uint64(b[64:72]) + binary.LittleEndian.PutUint64(b[64:72], v^key64) + v = binary.LittleEndian.Uint64(b[72:80]) + binary.LittleEndian.PutUint64(b[72:80], v^key64) + v = binary.LittleEndian.Uint64(b[80:88]) + binary.LittleEndian.PutUint64(b[80:88], v^key64) + v = binary.LittleEndian.Uint64(b[88:96]) + binary.LittleEndian.PutUint64(b[88:96], v^key64) + v = binary.LittleEndian.Uint64(b[96:104]) + binary.LittleEndian.PutUint64(b[96:104], v^key64) + v = binary.LittleEndian.Uint64(b[104:112]) + binary.LittleEndian.PutUint64(b[104:112], v^key64) + v = binary.LittleEndian.Uint64(b[112:120]) + binary.LittleEndian.PutUint64(b[112:120], v^key64) + v = binary.LittleEndian.Uint64(b[120:128]) + binary.LittleEndian.PutUint64(b[120:128], v^key64) + b = b[128:] + } + + // Then we xor until b is less than 64 bytes. + for len(b) >= 64 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + v = binary.LittleEndian.Uint64(b[16:24]) + binary.LittleEndian.PutUint64(b[16:24], v^key64) + v = binary.LittleEndian.Uint64(b[24:32]) + binary.LittleEndian.PutUint64(b[24:32], v^key64) + v = binary.LittleEndian.Uint64(b[32:40]) + binary.LittleEndian.PutUint64(b[32:40], v^key64) + v = binary.LittleEndian.Uint64(b[40:48]) + binary.LittleEndian.PutUint64(b[40:48], v^key64) + v = binary.LittleEndian.Uint64(b[48:56]) + binary.LittleEndian.PutUint64(b[48:56], v^key64) + v = binary.LittleEndian.Uint64(b[56:64]) + binary.LittleEndian.PutUint64(b[56:64], v^key64) + b = b[64:] + } + + // Then we xor until b is less than 32 bytes. + for len(b) >= 32 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + v = binary.LittleEndian.Uint64(b[16:24]) + binary.LittleEndian.PutUint64(b[16:24], v^key64) + v = binary.LittleEndian.Uint64(b[24:32]) + binary.LittleEndian.PutUint64(b[24:32], v^key64) + b = b[32:] + } + + // Then we xor until b is less than 16 bytes. + for len(b) >= 16 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + v = binary.LittleEndian.Uint64(b[8:16]) + binary.LittleEndian.PutUint64(b[8:16], v^key64) + b = b[16:] + } + + // Then we xor until b is less than 8 bytes. + for len(b) >= 8 { + v := binary.LittleEndian.Uint64(b) + binary.LittleEndian.PutUint64(b, v^key64) + b = b[8:] + } + } + + // Then we xor until b is less than 4 bytes. + for len(b) >= 4 { + v := binary.LittleEndian.Uint32(b) + binary.LittleEndian.PutUint32(b, v^key) + b = b[4:] + } + + // xor remaining bytes. + for i := range b { + b[i] ^= byte(key) + key = bits.RotateLeft32(key, -8) + } + + return key +} diff --git a/vendor/github.com/coder/websocket/mask_amd64.s b/vendor/github.com/coder/websocket/mask_amd64.s new file mode 100644 index 0000000..bd42be3 --- /dev/null +++ b/vendor/github.com/coder/websocket/mask_amd64.s @@ -0,0 +1,127 @@ +#include "textflag.h" + +// func maskAsm(b *byte, len int, key uint32) +TEXT ·maskAsm(SB), NOSPLIT, $0-28 + // AX = b + // CX = len (left length) + // SI = key (uint32) + // DI = uint64(SI) | uint64(SI)<<32 + MOVQ b+0(FP), AX + MOVQ len+8(FP), CX + MOVL key+16(FP), SI + + // calculate the DI + // DI = SI<<32 | SI + MOVL SI, DI + MOVQ DI, DX + SHLQ $32, DI + ORQ DX, DI + + CMPQ CX, $15 + JLE less_than_16 + CMPQ CX, $63 + JLE less_than_64 + CMPQ CX, $128 + JLE sse + TESTQ $31, AX + JNZ unaligned + +unaligned_loop_1byte: + XORB SI, (AX) + INCQ AX + DECQ CX + ROLL $24, SI + TESTQ $7, AX + JNZ unaligned_loop_1byte + + // calculate DI again since SI was modified + // DI = SI<<32 | SI + MOVL SI, DI + MOVQ DI, DX + SHLQ $32, DI + ORQ DX, DI + + TESTQ $31, AX + JZ sse + +unaligned: + TESTQ $7, AX // AND $7 & len, if not zero jump to loop_1b. + JNZ unaligned_loop_1byte + +unaligned_loop: + // we don't need to check the CX since we know it's above 128 + XORQ DI, (AX) + ADDQ $8, AX + SUBQ $8, CX + TESTQ $31, AX + JNZ unaligned_loop + JMP sse + +sse: + CMPQ CX, $0x40 + JL less_than_64 + MOVQ DI, X0 + PUNPCKLQDQ X0, X0 + +sse_loop: + MOVOU 0*16(AX), X1 + MOVOU 1*16(AX), X2 + MOVOU 2*16(AX), X3 + MOVOU 3*16(AX), X4 + PXOR X0, X1 + PXOR X0, X2 + PXOR X0, X3 + PXOR X0, X4 + MOVOU X1, 0*16(AX) + MOVOU X2, 1*16(AX) + MOVOU X3, 2*16(AX) + MOVOU X4, 3*16(AX) + ADDQ $0x40, AX + SUBQ $0x40, CX + CMPQ CX, $0x40 + JAE sse_loop + +less_than_64: + TESTQ $32, CX + JZ less_than_32 + XORQ DI, (AX) + XORQ DI, 8(AX) + XORQ DI, 16(AX) + XORQ DI, 24(AX) + ADDQ $32, AX + +less_than_32: + TESTQ $16, CX + JZ less_than_16 + XORQ DI, (AX) + XORQ DI, 8(AX) + ADDQ $16, AX + +less_than_16: + TESTQ $8, CX + JZ less_than_8 + XORQ DI, (AX) + ADDQ $8, AX + +less_than_8: + TESTQ $4, CX + JZ less_than_4 + XORL SI, (AX) + ADDQ $4, AX + +less_than_4: + TESTQ $2, CX + JZ less_than_2 + XORW SI, (AX) + ROLL $16, SI + ADDQ $2, AX + +less_than_2: + TESTQ $1, CX + JZ done + XORB SI, (AX) + ROLL $24, SI + +done: + MOVL SI, ret+24(FP) + RET diff --git a/vendor/github.com/coder/websocket/mask_arm64.s b/vendor/github.com/coder/websocket/mask_arm64.s new file mode 100644 index 0000000..e494b43 --- /dev/null +++ b/vendor/github.com/coder/websocket/mask_arm64.s @@ -0,0 +1,72 @@ +#include "textflag.h" + +// func maskAsm(b *byte, len int, key uint32) +TEXT ·maskAsm(SB), NOSPLIT, $0-28 + // R0 = b + // R1 = len + // R3 = key (uint32) + // R2 = uint64(key)<<32 | uint64(key) + MOVD b_ptr+0(FP), R0 + MOVD b_len+8(FP), R1 + MOVWU key+16(FP), R3 + MOVD R3, R2 + ORR R2<<32, R2, R2 + VDUP R2, V0.D2 + CMP $64, R1 + BLT less_than_64 + +loop_64: + VLD1 (R0), [V1.B16, V2.B16, V3.B16, V4.B16] + VEOR V1.B16, V0.B16, V1.B16 + VEOR V2.B16, V0.B16, V2.B16 + VEOR V3.B16, V0.B16, V3.B16 + VEOR V4.B16, V0.B16, V4.B16 + VST1.P [V1.B16, V2.B16, V3.B16, V4.B16], 64(R0) + SUBS $64, R1 + CMP $64, R1 + BGE loop_64 + +less_than_64: + CBZ R1, end + TBZ $5, R1, less_than_32 + VLD1 (R0), [V1.B16, V2.B16] + VEOR V1.B16, V0.B16, V1.B16 + VEOR V2.B16, V0.B16, V2.B16 + VST1.P [V1.B16, V2.B16], 32(R0) + +less_than_32: + TBZ $4, R1, less_than_16 + LDP (R0), (R11, R12) + EOR R11, R2, R11 + EOR R12, R2, R12 + STP.P (R11, R12), 16(R0) + +less_than_16: + TBZ $3, R1, less_than_8 + MOVD (R0), R11 + EOR R2, R11, R11 + MOVD.P R11, 8(R0) + +less_than_8: + TBZ $2, R1, less_than_4 + MOVWU (R0), R11 + EORW R2, R11, R11 + MOVWU.P R11, 4(R0) + +less_than_4: + TBZ $1, R1, less_than_2 + MOVHU (R0), R11 + EORW R3, R11, R11 + MOVHU.P R11, 2(R0) + RORW $16, R3 + +less_than_2: + TBZ $0, R1, end + MOVBU (R0), R11 + EORW R3, R11, R11 + MOVBU.P R11, 1(R0) + RORW $8, R3 + +end: + MOVWU R3, ret+24(FP) + RET diff --git a/vendor/github.com/coder/websocket/mask_asm.go b/vendor/github.com/coder/websocket/mask_asm.go new file mode 100644 index 0000000..f9484b5 --- /dev/null +++ b/vendor/github.com/coder/websocket/mask_asm.go @@ -0,0 +1,26 @@ +//go:build amd64 || arm64 + +package websocket + +func mask(b []byte, key uint32) uint32 { + // TODO: Will enable in v1.9.0. + return maskGo(b, key) + /* + if len(b) > 0 { + return maskAsm(&b[0], len(b), key) + } + return key + */ +} + +// @nhooyr: I am not confident that the amd64 or the arm64 implementations of this +// function are perfect. There are almost certainly missing optimizations or +// opportunities for simplification. I'm confident there are no bugs though. +// For example, the arm64 implementation doesn't align memory like the amd64. +// Or the amd64 implementation could use AVX512 instead of just AVX2. +// The AVX2 code I had to disable anyway as it wasn't performing as expected. +// See https://github.com/nhooyr/websocket/pull/326#issuecomment-1771138049 +// +//go:noescape +//lint:ignore U1000 disabled till v1.9.0 +func maskAsm(b *byte, len int, key uint32) uint32 diff --git a/vendor/github.com/coder/websocket/mask_go.go b/vendor/github.com/coder/websocket/mask_go.go new file mode 100644 index 0000000..b29435e --- /dev/null +++ b/vendor/github.com/coder/websocket/mask_go.go @@ -0,0 +1,7 @@ +//go:build !amd64 && !arm64 && !js + +package websocket + +func mask(b []byte, key uint32) uint32 { + return maskGo(b, key) +} diff --git a/vendor/github.com/coder/websocket/netconn.go b/vendor/github.com/coder/websocket/netconn.go new file mode 100644 index 0000000..1f73b04 --- /dev/null +++ b/vendor/github.com/coder/websocket/netconn.go @@ -0,0 +1,233 @@ +package websocket + +import ( + "context" + "fmt" + "io" + "math" + "net" + "sync/atomic" + "time" +) + +// NetConn converts a *websocket.Conn into a net.Conn. +// +// It's for tunneling arbitrary protocols over WebSockets. +// Few users of the library will need this but it's tricky to implement +// correctly and so provided in the library. +// See https://github.com/nhooyr/websocket/issues/100. +// +// Every Write to the net.Conn will correspond to a message write of +// the given type on *websocket.Conn. +// +// The passed ctx bounds the lifetime of the net.Conn. If cancelled, +// all reads and writes on the net.Conn will be cancelled. +// +// If a message is read that is not of the correct type, the connection +// will be closed with StatusUnsupportedData and an error will be returned. +// +// Close will close the *websocket.Conn with StatusNormalClosure. +// +// When a deadline is hit and there is an active read or write goroutine, the +// connection will be closed. This is different from most net.Conn implementations +// where only the reading/writing goroutines are interrupted but the connection +// is kept alive. +// +// The Addr methods will return the real addresses for connections obtained +// from websocket.Accept. But for connections obtained from websocket.Dial, a mock net.Addr +// will be returned that gives "websocket" for Network() and "websocket/unknown-addr" for +// String(). This is because websocket.Dial only exposes a io.ReadWriteCloser instead of the +// full net.Conn to us. +// +// When running as WASM, the Addr methods will always return the mock address described above. +// +// A received StatusNormalClosure or StatusGoingAway close frame will be translated to +// io.EOF when reading. +// +// Furthermore, the ReadLimit is set to -1 to disable it. +func NetConn(ctx context.Context, c *Conn, msgType MessageType) net.Conn { + c.SetReadLimit(-1) + + nc := &netConn{ + c: c, + msgType: msgType, + readMu: newMu(c), + writeMu: newMu(c), + } + + nc.writeCtx, nc.writeCancel = context.WithCancel(ctx) + nc.readCtx, nc.readCancel = context.WithCancel(ctx) + + nc.writeTimer = time.AfterFunc(math.MaxInt64, func() { + if !nc.writeMu.tryLock() { + // If the lock cannot be acquired, then there is an + // active write goroutine and so we should cancel the context. + nc.writeCancel() + return + } + defer nc.writeMu.unlock() + + // Prevents future writes from writing until the deadline is reset. + nc.writeExpired.Store(1) + }) + if !nc.writeTimer.Stop() { + <-nc.writeTimer.C + } + + nc.readTimer = time.AfterFunc(math.MaxInt64, func() { + if !nc.readMu.tryLock() { + // If the lock cannot be acquired, then there is an + // active read goroutine and so we should cancel the context. + nc.readCancel() + return + } + defer nc.readMu.unlock() + + // Prevents future reads from reading until the deadline is reset. + nc.readExpired.Store(1) + }) + if !nc.readTimer.Stop() { + <-nc.readTimer.C + } + + return nc +} + +type netConn struct { + c *Conn + msgType MessageType + + writeTimer *time.Timer + writeMu *mu + writeExpired atomic.Int64 + writeCtx context.Context + writeCancel context.CancelFunc + + readTimer *time.Timer + readMu *mu + readExpired atomic.Int64 + readCtx context.Context + readCancel context.CancelFunc + readEOFed bool + reader io.Reader +} + +var _ net.Conn = &netConn{} + +func (nc *netConn) Close() error { + nc.writeTimer.Stop() + nc.writeCancel() + nc.readTimer.Stop() + nc.readCancel() + return nc.c.Close(StatusNormalClosure, "") +} + +func (nc *netConn) Write(p []byte) (int, error) { + nc.writeMu.forceLock() + defer nc.writeMu.unlock() + + if nc.writeExpired.Load() == 1 { + return 0, fmt.Errorf("failed to write: %w", context.DeadlineExceeded) + } + + err := nc.c.Write(nc.writeCtx, nc.msgType, p) + if err != nil { + return 0, err + } + return len(p), nil +} + +func (nc *netConn) Read(p []byte) (int, error) { + nc.readMu.forceLock() + defer nc.readMu.unlock() + + for { + n, err := nc.read(p) + if err != nil { + return n, err + } + if n == 0 { + continue + } + return n, nil + } +} + +func (nc *netConn) read(p []byte) (int, error) { + if nc.readExpired.Load() == 1 { + return 0, fmt.Errorf("failed to read: %w", context.DeadlineExceeded) + } + + if nc.readEOFed { + return 0, io.EOF + } + + if nc.reader == nil { + typ, r, err := nc.c.Reader(nc.readCtx) + if err != nil { + switch CloseStatus(err) { + case StatusNormalClosure, StatusGoingAway: + nc.readEOFed = true + return 0, io.EOF + } + return 0, err + } + if typ != nc.msgType { + err := fmt.Errorf("unexpected frame type read (expected %v): %v", nc.msgType, typ) + nc.c.Close(StatusUnsupportedData, err.Error()) + return 0, err + } + nc.reader = r + } + + n, err := nc.reader.Read(p) + if err == io.EOF { + nc.reader = nil + err = nil + } + return n, err +} + +type websocketAddr struct{} + +func (a websocketAddr) Network() string { + return "websocket" +} + +func (a websocketAddr) String() string { + return "websocket/unknown-addr" +} + +func (nc *netConn) SetDeadline(t time.Time) error { + nc.SetWriteDeadline(t) + nc.SetReadDeadline(t) + return nil +} + +func (nc *netConn) SetWriteDeadline(t time.Time) error { + nc.writeExpired.Store(0) + if t.IsZero() { + nc.writeTimer.Stop() + } else { + dur := time.Until(t) + if dur <= 0 { + dur = 1 + } + nc.writeTimer.Reset(dur) + } + return nil +} + +func (nc *netConn) SetReadDeadline(t time.Time) error { + nc.readExpired.Store(0) + if t.IsZero() { + nc.readTimer.Stop() + } else { + dur := time.Until(t) + if dur <= 0 { + dur = 1 + } + nc.readTimer.Reset(dur) + } + return nil +} diff --git a/vendor/github.com/coder/websocket/netconn_js.go b/vendor/github.com/coder/websocket/netconn_js.go new file mode 100644 index 0000000..ccc8c89 --- /dev/null +++ b/vendor/github.com/coder/websocket/netconn_js.go @@ -0,0 +1,11 @@ +package websocket + +import "net" + +func (nc *netConn) RemoteAddr() net.Addr { + return websocketAddr{} +} + +func (nc *netConn) LocalAddr() net.Addr { + return websocketAddr{} +} diff --git a/vendor/github.com/coder/websocket/netconn_notjs.go b/vendor/github.com/coder/websocket/netconn_notjs.go new file mode 100644 index 0000000..cab7634 --- /dev/null +++ b/vendor/github.com/coder/websocket/netconn_notjs.go @@ -0,0 +1,19 @@ +//go:build !js + +package websocket + +import "net" + +func (nc *netConn) RemoteAddr() net.Addr { + if unc, ok := nc.c.rwc.(net.Conn); ok { + return unc.RemoteAddr() + } + return websocketAddr{} +} + +func (nc *netConn) LocalAddr() net.Addr { + if unc, ok := nc.c.rwc.(net.Conn); ok { + return unc.LocalAddr() + } + return websocketAddr{} +} diff --git a/vendor/github.com/coder/websocket/read.go b/vendor/github.com/coder/websocket/read.go new file mode 100644 index 0000000..c19f41d --- /dev/null +++ b/vendor/github.com/coder/websocket/read.go @@ -0,0 +1,541 @@ +//go:build !js + +package websocket + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "net" + "strings" + "sync/atomic" + "time" + + "github.com/coder/websocket/internal/errd" + "github.com/coder/websocket/internal/util" +) + +// Reader reads from the connection until there is a WebSocket +// data message to be read. It will handle ping, pong and close frames as appropriate. +// +// It returns the type of the message and an io.Reader to read it. +// The passed context will also bound the reader. +// Ensure you read to EOF otherwise the connection will hang. +// +// Call CloseRead if you do not expect any data messages from the peer. +// +// Only one Reader may be open at a time. +// +// If you need a separate timeout on the Reader call and the Read itself, +// use time.AfterFunc to cancel the context passed in. +// See https://github.com/nhooyr/websocket/issues/87#issue-451703332 +// Most users should not need this. +func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error) { + return c.reader(ctx) +} + +// Read is a convenience method around Reader to read a single message +// from the connection. +func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error) { + typ, r, err := c.Reader(ctx) + if err != nil { + return 0, nil, err + } + + b, err := io.ReadAll(r) + return typ, b, err +} + +// CloseRead starts a goroutine to read from the connection until it is closed +// or a data message is received. +// +// Once CloseRead is called you cannot read any messages from the connection. +// The returned context will be cancelled when the connection is closed. +// +// If a data message is received, the connection will be closed with StatusPolicyViolation. +// +// Call CloseRead when you do not expect to read any more messages. +// Since it actively reads from the connection, it will ensure that ping, pong and close +// frames are responded to. This means c.Ping and c.Close will still work as expected. +// +// This function is idempotent. +func (c *Conn) CloseRead(ctx context.Context) context.Context { + c.closeReadMu.Lock() + ctx2 := c.closeReadCtx + if ctx2 != nil { + c.closeReadMu.Unlock() + return ctx2 + } + ctx, cancel := context.WithCancel(ctx) + c.closeReadCtx = ctx + c.closeReadDone = make(chan struct{}) + c.closeReadMu.Unlock() + + go func() { + defer close(c.closeReadDone) + defer cancel() + defer c.close() + _, _, err := c.Reader(ctx) + if err == nil { + c.Close(StatusPolicyViolation, "unexpected data message") + } + }() + return ctx +} + +// SetReadLimit sets the max number of bytes to read for a single message. +// It applies to the Reader and Read methods. +// +// By default, the connection has a message read limit of 32768 bytes. +// +// When the limit is hit, reads return an error wrapping ErrMessageTooBig and +// the connection is closed with StatusMessageTooBig. +// +// Set to -1 to disable. +func (c *Conn) SetReadLimit(n int64) { + if n >= 0 { + // We read one more byte than the limit in case + // there is a fin frame that needs to be read. + n++ + } + + c.msgReader.limitReader.limit.Store(n) +} + +const defaultReadLimit = 32768 + +func newMsgReader(c *Conn) *msgReader { + mr := &msgReader{ + c: c, + fin: true, + } + mr.readFunc = mr.read + + mr.limitReader = newLimitReader(c, mr.readFunc, defaultReadLimit+1) + return mr +} + +func (mr *msgReader) resetFlate() { + if mr.flateContextTakeover() { + if mr.dict == nil { + mr.dict = &slidingWindow{} + } + mr.dict.init(32768) + } + if mr.flateBufio == nil { + mr.flateBufio = getBufioReader(mr.readFunc) + } + + if mr.flateContextTakeover() { + mr.flateReader = getFlateReader(mr.flateBufio, mr.dict.buf) + } else { + mr.flateReader = getFlateReader(mr.flateBufio, nil) + } + mr.limitReader.r = mr.flateReader + mr.flateTail.Reset(deflateMessageTail) +} + +func (mr *msgReader) putFlateReader() { + if mr.flateReader != nil { + putFlateReader(mr.flateReader) + mr.flateReader = nil + } +} + +func (mr *msgReader) close() { + mr.c.readMu.forceLock() + mr.putFlateReader() + if mr.dict != nil { + mr.dict.close() + mr.dict = nil + } + if mr.flateBufio != nil { + putBufioReader(mr.flateBufio) + } + + if mr.c.client { + putBufioReader(mr.c.br) + mr.c.br = nil + } +} + +func (mr *msgReader) flateContextTakeover() bool { + if mr.c.client { + return !mr.c.copts.serverNoContextTakeover + } + return !mr.c.copts.clientNoContextTakeover +} + +func (c *Conn) readRSV1Illegal(h header) bool { + // If compression is disabled, rsv1 is illegal. + if !c.flate() { + return true + } + // rsv1 is only allowed on data frames beginning messages. + if h.opcode != opText && h.opcode != opBinary { + return true + } + return false +} + +func (c *Conn) readLoop(ctx context.Context) (header, error) { + for { + h, err := c.readFrameHeader(ctx) + if err != nil { + return header{}, err + } + + if h.rsv1 && c.readRSV1Illegal(h) || h.rsv2 || h.rsv3 { + err := fmt.Errorf("received header with unexpected rsv bits set: %v:%v:%v", h.rsv1, h.rsv2, h.rsv3) + c.writeError(StatusProtocolError, err) + return header{}, err + } + + if !c.client && !h.masked { + return header{}, errors.New("received unmasked frame from client") + } + + switch h.opcode { + case opClose, opPing, opPong: + err = c.handleControl(ctx, h) + if err != nil { + // Pass through CloseErrors when receiving a close frame. + if h.opcode == opClose && CloseStatus(err) != -1 { + return header{}, err + } + return header{}, fmt.Errorf("failed to handle control frame %v: %w", h.opcode, err) + } + case opContinuation, opText, opBinary: + return h, nil + default: + err := fmt.Errorf("received unknown opcode %v", h.opcode) + c.writeError(StatusProtocolError, err) + return header{}, err + } + } +} + +// prepareRead sets the read timeout and checks whether the connection is closed. +func (c *Conn) prepareRead(ctx context.Context) (bool, error) { + select { + case <-c.closed: + return false, net.ErrClosed + default: + } + timeoutSet := c.setupReadTimeout(ctx) + + c.closeStateMu.Lock() + closeReceivedErr := c.closeReceivedErr + c.closeStateMu.Unlock() + if closeReceivedErr != nil { + if timeoutSet { + c.clearReadTimeout() + } + return false, closeReceivedErr + } + + return timeoutSet, nil +} + +// finishRead clears the read timeout and reports whether the connection or +// operation context ended while the read was in progress. +func (c *Conn) finishRead(ctx context.Context, err *error, timeoutSet bool) { + if timeoutSet { + c.clearReadTimeout() + } + select { + case <-c.closed: + if *err != nil { + *err = net.ErrClosed + } + default: + } + if *err != nil && ctx.Err() != nil { + *err = ctx.Err() + } +} + +func (c *Conn) readFrameHeader(ctx context.Context) (_ header, err error) { + timeoutSet, err := c.prepareRead(ctx) + if err != nil { + return header{}, err + } + defer c.finishRead(ctx, &err, timeoutSet) + + h, err := readFrameHeader(c.br, c.readHeaderBuf[:]) + if err != nil { + return header{}, err + } + + return h, nil +} + +func (c *Conn) readFramePayload(ctx context.Context, p []byte) (_ int, err error) { + timeoutSet, err := c.prepareRead(ctx) + if err != nil { + return 0, err + } + defer c.finishRead(ctx, &err, timeoutSet) + + n, err := io.ReadFull(c.br, p) + if err != nil { + return n, fmt.Errorf("failed to read frame payload: %w", err) + } + + return n, nil +} + +func (c *Conn) handleControl(ctx context.Context, h header) (err error) { + if h.payloadLength < 0 || h.payloadLength > maxControlPayload { + err := fmt.Errorf("received control frame payload with invalid length: %d", h.payloadLength) + c.writeError(StatusProtocolError, err) + return err + } + + if !h.fin { + err := errors.New("received fragmented control frame") + c.writeError(StatusProtocolError, err) + return err + } + + ctx, cancel := context.WithTimeout(ctx, time.Second*5) + defer cancel() + + b := c.readControlBuf[:h.payloadLength] + _, err = c.readFramePayload(ctx, b) + if err != nil { + return err + } + + if h.masked { + mask(b, h.maskKey) + } + + switch h.opcode { + case opPing: + if c.onPingReceived != nil { + if !c.onPingReceived(ctx, b) { + return nil + } + } + return c.writeControl(ctx, opPong, b) + case opPong: + if c.onPongReceived != nil { + c.onPongReceived(ctx, b) + } + c.activePingsMu.Lock() + pong, ok := c.activePings[string(b)] + c.activePingsMu.Unlock() + if ok { + select { + case pong <- struct{}{}: + default: + } + } + return nil + } + + // opClose + + ce, err := parseClosePayload(b) + if err != nil { + err = fmt.Errorf("received invalid close payload: %w", err) + c.writeError(StatusProtocolError, err) + return err + } + + err = fmt.Errorf("received close frame: %w", ce) + c.closeStateMu.Lock() + c.closeReceivedErr = err + closeSent := c.closeSentErr != nil + c.closeStateMu.Unlock() + + // Only unlock readMu if this connection is being closed becaue + // c.close will try to acquire the readMu lock. We unlock for + // writeClose as well because it may also call c.close. + if !closeSent { + c.readMu.unlock() + _ = c.writeClose(ce.Code, ce.Reason) + } + if !c.casClosing() { + c.readMu.unlock() + _ = c.close() + } + return err +} + +func (c *Conn) reader(ctx context.Context) (_ MessageType, _ io.Reader, err error) { + defer errd.Wrap(&err, "failed to get reader") + + err = c.readMu.lock(ctx) + if err != nil { + return 0, nil, err + } + defer c.readMu.unlock() + + if !c.msgReader.fin { + return 0, nil, errors.New("previous message not read to completion") + } + + h, err := c.readLoop(ctx) + if err != nil { + return 0, nil, err + } + + if h.opcode == opContinuation { + err := errors.New("received continuation frame without text or binary frame") + c.writeError(StatusProtocolError, err) + return 0, nil, err + } + + c.msgReader.reset(ctx, h) + + return MessageType(h.opcode), c.msgReader, nil +} + +type msgReader struct { + c *Conn + + ctx context.Context + flate bool + flateReader io.Reader + flateBufio *bufio.Reader + flateTail strings.Reader + limitReader *limitReader + dict *slidingWindow + + fin bool + payloadLength int64 + maskKey uint32 + + // util.ReaderFunc(mr.Read) to avoid continuous allocations. + readFunc util.ReaderFunc +} + +func (mr *msgReader) reset(ctx context.Context, h header) { + mr.ctx = ctx + mr.flate = h.rsv1 + mr.limitReader.reset(mr.readFunc) + + if mr.flate { + mr.resetFlate() + } + + mr.setFrame(h) +} + +func (mr *msgReader) setFrame(h header) { + mr.fin = h.fin + mr.payloadLength = h.payloadLength + mr.maskKey = h.maskKey +} + +func (mr *msgReader) Read(p []byte) (n int, err error) { + err = mr.c.readMu.lock(mr.ctx) + if err != nil { + return 0, fmt.Errorf("failed to read: %w", err) + } + defer mr.c.readMu.unlock() + + n, err = mr.limitReader.Read(p) + if mr.flate && mr.flateContextTakeover() { + p = p[:n] + mr.dict.write(p) + } + if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) && mr.fin && mr.flate { + mr.putFlateReader() + return n, io.EOF + } + if err != nil { + return n, fmt.Errorf("failed to read: %w", err) + } + return n, nil +} + +func (mr *msgReader) read(p []byte) (int, error) { + for { + if mr.payloadLength == 0 { + if mr.fin { + if mr.flate { + return mr.flateTail.Read(p) + } + return 0, io.EOF + } + + h, err := mr.c.readLoop(mr.ctx) + if err != nil { + return 0, err + } + if h.opcode != opContinuation { + err := errors.New("received new data message without finishing the previous message") + mr.c.writeError(StatusProtocolError, err) + return 0, err + } + mr.setFrame(h) + + continue + } + + if int64(len(p)) > mr.payloadLength { + p = p[:mr.payloadLength] + } + + n, err := mr.c.readFramePayload(mr.ctx, p) + if err != nil { + return n, err + } + + mr.payloadLength -= int64(n) + + if !mr.c.client { + mr.maskKey = mask(p, mr.maskKey) + } + + return n, nil + } +} + +type limitReader struct { + c *Conn + r io.Reader + limit atomic.Int64 + n int64 +} + +func newLimitReader(c *Conn, r io.Reader, limit int64) *limitReader { + lr := &limitReader{ + c: c, + } + lr.limit.Store(limit) + lr.reset(r) + return lr +} + +func (lr *limitReader) reset(r io.Reader) { + lr.n = lr.limit.Load() + lr.r = r +} + +func (lr *limitReader) Read(p []byte) (int, error) { + if lr.n < 0 { + return lr.r.Read(p) + } + + if lr.n == 0 { + reason := fmt.Errorf("read limited at %d bytes", lr.limit.Load()) + lr.c.writeError(StatusMessageTooBig, reason) + return 0, fmt.Errorf("%w: %v", ErrMessageTooBig, reason) + } + + if int64(len(p)) > lr.n { + p = p[:lr.n] + } + n, err := lr.r.Read(p) + lr.n -= int64(n) + if lr.n < 0 { + lr.n = 0 + } + return n, err +} diff --git a/vendor/github.com/coder/websocket/stringer.go b/vendor/github.com/coder/websocket/stringer.go new file mode 100644 index 0000000..5a66ba2 --- /dev/null +++ b/vendor/github.com/coder/websocket/stringer.go @@ -0,0 +1,91 @@ +// Code generated by "stringer -type=opcode,MessageType,StatusCode -output=stringer.go"; DO NOT EDIT. + +package websocket + +import "strconv" + +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[opContinuation-0] + _ = x[opText-1] + _ = x[opBinary-2] + _ = x[opClose-8] + _ = x[opPing-9] + _ = x[opPong-10] +} + +const ( + _opcode_name_0 = "opContinuationopTextopBinary" + _opcode_name_1 = "opCloseopPingopPong" +) + +var ( + _opcode_index_0 = [...]uint8{0, 14, 20, 28} + _opcode_index_1 = [...]uint8{0, 7, 13, 19} +) + +func (i opcode) String() string { + switch { + case 0 <= i && i <= 2: + return _opcode_name_0[_opcode_index_0[i]:_opcode_index_0[i+1]] + case 8 <= i && i <= 10: + i -= 8 + return _opcode_name_1[_opcode_index_1[i]:_opcode_index_1[i+1]] + default: + return "opcode(" + strconv.FormatInt(int64(i), 10) + ")" + } +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[MessageText-1] + _ = x[MessageBinary-2] +} + +const _MessageType_name = "MessageTextMessageBinary" + +var _MessageType_index = [...]uint8{0, 11, 24} + +func (i MessageType) String() string { + i -= 1 + if i < 0 || i >= MessageType(len(_MessageType_index)-1) { + return "MessageType(" + strconv.FormatInt(int64(i+1), 10) + ")" + } + return _MessageType_name[_MessageType_index[i]:_MessageType_index[i+1]] +} +func _() { + // An "invalid array index" compiler error signifies that the constant values have changed. + // Re-run the stringer command to generate them again. + var x [1]struct{} + _ = x[StatusNormalClosure-1000] + _ = x[StatusGoingAway-1001] + _ = x[StatusProtocolError-1002] + _ = x[StatusUnsupportedData-1003] + _ = x[statusReserved-1004] + _ = x[StatusNoStatusRcvd-1005] + _ = x[StatusAbnormalClosure-1006] + _ = x[StatusInvalidFramePayloadData-1007] + _ = x[StatusPolicyViolation-1008] + _ = x[StatusMessageTooBig-1009] + _ = x[StatusMandatoryExtension-1010] + _ = x[StatusInternalError-1011] + _ = x[StatusServiceRestart-1012] + _ = x[StatusTryAgainLater-1013] + _ = x[StatusBadGateway-1014] + _ = x[StatusTLSHandshake-1015] +} + +const _StatusCode_name = "StatusNormalClosureStatusGoingAwayStatusProtocolErrorStatusUnsupportedDatastatusReservedStatusNoStatusRcvdStatusAbnormalClosureStatusInvalidFramePayloadDataStatusPolicyViolationStatusMessageTooBigStatusMandatoryExtensionStatusInternalErrorStatusServiceRestartStatusTryAgainLaterStatusBadGatewayStatusTLSHandshake" + +var _StatusCode_index = [...]uint16{0, 19, 34, 53, 74, 88, 106, 127, 156, 177, 196, 220, 239, 259, 278, 294, 312} + +func (i StatusCode) String() string { + i -= 1000 + if i < 0 || i >= StatusCode(len(_StatusCode_index)-1) { + return "StatusCode(" + strconv.FormatInt(int64(i+1000), 10) + ")" + } + return _StatusCode_name[_StatusCode_index[i]:_StatusCode_index[i+1]] +} diff --git a/vendor/github.com/coder/websocket/write.go b/vendor/github.com/coder/websocket/write.go new file mode 100644 index 0000000..81bab4f --- /dev/null +++ b/vendor/github.com/coder/websocket/write.go @@ -0,0 +1,430 @@ +//go:build !js + +package websocket + +import ( + "bufio" + "compress/flate" + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "io" + "net" + "time" + + "github.com/coder/websocket/internal/bpool" + "github.com/coder/websocket/internal/errd" + "github.com/coder/websocket/internal/util" +) + +// Writer returns a writer bounded by the context that will write +// a WebSocket message of type dataType to the connection. +// +// You must close the writer once you have written the entire message. +// +// Only one writer can be open at a time, multiple calls will block until the previous writer +// is closed. +func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) { + w, err := c.writer(ctx, typ) + if err != nil { + return nil, fmt.Errorf("failed to get writer: %w", err) + } + return w, nil +} + +// Write writes a message to the connection. +// +// See the Writer method if you want to stream a message. +// +// If compression is disabled or the compression threshold is not met, then it +// will write the message in a single frame. +func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error { + _, err := c.write(ctx, typ, p) + if err != nil { + return fmt.Errorf("failed to write msg: %w", err) + } + return nil +} + +type msgWriter struct { + c *Conn + + mu *mu + writeMu *mu + closed bool + + ctx context.Context + opcode opcode + flate bool + + trimWriter *trimLastFourBytesWriter + flateWriter *flate.Writer +} + +func newMsgWriter(c *Conn) *msgWriter { + mw := &msgWriter{ + c: c, + mu: newMu(c), + writeMu: newMu(c), + } + return mw +} + +func (mw *msgWriter) ensureFlate() { + if mw.trimWriter == nil { + mw.trimWriter = &trimLastFourBytesWriter{ + w: util.WriterFunc(mw.write), + } + } + + if mw.flateWriter == nil { + mw.flateWriter = getFlateWriter(mw.trimWriter) + } + mw.flate = true +} + +func (mw *msgWriter) flateContextTakeover() bool { + if mw.c.client { + return !mw.c.copts.clientNoContextTakeover + } + return !mw.c.copts.serverNoContextTakeover +} + +func (c *Conn) writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) { + err := c.msgWriter.reset(ctx, typ) + if err != nil { + return nil, err + } + return c.msgWriter, nil +} + +func (c *Conn) write(ctx context.Context, typ MessageType, p []byte) (int, error) { + err := c.msgWriter.reset(ctx, typ) + if err != nil { + return 0, err + } + defer c.msgWriter.mu.unlock() + + if !c.flate() || len(p) < c.flateThreshold { + return c.writeFrame(ctx, true, false, c.msgWriter.opcode, p) + } + + return c.msgWriter.writeCompressedFrame(ctx, p) +} + +func (mw *msgWriter) reset(ctx context.Context, typ MessageType) error { + err := mw.mu.lock(ctx) + if err != nil { + return err + } + + mw.ctx = ctx + mw.opcode = opcode(typ) + mw.flate = false + mw.closed = false + + mw.trimWriter.reset() + + return nil +} + +func (mw *msgWriter) putFlateWriter() { + if mw.flateWriter != nil { + putFlateWriter(mw.flateWriter) + mw.flateWriter = nil + } +} + +// writeCompressedFrame compresses and writes p as a single frame. +func (mw *msgWriter) writeCompressedFrame(ctx context.Context, p []byte) (int, error) { + err := mw.writeMu.lock(mw.ctx) + if err != nil { + return 0, fmt.Errorf("failed to write: %w", err) + } + defer mw.writeMu.unlock() + + if mw.closed { + return 0, errors.New("cannot use closed writer") + } + + mw.ensureFlate() + + buf := bpool.Get() + defer bpool.Put(buf) + + // Buffer compressed output so we can write as + // a single frame instead of chunked frames. + origWriter := mw.trimWriter.w + mw.trimWriter.w = buf + defer func() { + mw.trimWriter.w = origWriter + }() + + _, err = mw.flateWriter.Write(p) + if err != nil { + return 0, fmt.Errorf("failed to compress: %w", err) + } + + err = mw.flateWriter.Flush() + if err != nil { + return 0, fmt.Errorf("failed to flush compression: %w", err) + } + + mw.trimWriter.reset() + + if !mw.flateContextTakeover() { + mw.putFlateWriter() + } + + mw.closed = true + + _, err = mw.c.writeFrame(ctx, true, true, mw.opcode, buf.Bytes()) + if err != nil { + return 0, err + } + return len(p), nil +} + +// Write writes the given bytes to the WebSocket connection. +func (mw *msgWriter) Write(p []byte) (_ int, err error) { + err = mw.writeMu.lock(mw.ctx) + if err != nil { + return 0, fmt.Errorf("failed to write: %w", err) + } + defer mw.writeMu.unlock() + + if mw.closed { + return 0, errors.New("cannot use closed writer") + } + + defer func() { + if err != nil { + err = fmt.Errorf("failed to write: %w", err) + } + }() + + if mw.c.flate() { + // Only enables flate if the length crosses the + // threshold on the first frame + if mw.opcode != opContinuation && len(p) >= mw.c.flateThreshold { + mw.ensureFlate() + } + } + + if mw.flate { + return mw.flateWriter.Write(p) + } + + return mw.write(p) +} + +func (mw *msgWriter) write(p []byte) (int, error) { + n, err := mw.c.writeFrame(mw.ctx, false, mw.flate, mw.opcode, p) + if err != nil { + return n, fmt.Errorf("failed to write data frame: %w", err) + } + mw.opcode = opContinuation + return n, nil +} + +// Close flushes the frame to the connection. +func (mw *msgWriter) Close() (err error) { + defer errd.Wrap(&err, "failed to close writer") + + err = mw.writeMu.lock(mw.ctx) + if err != nil { + return err + } + defer mw.writeMu.unlock() + + if mw.closed { + return errors.New("writer already closed") + } + mw.closed = true + + if mw.flate { + err = mw.flateWriter.Flush() + if err != nil { + return fmt.Errorf("failed to flush flate: %w", err) + } + } + + _, err = mw.c.writeFrame(mw.ctx, true, mw.flate, mw.opcode, nil) + if err != nil { + return fmt.Errorf("failed to write fin frame: %w", err) + } + + if mw.flate && !mw.flateContextTakeover() { + mw.putFlateWriter() + } + mw.mu.unlock() + return nil +} + +func (mw *msgWriter) close() { + if mw.c.client { + mw.c.writeFrameMu.forceLock() + putBufioWriter(mw.c.bw) + } + + mw.writeMu.forceLock() + mw.putFlateWriter() +} + +func (c *Conn) writeControl(ctx context.Context, opcode opcode, p []byte) error { + ctx, cancel := context.WithTimeout(ctx, time.Second*5) + defer cancel() + + _, err := c.writeFrame(ctx, true, false, opcode, p) + if err != nil { + return fmt.Errorf("failed to write control frame %v: %w", opcode, err) + } + return nil +} + +// writeFrame handles all writes to the connection. +func (c *Conn) writeFrame(ctx context.Context, fin bool, flate bool, opcode opcode, p []byte) (_ int, err error) { + err = c.writeFrameMu.lock(ctx) + if err != nil { + return 0, err + } + defer c.writeFrameMu.unlock() + + defer func() { + if c.isClosed() && opcode == opClose { + err = nil + } + if err != nil { + if ctx.Err() != nil { + err = ctx.Err() + } else if c.isClosed() { + err = net.ErrClosed + } + err = fmt.Errorf("failed to write frame: %w", err) + } + }() + + c.closeStateMu.Lock() + closeSentErr := c.closeSentErr + c.closeStateMu.Unlock() + if closeSentErr != nil { + return 0, net.ErrClosed + } + + select { + case <-c.closed: + return 0, net.ErrClosed + default: + } + if c.setupWriteTimeout(ctx) { + defer c.clearWriteTimeout() + } + + c.writeHeader.fin = fin + c.writeHeader.opcode = opcode + c.writeHeader.payloadLength = int64(len(p)) + + if c.client { + c.writeHeader.masked = true + _, err = io.ReadFull(rand.Reader, c.writeHeaderBuf[:4]) + if err != nil { + return 0, fmt.Errorf("failed to generate masking key: %w", err) + } + c.writeHeader.maskKey = binary.LittleEndian.Uint32(c.writeHeaderBuf[:]) + } + + c.writeHeader.rsv1 = false + if flate && (opcode == opText || opcode == opBinary) { + c.writeHeader.rsv1 = true + } + + err = writeFrameHeader(c.writeHeader, c.bw, c.writeHeaderBuf[:]) + if err != nil { + return 0, err + } + + n, err := c.writeFramePayload(p) + if err != nil { + return n, err + } + + if c.writeHeader.fin { + err = c.bw.Flush() + if err != nil { + return n, fmt.Errorf("failed to flush: %w", err) + } + } + + if opcode == opClose { + c.closeStateMu.Lock() + c.closeSentErr = fmt.Errorf("sent close frame: %w", net.ErrClosed) + closeReceived := c.closeReceivedErr != nil + c.closeStateMu.Unlock() + + if closeReceived && !c.casClosing() { + c.writeFrameMu.unlock() + _ = c.close() + } + } + + return n, nil +} + +func (c *Conn) writeFramePayload(p []byte) (n int, err error) { + defer errd.Wrap(&err, "failed to write frame payload") + + if !c.writeHeader.masked { + return c.bw.Write(p) + } + + maskKey := c.writeHeader.maskKey + for len(p) > 0 { + // If the buffer is full, we need to flush. + if c.bw.Available() == 0 { + err = c.bw.Flush() + if err != nil { + return n, err + } + } + + // Start of next write in the buffer. + i := c.bw.Buffered() + + j := min(len(p), c.bw.Available()) + + _, err := c.bw.Write(p[:j]) + if err != nil { + return n, err + } + + maskKey = mask(c.writeBuf[i:c.bw.Buffered()], maskKey) + + p = p[j:] + n += j + } + + return n, nil +} + +// extractBufioWriterBuf grabs the []byte backing a *bufio.Writer +// and returns it. +func extractBufioWriterBuf(bw *bufio.Writer, w io.Writer) []byte { + var writeBuf []byte + bw.Reset(util.WriterFunc(func(p2 []byte) (int, error) { + writeBuf = p2[:cap(p2)] + return len(p2), nil + })) + + bw.WriteByte(0) + bw.Flush() + + bw.Reset(w) + + return writeBuf +} + +func (c *Conn) writeError(code StatusCode, err error) { + c.writeClose(code, err.Error()) +} diff --git a/vendor/github.com/coder/websocket/ws_js.go b/vendor/github.com/coder/websocket/ws_js.go new file mode 100644 index 0000000..026b75f --- /dev/null +++ b/vendor/github.com/coder/websocket/ws_js.go @@ -0,0 +1,598 @@ +package websocket // import "github.com/coder/websocket" + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "reflect" + "runtime" + "strings" + "sync" + "sync/atomic" + "syscall/js" + + "github.com/coder/websocket/internal/bpool" + "github.com/coder/websocket/internal/wsjs" +) + +// opcode represents a WebSocket opcode. +type opcode int + +// https://tools.ietf.org/html/rfc6455#section-11.8. +const ( + opContinuation opcode = iota + opText + opBinary + // 3 - 7 are reserved for further non-control frames. + _ + _ + _ + _ + _ + opClose + opPing + opPong + // 11-16 are reserved for further control frames. +) + +// Conn provides a wrapper around the browser WebSocket API. +type Conn struct { + noCopy noCopy + ws wsjs.WebSocket + + // read limit for a message in bytes. + msgReadLimit atomic.Int64 + + closeReadMu sync.Mutex + closeReadCtx context.Context + + closingMu sync.Mutex + closeOnce sync.Once + closed chan struct{} + closeErrOnce sync.Once + closeErr error + closeWasClean bool + + releaseOnClose func() + releaseOnError func() + releaseOnMessage func() + + readSignal chan struct{} + readBufMu sync.Mutex + readBuf []wsjs.MessageEvent +} + +func (c *Conn) close(err error, wasClean bool) { + c.closeOnce.Do(func() { + runtime.SetFinalizer(c, nil) + + if !wasClean { + err = fmt.Errorf("unclean connection close: %w", err) + } + c.setCloseErr(err) + c.closeWasClean = wasClean + close(c.closed) + }) +} + +func (c *Conn) init() { + c.closed = make(chan struct{}) + c.readSignal = make(chan struct{}, 1) + + c.msgReadLimit.Store(32768) + + c.releaseOnClose = c.ws.OnClose(func(e wsjs.CloseEvent) { + err := CloseError{ + Code: StatusCode(e.Code), + Reason: e.Reason, + } + // We do not know if we sent or received this close as + // its possible the browser triggered it without us + // explicitly sending it. + c.close(err, e.WasClean) + + c.releaseOnClose() + c.releaseOnError() + c.releaseOnMessage() + }) + + c.releaseOnError = c.ws.OnError(func(v js.Value) { + c.setCloseErr(errors.New(v.Get("message").String())) + c.closeWithInternal() + }) + + c.releaseOnMessage = c.ws.OnMessage(func(e wsjs.MessageEvent) { + c.readBufMu.Lock() + defer c.readBufMu.Unlock() + + c.readBuf = append(c.readBuf, e) + + // Lets the read goroutine know there is definitely something in readBuf. + select { + case c.readSignal <- struct{}{}: + default: + } + }) + + runtime.SetFinalizer(c, func(c *Conn) { + c.setCloseErr(errors.New("connection garbage collected")) + c.closeWithInternal() + }) +} + +func (c *Conn) closeWithInternal() { + c.Close(StatusInternalError, "something went wrong") +} + +// Read attempts to read a message from the connection. +// The maximum time spent waiting is bounded by the context. +func (c *Conn) Read(ctx context.Context) (MessageType, []byte, error) { + c.closeReadMu.Lock() + closedRead := c.closeReadCtx != nil + c.closeReadMu.Unlock() + if closedRead { + return 0, nil, errors.New("WebSocket connection read closed") + } + + typ, p, err := c.read(ctx) + if err != nil { + return 0, nil, fmt.Errorf("failed to read: %w", err) + } + readLimit := c.msgReadLimit.Load() + if readLimit >= 0 && int64(len(p)) > readLimit { + reason := fmt.Errorf("read limited at %d bytes", c.msgReadLimit.Load()) + c.Close(StatusMessageTooBig, reason.Error()) + return 0, nil, fmt.Errorf("%w: %v", ErrMessageTooBig, reason) + } + return typ, p, nil +} + +func (c *Conn) read(ctx context.Context) (MessageType, []byte, error) { + select { + case <-ctx.Done(): + c.Close(StatusPolicyViolation, "read timed out") + return 0, nil, ctx.Err() + case <-c.readSignal: + case <-c.closed: + return 0, nil, net.ErrClosed + } + + c.readBufMu.Lock() + defer c.readBufMu.Unlock() + + me := c.readBuf[0] + // We copy the messages forward and decrease the size + // of the slice to avoid reallocating. + copy(c.readBuf, c.readBuf[1:]) + c.readBuf = c.readBuf[:len(c.readBuf)-1] + + if len(c.readBuf) > 0 { + // Next time we read, we'll grab the message. + select { + case c.readSignal <- struct{}{}: + default: + } + } + + switch p := me.Data.(type) { + case string: + return MessageText, []byte(p), nil + case []byte: + return MessageBinary, p, nil + default: + panic("websocket: unexpected data type from wsjs OnMessage: " + reflect.TypeOf(me.Data).String()) + } +} + +// Ping is mocked out for Wasm. +func (c *Conn) Ping(ctx context.Context) error { + return nil +} + +// Write writes a message of the given type to the connection. +// Always non blocking. +func (c *Conn) Write(ctx context.Context, typ MessageType, p []byte) error { + err := c.write(typ, p) + if err != nil { + // Have to ensure the WebSocket is closed after a write error + // to match the Go API. It can only error if the message type + // is unexpected or the passed bytes contain invalid UTF-8 for + // MessageText. + err := fmt.Errorf("failed to write: %w", err) + c.setCloseErr(err) + c.closeWithInternal() + return err + } + return nil +} + +func (c *Conn) write(typ MessageType, p []byte) error { + if c.isClosed() { + return net.ErrClosed + } + switch typ { + case MessageBinary: + return c.ws.SendBytes(p) + case MessageText: + return c.ws.SendText(string(p)) + default: + return fmt.Errorf("unexpected message type: %v", typ) + } +} + +// Close closes the WebSocket with the given code and reason. +// It will wait until the peer responds with a close frame +// or the connection is closed. +// It thus performs the full WebSocket close handshake. +func (c *Conn) Close(code StatusCode, reason string) error { + err := c.exportedClose(code, reason) + if err != nil { + return fmt.Errorf("failed to close WebSocket: %w", err) + } + return nil +} + +// CloseNow closes the WebSocket connection without attempting a close handshake. +// Use when you do not want the overhead of the close handshake. +// +// note: No different from Close(StatusGoingAway, "") in WASM as there is no way to close +// a WebSocket without the close handshake. +func (c *Conn) CloseNow() error { + return c.Close(StatusGoingAway, "") +} + +func (c *Conn) exportedClose(code StatusCode, reason string) error { + c.closingMu.Lock() + defer c.closingMu.Unlock() + + if c.isClosed() { + return net.ErrClosed + } + + ce := fmt.Errorf("sent close: %w", CloseError{ + Code: code, + Reason: reason, + }) + + c.setCloseErr(ce) + err := c.ws.Close(int(code), reason) + if err != nil { + return err + } + + <-c.closed + if !c.closeWasClean { + return c.closeErr + } + return nil +} + +// Subprotocol returns the negotiated subprotocol. +// An empty string means the default protocol. +func (c *Conn) Subprotocol() string { + return c.ws.Subprotocol() +} + +// DialOptions represents the options available to pass to Dial. +type DialOptions struct { + // Subprotocols lists the subprotocols to negotiate with the server. + Subprotocols []string +} + +// Dial creates a new WebSocket connection to the given url with the given options. +// The passed context bounds the maximum time spent waiting for the connection to open. +// The returned *http.Response is always nil or a mock. It's only in the signature +// to match the core API. +func Dial(ctx context.Context, url string, opts *DialOptions) (*Conn, *http.Response, error) { + c, resp, err := dial(ctx, url, opts) + if err != nil { + return nil, nil, fmt.Errorf("failed to WebSocket dial %q: %w", url, err) + } + return c, resp, nil +} + +func dial(ctx context.Context, url string, opts *DialOptions) (*Conn, *http.Response, error) { + if opts == nil { + opts = &DialOptions{} + } + + url = strings.Replace(url, "http://", "ws://", 1) + url = strings.Replace(url, "https://", "wss://", 1) + + ws, err := wsjs.New(url, opts.Subprotocols) + if err != nil { + return nil, nil, err + } + + c := &Conn{ + ws: ws, + } + c.init() + + opench := make(chan struct{}) + releaseOpen := ws.OnOpen(func(e js.Value) { + close(opench) + }) + defer releaseOpen() + + select { + case <-ctx.Done(): + c.Close(StatusPolicyViolation, "dial timed out") + return nil, nil, ctx.Err() + case <-opench: + return c, &http.Response{ + StatusCode: http.StatusSwitchingProtocols, + }, nil + case <-c.closed: + return nil, nil, net.ErrClosed + } +} + +// Reader attempts to read a message from the connection. +// The maximum time spent waiting is bounded by the context. +func (c *Conn) Reader(ctx context.Context) (MessageType, io.Reader, error) { + typ, p, err := c.Read(ctx) + if err != nil { + return 0, nil, err + } + return typ, bytes.NewReader(p), nil +} + +// Writer returns a writer to write a WebSocket data message to the connection. +// It buffers the entire message in memory and then sends it when the writer +// is closed. +func (c *Conn) Writer(ctx context.Context, typ MessageType) (io.WriteCloser, error) { + return &writer{ + c: c, + ctx: ctx, + typ: typ, + b: bpool.Get(), + }, nil +} + +type writer struct { + closed bool + + c *Conn + ctx context.Context + typ MessageType + + b *bytes.Buffer +} + +func (w *writer) Write(p []byte) (int, error) { + if w.closed { + return 0, errors.New("cannot write to closed writer") + } + n, err := w.b.Write(p) + if err != nil { + return n, fmt.Errorf("failed to write message: %w", err) + } + return n, nil +} + +func (w *writer) Close() error { + if w.closed { + return errors.New("cannot close closed writer") + } + w.closed = true + defer bpool.Put(w.b) + + err := w.c.Write(w.ctx, w.typ, w.b.Bytes()) + if err != nil { + return fmt.Errorf("failed to close writer: %w", err) + } + return nil +} + +// CloseRead implements *Conn.CloseRead for wasm. +func (c *Conn) CloseRead(ctx context.Context) context.Context { + c.closeReadMu.Lock() + ctx2 := c.closeReadCtx + if ctx2 != nil { + c.closeReadMu.Unlock() + return ctx2 + } + ctx, cancel := context.WithCancel(ctx) + c.closeReadCtx = ctx + c.closeReadMu.Unlock() + + go func() { + defer cancel() + defer c.CloseNow() + _, _, err := c.read(ctx) + if err != nil { + c.Close(StatusPolicyViolation, "unexpected data message") + } + }() + return ctx +} + +// SetReadLimit implements *Conn.SetReadLimit for wasm. +func (c *Conn) SetReadLimit(n int64) { + c.msgReadLimit.Store(n) +} + +func (c *Conn) setCloseErr(err error) { + c.closeErrOnce.Do(func() { + c.closeErr = fmt.Errorf("WebSocket closed: %w", err) + }) +} + +func (c *Conn) isClosed() bool { + select { + case <-c.closed: + return true + default: + return false + } +} + +// AcceptOptions represents Accept's options. +type AcceptOptions struct { + Subprotocols []string + InsecureSkipVerify bool + OriginPatterns []string + CompressionMode CompressionMode + CompressionThreshold int +} + +// Accept is stubbed out for Wasm. +func Accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (*Conn, error) { + return nil, errors.New("unimplemented") +} + +// StatusCode represents a WebSocket status code. +// https://tools.ietf.org/html/rfc6455#section-7.4 +type StatusCode int + +// https://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number +// +// These are only the status codes defined by the protocol. +// +// You can define custom codes in the 3000-4999 range. +// The 3000-3999 range is reserved for use by libraries, frameworks and applications. +// The 4000-4999 range is reserved for private use. +const ( + StatusNormalClosure StatusCode = 1000 + StatusGoingAway StatusCode = 1001 + StatusProtocolError StatusCode = 1002 + StatusUnsupportedData StatusCode = 1003 + + // 1004 is reserved and so unexported. + statusReserved StatusCode = 1004 + + // StatusNoStatusRcvd cannot be sent in a close message. + // It is reserved for when a close message is received without + // a status code. + StatusNoStatusRcvd StatusCode = 1005 + + // StatusAbnormalClosure is exported for use only with Wasm. + // In non Wasm Go, the returned error will indicate whether the + // connection was closed abnormally. + StatusAbnormalClosure StatusCode = 1006 + + StatusInvalidFramePayloadData StatusCode = 1007 + StatusPolicyViolation StatusCode = 1008 + StatusMessageTooBig StatusCode = 1009 + StatusMandatoryExtension StatusCode = 1010 + StatusInternalError StatusCode = 1011 + StatusServiceRestart StatusCode = 1012 + StatusTryAgainLater StatusCode = 1013 + StatusBadGateway StatusCode = 1014 + + // StatusTLSHandshake is only exported for use with Wasm. + // In non Wasm Go, the returned error will indicate whether there was + // a TLS handshake failure. + StatusTLSHandshake StatusCode = 1015 +) + +// CloseError is returned when the connection is closed with a status and reason. +// +// Use Go 1.13's errors.As to check for this error. +// Also see the CloseStatus helper. +type CloseError struct { + Code StatusCode + Reason string +} + +func (ce CloseError) Error() string { + return fmt.Sprintf("status = %v and reason = %q", ce.Code, ce.Reason) +} + +// CloseStatus is a convenience wrapper around Go 1.13's errors.As to grab +// the status code from a CloseError. +// +// -1 will be returned if the passed error is nil or not a CloseError. +func CloseStatus(err error) StatusCode { + var ce CloseError + if errors.As(err, &ce) { + return ce.Code + } + return -1 +} + +// CompressionMode represents the modes available to the deflate extension. +// See https://tools.ietf.org/html/rfc7692 +// Works in all browsers except Safari which does not implement the deflate extension. +type CompressionMode int + +const ( + // CompressionNoContextTakeover grabs a new flate.Reader and flate.Writer as needed + // for every message. This applies to both server and client side. + // + // This means less efficient compression as the sliding window from previous messages + // will not be used but the memory overhead will be lower if the connections + // are long lived and seldom used. + // + // The message will only be compressed if greater than 512 bytes. + CompressionNoContextTakeover CompressionMode = iota + + // CompressionContextTakeover uses a flate.Reader and flate.Writer per connection. + // This enables reusing the sliding window from previous messages. + // As most WebSocket protocols are repetitive, this can be very efficient. + // It carries an overhead of 8 kB for every connection compared to CompressionNoContextTakeover. + // + // If the peer negotiates NoContextTakeover on the client or server side, it will be + // used instead as this is required by the RFC. + CompressionContextTakeover + + // CompressionDisabled disables the deflate extension. + // + // Use this if you are using a predominantly binary protocol with very + // little duplication in between messages or CPU and memory are more + // important than bandwidth. + CompressionDisabled +) + +// MessageType represents the type of a WebSocket message. +// See https://tools.ietf.org/html/rfc6455#section-5.6 +type MessageType int + +// MessageType constants. +const ( + // MessageText is for UTF-8 encoded text messages like JSON. + MessageText MessageType = iota + 1 + // MessageBinary is for binary messages like protobufs. + MessageBinary +) + +type mu struct { + c *Conn + ch chan struct{} +} + +func newMu(c *Conn) *mu { + return &mu{ + c: c, + ch: make(chan struct{}, 1), + } +} + +func (m *mu) forceLock() { + m.ch <- struct{}{} +} + +func (m *mu) tryLock() bool { + select { + case m.ch <- struct{}{}: + return true + default: + return false + } +} + +func (m *mu) unlock() { + select { + case <-m.ch: + default: + } +} + +type noCopy struct{} + +func (*noCopy) Lock() {} diff --git a/vendor/github.com/gabriel-vasile/mimetype/.git-blame-ignore-revs b/vendor/github.com/gabriel-vasile/mimetype/.git-blame-ignore-revs new file mode 100644 index 0000000..3892826 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/.git-blame-ignore-revs @@ -0,0 +1,9 @@ +# Github is obeying this ignore file by default. +# Run this command on local to ignore formatting commits in `git blame` +# git config blame.ignoreRevsFile .git-blame-ignore-revs + +# Added a new column to supported_mimes.md +# The supported_mimes.md file was a nice way to find when a file format was +# introduced. However, when I changed to add a new column in the table, the +# whole git blame got poisoned for the file. +eb497f9bc5d31c6eab2929a112051218670137ba diff --git a/vendor/github.com/gabriel-vasile/mimetype/.gitattributes b/vendor/github.com/gabriel-vasile/mimetype/.gitattributes new file mode 100644 index 0000000..0cc26ec --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/.gitattributes @@ -0,0 +1 @@ +testdata/* linguist-vendored diff --git a/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml b/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml new file mode 100644 index 0000000..835dea6 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/.golangci.yml @@ -0,0 +1,48 @@ +version: "2" + +run: + timeout: 5m + +linters: + exclusions: + presets: + - std-error-handling + rules: + # Test fixtures construct CDF binary blobs from known small constants, so + # gosec's integer-overflow checks (G115) add no value there. + - path: internal/cdf/cdf_test\.go + linters: + - gosec + enable: + - gosec # Detects security problems. + # Keep all extras disabled for now to focus on the integer overflow problem. + # TODO: enable these and other good linters + - dogsled # Detects assignments with too many blank identifiers. + - errcheck + - errchkjson # Detects unsupported types passed to json encoding functions and reports if checks for the returned error can be omitted. + - exhaustive # Detects missing options in enum switch statements. + - gocyclo + - govet + - ineffassign + - makezero # Finds slice declarations with non-zero initial length. + - misspell # Detects commonly misspelled English words in comments. + - nakedret # Detects uses of naked returns. + - prealloc # Detects slice declarations that could potentially be pre-allocated. + - predeclared # Detects code that shadows one of Go's predeclared identifiers. + - reassign # Detects reassigning a top-level variable in another package. + - staticcheck + - thelper # Detects test helpers without t.Helper(). + - tparallel # Detects inappropriate usage of t.Parallel(). + - unconvert # Detects unnecessary type conversions. + - unused + - usestdlibvars # Detects the possibility to use variables/constants from the Go standard library. + - usetesting # Reports uses of functions with replacement inside the testing package. + - asciicheck # https://daniel.haxx.se/blog/2025/05/16/detecting-malicious-unicode/ + settings: + govet: + disable: + - stdversion + gosec: + excludes: + - G404 # Weak random number generator used in tests. + - G304 # File inclusion diff --git a/vendor/github.com/gabriel-vasile/mimetype/LICENSE b/vendor/github.com/gabriel-vasile/mimetype/LICENSE new file mode 100644 index 0000000..13b61da --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Gabriel Vasile + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/gabriel-vasile/mimetype/README.md b/vendor/github.com/gabriel-vasile/mimetype/README.md new file mode 100644 index 0000000..b024316 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/README.md @@ -0,0 +1,112 @@ +

+ mimetype +

+ +

+ A package for detecting MIME types and extensions based on magic numbers +

+
+ Goroutine safe, extensible, no C bindings +
+ +

+ + Go Reference + + + Code coverage + + + License + +

+ +## Features +- fast and precise MIME type and file extension detection +- long list of [supported MIME types](supported_mimes.md) +- possibility to [extend](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#example-package-Extend) with other file formats +- common file formats are prioritized +- [text vs. binary files differentiation](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#example-package-TextVsBinary) +- no external dependencies +- safe for concurrent usage + +## Install +```bash +go get github.com/gabriel-vasile/mimetype +``` + +## Usage +```go +mtype := mimetype.Detect([]byte) +// OR +mtype, err := mimetype.DetectReader(io.Reader) +// OR +mtype, err := mimetype.DetectFile("/path/to/file") +fmt.Println(mtype.String(), mtype.Extension()) +``` +See the [runnable Go Playground examples](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#pkg-overview). + +Caution: only use libraries like **mimetype** as a last resort. Content type detection +using magic numbers is slow, inaccurate, and non-standard. Most of the times +protocols have methods for specifying such metadata; e.g., `Content-Type` header +in HTTP and SMTP. + +## FAQ +Q: My file is in the list of [supported MIME types](supported_mimes.md) but +it is not correctly detected. What should I do? + +A: Some file formats (often Microsoft Office documents) keep their signatures +towards the end of the file. Try increasing the number of bytes used for detection +with: +```go +mimetype.SetLimit(1024*1024) // Set limit to 1MB. +// or +mimetype.SetLimit(0) // No limit, whole file content used. +mimetype.DetectFile("file.doc") +``` +If increasing the limit does not help, please +[open an issue](https://github.com/gabriel-vasile/mimetype/issues/new?assignees=&labels=&template=mismatched-mime-type-detected.md&title=). + +## Tests +In addition to unit tests, +[mimetype_tests](https://github.com/gabriel-vasile/mimetype_tests) compares the +library with [libmagic](https://en.wikipedia.org/wiki/File_(command)) +for around 50 000 sample files. Check the latest comparison results +[here](https://github.com/gabriel-vasile/mimetype_tests/actions). + +## Benchmarks +Benchmarks are performed when a PR is open. The results can be seen on the +[workflows page](https://github.com/gabriel-vasile/mimetype/actions/workflows/benchmark.yml). +Performance improvements are welcome but correctness is prioritized. + +## Structure +**mimetype** uses a hierarchical structure to keep the MIME type detection logic. +This reduces the number of calls needed for detecting the file type. The reason +behind this choice is that there are file formats used as containers for other +file formats. For example, Microsoft Office files are just zip archives, +containing specific metadata files. Once a file has been identified as a +zip, there is no need to check if it is a text file, but it is worth checking if +it is an Microsoft Office file. + +To prevent loading entire files into memory, when detecting from a +[reader](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#DetectReader) +or from a [file](https://pkg.go.dev/github.com/gabriel-vasile/mimetype#DetectFile) +**mimetype** limits itself to reading only the header of the input. +
+ how project is structured +
+ +## Contributing +Contributions are never expected but very much welcome. +[mimetype_tests](https://github.com/gabriel-vasile/mimetype_tests/actions/workflows/test.yml) +shows which file formats are most often misidentified and can help prioritise. +When submitting a PR for detection of a new file format, please make sure to +add a record to the list of testcases in [mimetype_test.go](mimetype_test.go). +For complex files a record can be added in the [testdata](testdata) directory. +Code contributions must respect following rules: + - code must be test covered + - code must be formatted using the `gofmt` tool + - exported names must be documented + +**Important**: By submitting a pull request, you agree to allow the project +owner to license your work under the same license as that used by the project. diff --git a/vendor/github.com/gabriel-vasile/mimetype/codecov.yml b/vendor/github.com/gabriel-vasile/mimetype/codecov.yml new file mode 100644 index 0000000..69cb760 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/codecov.yml @@ -0,0 +1 @@ +comment: false diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go new file mode 100644 index 0000000..926cef7 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/cdf/cdf.go @@ -0,0 +1,667 @@ +// Package cdf implements parsing of CDF (OLE2) files. It is greatly inspired +// by src/readcdf.c from libmagic. One difference is this implementation is +// permissive of truncated inputs. See readLimit in mimetype.go for the +// reason why truncated inputs need to be handled. +// http://sc.openoffice.org/compdocfileformat.pdf +package cdf + +import ( + "bytes" + "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +type CDFType int8 + +const ( + CDFTypeGeneric CDFType = iota + CDFTypeInstaller + CDFTypeDoc + CDFTypePpt + CDFTypeXls + CDFTypeMsg +) + +// Detect parses raw as a CDF (OLE2) compound file and returns the document type +// it contains. It returns CDFTypeGeneric for input that is not a CDF file or +// whose type cannot be narrowed down. +func Detect(raw []byte) CDFType { + if len(raw) < 512 { + return CDFTypeGeneric + } + var c cdf + if !parse(raw, &c) { + return CDFTypeGeneric + } + return c.detect() +} + +// cdf holds everything we need from a CDF file to do detection. +type cdf struct { + data []byte + secSize int + shortSecSize int + minStdStream uint32 + satSecs int32s // list of SAT sector ids; usually a sub-slice of raw input + satEntries int // number of valid SAT entries reachable through satSecs + firstSSAT int32 + dirRaw []byte // directory stream bytes (entries are decoded on demand) + sst []byte // short-stream pool (root storage's stream) + sstBuilt bool // whether sst was already loaded (it is loaded lazily) + rootStreamFirst int32 // first sector of the root storage short-stream pool + rootStreamSize uint32 // size of the root storage short-stream pool + rootStorageUUID []byte +} + +// parse reads the entire on-disk structure required for type detection. It +// returns true on success and false if the header does not look like a CDF file. +// Truncated or partially malformed bodies are tolerated: sector reads degrade +// to whatever could be collected so detection can still succeed from partial data. +func parse(raw []byte, c *cdf) bool { + if len(raw) < 512 || binary.LittleEndian.Uint64(raw) != cdfMagic { + return false + } + secP2 := binary.LittleEndian.Uint16(raw[30:32]) + shortP2 := binary.LittleEndian.Uint16(raw[32:34]) + if secP2 > 20 || shortP2 > 20 { + return false + } + c.data = raw + c.secSize = 1 << secP2 + c.shortSecSize = 1 << shortP2 + c.minStdStream = binary.LittleEndian.Uint32(raw[56:60]) + if c.secSize < dirEntrySize { + return false + } + firstDirSec := readSecID(raw[48:52]) + c.firstSSAT = readSecID(raw[60:64]) + firstMSAT := readSecID(raw[68:72]) + nMSAT := binary.LittleEndian.Uint32(raw[72:76]) + masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]} + + c.buildSAT(masterSAT, firstMSAT, nMSAT) + c.dirRaw = c.readLong(firstDirSec, 0) + + c.rootStreamFirst = -1 + var d dirEntry + for i, n := 0, c.dirLen(); i < n; i++ { + c.dirAt(i, &d) + if d.typ != dirTypeRootStorage || d.streamFirst < 0 { + continue + } + c.rootStorageUUID = d.storageUUID[:] + // Record where the short-stream pool lives; it is loaded lazily by + // shortStream the first time a short stream is actually read. + c.rootStreamFirst = d.streamFirst + c.rootStreamSize = d.size + break + } + return true +} + +func (c *cdf) detect() CDFType { + for _, name := range []string{"\x05SummaryInformation", "\x05DocumentSummaryInformation"} { + if t, ok := c.detectFromSummary(name); ok { + return t + } + } + var d dirEntry + for i, n := 0, c.dirLen(); i < n; i++ { + c.dirAt(i, &d) + if t, ok := lookupSection(d.nameBytes(), d.typ); ok { + return t + } + } + return CDFTypeGeneric +} + +// detectFromSummary inspects a (Doc)SummaryInformation stream and tries to +// derive a CDFType from the root-storage CLSID, the property NameOfApplication, +// and finally the names of sibling user streams. +func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) { + if c.rootStorageUUID != nil && bytes.Equal(c.rootStorageUUID, msiCLSID) { + return CDFTypeInstaller, true + } + raw, ok := c.userStream(streamName) + if !ok { + return CDFTypeGeneric, false + } + if app := summaryAppName(raw); len(app) > 0 { + if t, ok := lookupSubstring(app, app2type); ok { + return t, true + } + } + for i, n := 0, c.dirLen(); i < n; i++ { + var d dirEntry + c.dirAt(i, &d) + if d.nameLen == 0 { + continue + } + if t, ok := lookupSubstring(d.nameBytes(), name2type); ok { + return t, true + } + } + return CDFTypeGeneric, true +} + +const ( + cdfMagic uint64 = 0xE11AB1A1E011CFD0 + + dirTypeUserStorage = 1 + dirTypeUserStream = 2 + dirTypeRootStorage = 5 + + dirEntrySize = 128 + masterSATSize = 109 // first 109 SAT secids live in the file header +) + +// dirEntry is a single CDF directory record. The UTF-16LE name is pre-decoded +// into an inline ASCII buffer at parse time, avoiding a per-entry heap +// allocation while keeping comparisons trivial. CDF names are at most 32 +// UTF-16 code units, so 32 bytes always suffice. +type dirEntry struct { + name [32]byte + nameLen uint8 + typ uint8 + streamFirst int32 + size uint32 + storageUUID [16]byte +} + +// nameBytes returns the decoded ASCII name without copying. +func (d *dirEntry) nameBytes() []byte { return d.name[:d.nameLen] } + +func (c *cdf) ssatAt(i int32) int32 { + for sid := c.firstSSAT; sid >= 0; { + if int(sid) >= c.satLen() { + break // SAT is truncated; stop collecting + } + buf, ok := c.sector(sid) + if !ok { + break + } + lbuf := int32(len(buf) / 4) //nolint:gosec // anything divided by 4 fits int32 + if i < lbuf { + return int32(binary.LittleEndian.Uint32(buf[4*i:])) //nolint:gosec // intentional two's-complement reinterpretation of a sector id + } + i -= lbuf + sid = c.satAt(sid) + } + return -1 +} + +// shortStream returns the root storage short-stream pool, loading it on first +// use. Detection often finishes (e.g. via the root CLSID or a long-stream +// summary) without ever reading a short stream, so building this eagerly would +// be wasted work. +func (c *cdf) shortStream() []byte { + if !c.sstBuilt { + c.sstBuilt = true + if c.rootStreamFirst >= 0 { + c.sst = c.readLong(c.rootStreamFirst, c.rootStreamSize) + } + } + return c.sst +} + +// int32s works like a slice of LE int32 and is backed by a slice of bytes. +// int32s could very well be type int32s []byte, but that would mean +// len function can be called on it. We don't want that, we always want to use +// the len method. +type int32s struct { + b []byte +} + +func (b int32s) at(i int) int32 { + //nolint:gosec // intentional two's-complement reinterpretation of a sector id + return int32(binary.LittleEndian.Uint32(b.b[4*i:])) +} +func (b int32s) len() int { + return len(b.b) / 4 +} + +// readSecID reinterprets four little-endian bytes as a signed sector id. +// Every 32-bit pattern is a valid id (values >= 0 are sector numbers, +// negatives are CDF sentinels such as -2 end-of-chain), so the conversion is +// an intentional two's-complement reinterpretation rather than an overflow. +func readSecID(b []byte) int32 { + return int32(binary.LittleEndian.Uint32(b)) //nolint:gosec // intentional two's-complement reinterpretation +} + +// satLen is the number of sector ids reachable through the SAT. +func (c *cdf) satLen() int { return c.satEntries } + +// satAt returns the i-th sector id from the SAT. Callers must ensure +// i < satLen(). The SAT is not materialized; the entry is fetched directly +// from the input by translating i into (SAT sector index, entry offset). +func (c *cdf) satAt(i int32) int32 { + perSec := c.secSize / 4 + secIdx := int(i) / perSec + entryIdx := int(i) % perSec + secID := c.satSecs.at(secIdx) + off := c.secSize*(1+int(secID)) + 4*entryIdx + return readSecID(c.data[off:]) +} + +// sector returns the bytes of long sector secid. If the file is truncated +// inside the requested sector the result is the available bytes (no padding). +// If the sector starts past EOF or secid is negative, then ok is false. +func (c *cdf) sector(secid int32) (_ []byte, ok bool) { + if secid < 0 { + return nil, false + } + off := int64(c.secSize) * (1 + int64(secid)) + if off >= int64(len(c.data)) { + return nil, false + } + // The returned sector might be truncated, + // but we still return it as best effort. + end := min(off+int64(c.secSize), int64(len(c.data))) + // If not even one int32 fits, then fail. + if end-off < 4 { + return nil, false + } + return c.data[off:end], true +} + +func (c *cdf) sectorIDs(secid int32) (int32s, bool) { + buf, ok := c.sector(secid) + if !ok { + return int32s{}, ok + } + return int32s{b: buf}, true +} + +// buildSAT records the list of SAT sector ids from the master-SAT (header) +// plus any extension blocks chained via firstMSAT. The SAT itself is not +// materialized: satAt computes the requested entry directly from c.data via +// satSecs. In the common case (no extension chain) satSecs is a zero-copy +// sub-slice of the input header. +func (c *cdf) buildSAT(masterSAT int32s, firstMSAT int32, nMSAT uint32) { + // Fast path: no extension chain. masterSAT is already a sub-slice of raw + // input; reuse it directly. + if firstMSAT < 0 || nMSAT == 0 { + c.satSecs = masterSAT + c.satEntries = c.computeSATLen() + return + } + + // Slow path: gather sector ids from the header plus the extension chain + // into a fresh buffer. Even here we only allocate space for ids (4 bytes + // each), not the full SAT contents. + maxIDs := len(c.data)/c.secSize + 1 + buf := make([]byte, 0, 4*masterSATSize) + for i := 0; i < masterSAT.len(); i++ { + if masterSAT.at(i) < 0 { + break + } + buf = append(buf, masterSAT.b[4*i:4*i+4]...) + } + perSec := c.secSize/4 - 1 + mid := firstMSAT +chain: + for j := uint32(0); j < nMSAT && mid >= 0; j++ { + msa, ok := c.sectorIDs(mid) + if !ok { + break + } + for k := 0; k < perSec; k++ { + if k >= msa.len() || msa.at(k) < 0 { + break chain + } + buf = append(buf, msa.b[4*k:4*k+4]...) + if len(buf)/4 > maxIDs { + break chain // cyclic MSAT chain; stop allocating + } + } + if perSec >= msa.len() { + break // no next-MSAT pointer available + } + mid = msa.at(perSec) + } + c.satSecs = int32s{b: buf} + c.satEntries = c.computeSATLen() +} + +// computeSATLen walks satSecs and counts how many SAT entries are actually +// reachable in c.data, stopping at the first sentinel id or sector that is not +// fully present in the file. +func (c *cdf) computeSATLen() int { + perSec := c.secSize / 4 + total := 0 + for i := 0; i < c.satSecs.len(); i++ { + sec := c.satSecs.at(i) + if sec < 0 { + break + } + off := int64(c.secSize) * (1 + int64(sec)) + if off >= int64(len(c.data)) { + break + } + avail := int64(len(c.data)) - off + if avail >= int64(c.secSize) { + total += perSec + continue + } + total += int(avail / 4) + break + } + return total +} + +// readLong reads a long-sector chain starting at sid. If length > 0 the +// result is truncated to that many bytes. On truncation or any other failure +// it returns whatever sectors were readable. +func (c *cdf) readLong(sid int32, length uint32) []byte { + // Fast path: when the chain is a single physically contiguous run of + // sectors (the common case for the directory and summary streams) the data + // is already laid out sequentially in the input, so return a sub-slice of + // it instead of allocating a buffer and copying every sector. + if sid >= 0 { + maxSec := len(c.data)/c.secSize + 1 + n, s := 0, sid + contiguous := true + for s >= 0 { + if int(s) >= c.satLen() { + break // SAT truncated; what remains is still contiguous + } + n++ + if n > maxSec { + contiguous = false // cyclic chain; let the slow path guard it + break + } + next := c.satAt(s) + if next >= 0 && int64(next) != int64(s)+1 { + contiguous = false + break + } + s = next + } + if contiguous { + off64 := int64(c.secSize) * (1 + int64(sid)) + if off64 >= int64(len(c.data)) { + return nil + } + end64 := min(off64+int64(n)*int64(c.secSize), int64(len(c.data))) + out := c.data[off64:end64] + if length > 0 && int64(length) < int64(len(out)) { + out = out[:length] + } + return out + } + } + + // Slow path: gather a fragmented chain into a fresh buffer. Real-world + // writers (MSI builders, edited Office documents) routinely produce + // non-contiguous directory and stream chains, so this fallback is required + // for correct detection on those files. + maxBytes := len(c.data) + out := make([]byte, 0, c.secSize) + for sid >= 0 { + if int(sid) >= c.satLen() { + break // SAT truncated; return what we have + } + buf, ok := c.sector(sid) + if !ok { + break + } + out = append(out, buf...) + if len(out) >= maxBytes { + break // chain longer than the file: cyclic SAT, stop + } + sid = c.satAt(sid) + } + if length > 0 && int64(length) < int64(len(out)) { + out = out[:length] + } + return out +} + +// readShort reads a short-sector chain at sid by indexing into the short-stream +// pool. On truncation or if the pool is unavailable it returns whatever was +// readable (possibly nil). +func (c *cdf) readShort(sid int32, length uint32) []byte { + sst := c.shortStream() + if sst == nil { + return nil + } + // TODO: anyway to avoid allocating and copying the bytes? + out := make([]byte, 0, c.shortSecSize) + for sid >= 0 { + off64 := int64(sid) * int64(c.shortSecSize) + if off64+int64(c.shortSecSize) > int64(len(sst)) { + break // short-stream pool truncated or sid out of range + } + off := int(off64) + out = append(out, sst[off:off+c.shortSecSize]...) + if len(out) >= len(sst) { + break // chain longer than the pool: cyclic SSAT, stop + } + sid = c.ssatAt(sid) + } + if length > 0 && int64(length) < int64(len(out)) { + out = out[:length] + } + return out +} + +// readChain dispatches to the long or short reader depending on stream size. +func (c *cdf) readChain(sid int32, length uint32) []byte { + if length < c.minStdStream && c.rootStreamFirst >= 0 { + return c.readShort(sid, length) + } + return c.readLong(sid, length) +} + +// dirLen returns the number of directory entries in dirRaw. +func (c *cdf) dirLen() int { return len(c.dirRaw) / dirEntrySize } + +// dirAt decodes the i-th directory entry into *out. Callers must ensure +// i < dirLen(). The UTF-16LE name is decoded into out.name, ASCII-style, +// stopping at the first NUL. +func (c *cdf) dirAt(i int, out *dirEntry) { + raw := c.dirRaw[i*dirEntrySize:] + nameLen := min(int(binary.LittleEndian.Uint16(raw[64:])), 64) + k := uint8(0) + for j := 0; j < nameLen/2; j++ { + // Names are ASCII; keep the low byte of each little-endian UTF-16 + // code unit and stop at the first NUL. + lo, hi := raw[2*j], raw[2*j+1] + if lo == 0 && hi == 0 { + break + } + out.name[k] = lo + k++ + } + out.nameLen = k + out.typ = raw[66] + out.streamFirst = readSecID(raw[116:120]) + out.size = binary.LittleEndian.Uint32(raw[120:]) + copy(out.storageUUID[:], raw[80:96]) +} + +// userStream finds a user stream by name and returns its bytes. +func (c *cdf) userStream(name string) ([]byte, bool) { + var d dirEntry + for i, n := 0, c.dirLen(); i < n; i++ { + c.dirAt(i, &d) + if d.typ == dirTypeUserStream && string(d.nameBytes()) == name { + buf := c.readChain(d.streamFirst, d.size) + if buf == nil { + return nil, false + } + return buf, true + } + } + return nil, false +} + +const ( + propIDNameOfApplication = 0x12 + + typeMask = 0x0fff + typeVector = 0x1000 + typeStringASCII = 0x1e + typeStringWide = 0x1f + + sectionDeclOffset = 0x1c // section declaration in property-set header +) + +// summaryAppName parses a (Doc)SummaryInformation stream and returns the +// value of property NameOfApplication (0x12) as printable ASCII, or nil if +// not present or the stream is malformed. This is the only summary property +// the detection logic ever consults. +func summaryAppName(stream []byte) []byte { + if len(stream) < sectionDeclOffset+20 { + return nil + } + sdOff := binary.LittleEndian.Uint32(stream[sectionDeclOffset+16:]) + if uint64(sdOff)+8 > uint64(len(stream)) { + return nil + } + section := stream[sdOff:] + shLen := binary.LittleEndian.Uint32(section[0:]) + nProps := binary.LittleEndian.Uint32(section[4:]) + if uint64(shLen) > uint64(len(section)) || nProps > 1<<16 || 8+8*nProps > shLen { + return nil + } + for i := uint32(0); i < nProps; i++ { + base := 8 + 8*i + id := binary.LittleEndian.Uint32(section[base:]) + if id != propIDNameOfApplication { + continue + } + off := binary.LittleEndian.Uint32(section[base+4:]) + if uint64(off)+8 > uint64(shLen) { + return nil + } + typ := binary.LittleEndian.Uint32(section[off:]) + if typ&typeVector != 0 { + return nil + } + step := uint32(0) + switch typ & typeMask { + case typeStringASCII: + step = 1 + case typeStringWide: + step = 2 + default: + return nil + } + slen := binary.LittleEndian.Uint32(section[off+4:]) + start := uint64(off) + 8 + end := start + uint64(slen)*uint64(step) + if end > uint64(shLen) { + return nil + } + return printableLowBytes(section[start:end], int(step)) + } + return nil +} + +// printableLowBytes copies the printable low byte of each step-byte unit +// in b, stopping at the first NUL. +func printableLowBytes(b []byte, step int) []byte { + out := make([]byte, 0, len(b)/step) + for i := 0; i+step <= len(b); i += step { + c := b[i] + if c == 0 { + break + } + if c >= 0x20 && c < 0x7f { + out = append(out, c) + } + } + return out +} + +// pattern is a case-insensitive substring → CDFType mapping. Entries are +// tested in order; first match wins. needle is stored upper-cased so it can be +// matched case-insensitively by scan.Bytes.Search with scan.IgnoreCase. +type pattern struct { + needle []byte + typ CDFType +} + +// app2type maps NameOfApplication values to CDFTypes. +// Mirrors app2mime[] in libmagic. Needles are upper-cased for case-insensitive +// matching via scan.IgnoreCase. +var app2type = []pattern{ + {[]byte("WORD"), CDFTypeDoc}, + {[]byte("EXCEL"), CDFTypeXls}, + {[]byte("POWERPOINT"), CDFTypePpt}, + {[]byte("ADVANCED INSTALLER"), CDFTypeInstaller}, + {[]byte("INSTALLSHIELD"), CDFTypeInstaller}, + {[]byte("MICROSOFT PATCH COMPILER"), CDFTypeInstaller}, + {[]byte("NANT"), CDFTypeInstaller}, + {[]byte("WINDOWS INSTALLER"), CDFTypeInstaller}, +} + +// name2type maps directory entry names to CDFTypes. +// Mirrors name2mime[] in libmagic. Needles are upper-cased for case-insensitive +// matching via scan.IgnoreCase. +var name2type = []pattern{ + {[]byte("BOOK"), CDFTypeXls}, + {[]byte("WORKBOOK"), CDFTypeXls}, + {[]byte("WORDDOCUMENT"), CDFTypeDoc}, + {[]byte("POWERPOINT"), CDFTypePpt}, + {[]byte("DIGITALSIGNATURE"), CDFTypeInstaller}, +} + +// lookupSubstring returns the CDFType for the first entry in t whose needle +// is a case-insensitive substring of v. Mirrors C's strcasestr semantics +// under the C locale. It allocates nothing: scan.IgnoreCase matches the +// upper-cased needle against input of either case. +func lookupSubstring(v []byte, t []pattern) (CDFType, bool) { + s := scan.Bytes(v) + for _, p := range t { + if i, _ := s.Search(p.needle, scan.IgnoreCase); i != -1 { + return p.typ, true + } + } + return CDFTypeGeneric, false +} + +// msiCLSID is the Microsoft Installer root-storage CLSID, in on-disk byte +// order (cdf_directory_t.d_storage_uuid stores two little-endian uint64s). +var msiCLSID = []byte{ + 0x84, 0x10, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, +} + +// section is a (directory entry name, type) → CDFType mapping. +type section struct { + name string + typ uint8 + cdf CDFType +} + +// sectionTypes maps distinctive directory entries to CDFTypes — a flattened +// equivalent of sectioninfo[] in libmagic. Used as a fallback when no +// SummaryInformation stream is present. A slice (rather than a map) lets +// lookupSection compare entry names without allocating a string key. +var sectionTypes = []section{ + // libmagic uses application/encrypted, but that is not a registered media type. + // For now, we skip identifying that and fall-back on CDFTypeGeneric + // {"EncryptedPackage", dirTypeUserStream, CDFTypeEncrypted}, + // {"EncryptedSummary", dirTypeUserStream, CDFTypeEncrypted}, + {"Book", dirTypeUserStream, CDFTypeXls}, + {"Workbook", dirTypeUserStream, CDFTypeXls}, + {"WordDocument", dirTypeUserStream, CDFTypeDoc}, + {"PowerPoint Document", dirTypeUserStream, CDFTypePpt}, + {"__properties_version1.0", dirTypeUserStream, CDFTypeMsg}, + {"__recip_version1.0_#00000000", dirTypeUserStorage, CDFTypeMsg}, +} + +// lookupSection returns the CDFType for a directory entry whose name and type +// match a sectionTypes entry exactly. The string(name) == comparison is +// optimized by the compiler to avoid allocating. +func lookupSection(name []byte, typ uint8) (CDFType, bool) { + for _, s := range sectionTypes { + if s.typ == typ && string(name) == s.name { + return s.cdf, true + } + } + return CDFTypeGeneric, false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go new file mode 100644 index 0000000..d17e629 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/charset/charset.go @@ -0,0 +1,267 @@ +package charset + +import ( + "bytes" + "strings" + "unicode/utf8" + + "github.com/gabriel-vasile/mimetype/internal/markup" + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +const ( + F = 0 /* character never appears in text */ + T = 1 /* character appears in plain ASCII text */ + I = 2 /* character appears in ISO-8859 text */ + X = 3 /* character appears in non-ISO extended ASCII (Mac, IBM PC) */ +) + +var ( + boms = []struct { + bom []byte + enc string + }{ + {[]byte{0xEF, 0xBB, 0xBF}, "utf-8"}, + {[]byte{0x00, 0x00, 0xFE, 0xFF}, "utf-32be"}, + {[]byte{0xFF, 0xFE, 0x00, 0x00}, "utf-32le"}, + {[]byte{0xFE, 0xFF}, "utf-16be"}, + {[]byte{0xFF, 0xFE}, "utf-16le"}, + } + + // https://github.com/file/file/blob/fa93fb9f7d21935f1c7644c47d2975d31f12b812/src/encoding.c#L241 + textChars = [256]byte{ + /* BEL BS HT LF VT FF CR */ + F, F, F, F, F, F, F, T, T, T, T, T, T, T, F, F, /* 0x0X */ + /* ESC */ + F, F, F, F, F, F, F, F, F, F, F, T, F, F, F, F, /* 0x1X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x2X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x3X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x4X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x5X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, /* 0x6X */ + T, T, T, T, T, T, T, T, T, T, T, T, T, T, T, F, /* 0x7X */ + /* NEL */ + X, X, X, X, X, T, X, X, X, X, X, X, X, X, X, X, /* 0x8X */ + X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, X, /* 0x9X */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xaX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xbX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xcX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xdX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xeX */ + I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, I, /* 0xfX */ + } +) + +// FromBOM returns the charset declared in the BOM of content. +func FromBOM(content []byte) string { + for _, b := range boms { + if bytes.HasPrefix(content, b.bom) { + return b.enc + } + } + return "" +} + +// FromPlain returns the charset of a plain text. It relies on BOM presence +// and it falls back on checking each byte in content. +func FromPlain(content []byte) string { + if len(content) == 0 { + return "" + } + if cset := FromBOM(content); cset != "" { + return cset + } + origContent := content + // Try to detect UTF-8. + // First eliminate any partial rune at the end. + for i := len(content) - 1; i >= 0 && i > len(content)-4; i-- { + b := content[i] + if b < 0x80 { + break + } + if utf8.RuneStart(b) { + content = content[:i] + break + } + } + // ASCII is a subset of UTF8. Follow W3C recommendation and replace with UTF8. + if utf8.Valid(content) { + return "utf-8" + } + + return latin(origContent) +} + +func latin(content []byte) string { + hasControlBytes := false + for _, b := range content { + t := textChars[b] + if t != T && t != I { + return "" + } + if b >= 0x80 && b <= 0x9F { + hasControlBytes = true + } + } + // Code range 0x80 to 0x9F is reserved for control characters in ISO-8859-1 + // (so-called C1 Controls). Windows 1252, however, has printable punctuation + // characters in this range. + if hasControlBytes { + return "windows-1252" + } + return "iso-8859-1" +} + +// FromXML returns the charset of an XML document. It relies on the XML +// header and falls back on the plain +// text content. +func FromXML(content []byte) string { + if cset := fromXML(content); cset != "" { + return cset + } + return FromPlain(content) +} +func fromXML(s scan.Bytes) string { + xml := []byte(" and falls back on the +// plain text content. +func FromHTML(content []byte) string { + if cset := FromBOM(content); cset != "" { + return cset + } + if cset := fromHTML(content); cset != "" { + return cset + } + return FromPlain(content) +} + +func fromHTML(s scan.Bytes) string { + const ( + dontKnow = iota + doNeedPragma + doNotNeedPragma + ) + meta := []byte(" 0 && line[n-1] == '\r' { + return line[:n-1], false // drop \r at end of line + } + + // This line is problematic. The logic from CountFields comes from + // encoding/csv.Reader which relies on mutating the input bytes. + // https://github.com/golang/go/blob/b3251514531123d7fd007682389bce7428d159a0/src/encoding/csv/reader.go#L275-L279 + // To avoid mutating the input, we return cutShort. #680 + if n >= 2 && line[n-2] == '\r' && line[n-1] == '\n' { + return line[:n-2], true + } + return line, false +} + +// CountFields reads one CSV line and counts how many records that line contained. +// hasMore reports whether there are more lines in the input. +// collectIndexes makes CountFields return a list of indexes where CSV fields +// start in the line. These indexes are used to test the correctness against the +// encoding/csv parser. +func (r *Parser) CountFields(collectIndexes bool) (fields int, fieldPos []int, hasMore bool) { + finished := false + var line scan.Bytes + cutShort := false + for { + line, cutShort = r.readLine() + if finished { + return 0, nil, false + } + finished = len(*r.s) == 0 && len(line) == 0 + if len(line) == lengthNL(line) { + line = nil + continue // Skip empty lines. + } + if len(line) > 0 && line[0] == r.comment { + line = nil + continue + } + break + } + + indexes := []int{} + originalLine := line +parseField: + for { + if len(line) == 0 || line[0] != '"' { // non-quoted string field + fields++ + if collectIndexes { + indexes = append(indexes, len(originalLine)-len(line)) + } + i := bytes.IndexByte(line, r.comma) + if i >= 0 { + line.Advance(i + 1) // 1 to get over ending comma + continue parseField + } + break parseField + } else { // Quoted string field. + if collectIndexes { + indexes = append(indexes, len(originalLine)-len(line)) + } + line.Advance(1) // get over starting quote + for { + i := bytes.IndexByte(line, '"') + if i >= 0 { + line.Advance(i + 1) // 1 for ending quote + switch rn := line.Peek(); { + case rn == '"': + line.Advance(1) + case rn == r.comma: + line.Advance(1) + fields++ + continue parseField + case lengthNL(line) == len(line): + fields++ + break parseField + } + } else if len(line) > 0 || cutShort { + line, cutShort = r.readLine() + originalLine = line + } else { + fields++ + break parseField + } + } + } + } + + return fields, indexes, fields != 0 +} + +// lengthNL reports the number of bytes for the trailing \n. +func lengthNL(b []byte) int { + if len(b) > 0 && b[len(b)-1] == '\n' { + return 1 + } + return 0 +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go new file mode 100644 index 0000000..a1c6912 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/json/parser.go @@ -0,0 +1,470 @@ +package json + +import ( + "bytes" + "sync" +) + +const ( + QueryNone = "json" + QueryGeo = "geo" + QueryHAR = "har" + QueryGLTF = "gltf" + QueryCDX = "cdx" + maxRecursion = 4096 +) + +var queries = map[string][]query{ + QueryNone: nil, + QueryGeo: {{ + SearchPath: [][]byte{[]byte("type")}, + SearchVals: [][]byte{ + []byte(`"Feature"`), + []byte(`"FeatureCollection"`), + []byte(`"Point"`), + []byte(`"LineString"`), + []byte(`"Polygon"`), + []byte(`"MultiPoint"`), + []byte(`"MultiLineString"`), + []byte(`"MultiPolygon"`), + []byte(`"GeometryCollection"`), + }, + }}, + QueryHAR: {{ + SearchPath: [][]byte{[]byte("log"), []byte("version")}, + }, { + SearchPath: [][]byte{[]byte("log"), []byte("creator")}, + }, { + SearchPath: [][]byte{[]byte("log"), []byte("entries")}, + }}, + QueryGLTF: {{ + SearchPath: [][]byte{[]byte("asset"), []byte("version")}, + SearchVals: [][]byte{[]byte(`"1.0"`), []byte(`"2.0"`)}, + }}, + QueryCDX: {{ + SearchPath: [][]byte{[]byte("bomFormat")}, + SearchVals: [][]byte{[]byte(`"CycloneDX"`)}, + }}, +} + +var parserPool = sync.Pool{ + New: func() any { + return &parserState{maxRecursion: maxRecursion} + }, +} + +// parserState holds the state of JSON parsing. The number of inspected bytes, +// the current path inside the JSON object, etc. +type parserState struct { + // ib represents the number of inspected bytes. + // Because mimetype limits itself to only reading the header of the file, + // it means sometimes the input JSON can be truncated. In that case, we want + // to still detect it as JSON, even if it's invalid/truncated. + // When ib == len(input) it means the JSON was valid (at least the header). + ib int + maxRecursion int + // currPath keeps a track of the JSON keys parsed up. + // It works only for JSON objects. JSON arrays are ignored + // mainly because the functionality is not needed. + currPath [][]byte + // firstToken stores the first JSON token encountered in input. + firstToken int + // querySatisfied is true if both path and value of any queries passed to + // consumeAny are satisfied. + querySatisfied bool +} + +// query holds information about a combination of {"key": "val"} that we're trying +// to search for inside the JSON. +type query struct { + // SearchPath represents the whole path to look for inside the JSON. + // ex: [][]byte{[]byte("foo"), []byte("bar")} matches {"foo": {"bar": "baz"}} + SearchPath [][]byte + // SearchVals represents values to look for when the SearchPath is found. + // Each SearchVal element is tried until one of them matches (logical OR.) + SearchVals [][]byte +} + +func eq(path1, path2 [][]byte) bool { + if len(path1) != len(path2) { + return false + } + for i := range path1 { + if !bytes.Equal(path1[i], path2[i]) { + return false + } + } + return true +} + +// Parse will take out a parser from the pool depending on queryType and tries +// to parse raw bytes as JSON. +func Parse(queryType string, raw []byte) (parsed, inspected, firstToken int, querySatisfied bool) { + p := parserPool.Get().(*parserState) + defer func() { + // Avoid hanging on to too much memory in extreme input cases. + if len(p.currPath) > 128 { + p.currPath = nil + } + parserPool.Put(p) + }() + p.reset() + + qs := queries[queryType] + got := p.consumeAny(raw, qs, 0) + return got, p.ib, p.firstToken, p.querySatisfied +} + +func (p *parserState) reset() { + p.ib = 0 + p.currPath = p.currPath[0:0] + p.firstToken = TokInvalid + p.querySatisfied = false +} + +func (p *parserState) consumeSpace(b []byte) (n int) { + for len(b) > 0 && isSpace(b[0]) { + b = b[1:] + n++ + p.ib++ + } + return n +} + +func (p *parserState) consumeConst(b, cnst []byte) int { + lb := len(b) + for i, c := range cnst { + if lb > i && b[i] == c { + p.ib++ + } else { + return 0 + } + } + return len(cnst) +} + +func (p *parserState) consumeString(b []byte) (n int) { + var c byte + for len(b[n:]) > 0 { + c, n = b[n], n+1 + p.ib++ + switch c { + case '\\': + if len(b[n:]) == 0 { + return 0 + } + switch b[n] { + case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': + n++ + p.ib++ + continue + case 'u': + n++ + p.ib++ + for j := 0; j < 4 && len(b[n:]) > 0; j++ { + if !isXDigit(b[n]) { + return 0 + } + n++ + p.ib++ + } + continue + default: + return 0 + } + case '"': + return n + default: + continue + } + } + return 0 +} + +func (p *parserState) consumeNumber(b []byte) (n int) { + got := false + var i int + + if len(b) == 0 { + goto out + } + if b[0] == '-' { + b, i = b[1:], i+1 + p.ib++ + } + + for len(b) > 0 { + if !isDigit(b[0]) { + break + } + got = true + b, i = b[1:], i+1 + p.ib++ + } + if len(b) == 0 { + goto out + } + if b[0] == '.' { + b, i = b[1:], i+1 + p.ib++ + } + for len(b) > 0 { + if !isDigit(b[0]) { + break + } + got = true + b, i = b[1:], i+1 + p.ib++ + } + if len(b) == 0 { + goto out + } + if got && (b[0] == 'e' || b[0] == 'E') { + b, i = b[1:], i+1 + p.ib++ + got = false + if len(b) == 0 { + goto out + } + if b[0] == '+' || b[0] == '-' { + b, i = b[1:], i+1 + p.ib++ + } + for len(b) > 0 { + if !isDigit(b[0]) { + break + } + got = true + b, i = b[1:], i+1 + p.ib++ + } + } +out: + if got { + return i + } + return 0 +} + +// openArray is used instead of an inline []byte{'['} to avoid mem alllocs. +var openArray = []byte{'['} + +func (p *parserState) consumeArray(b []byte, qs []query, lvl int) (n int) { + p.appendPath(openArray, qs) + if len(b) == 0 { + return 0 + } + + for n < len(b) { + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + if b[n] == ']' { + p.ib++ + p.popLastPath(qs) + return n + 1 + } + innerParsed := p.consumeAny(b[n:], qs, lvl) + if innerParsed == 0 { + return 0 + } + n += innerParsed + if len(b[n:]) == 0 { + return 0 + } + switch b[n] { + case ',': + n += 1 + p.ib++ + continue + case ']': + p.ib++ + return n + 1 + default: + return 0 + } + } + return 0 +} + +func queryPathMatch(qs []query, path [][]byte) int { + for i := range qs { + if eq(qs[i].SearchPath, path) { + return i + } + } + return -1 +} + +// appendPath will append a path fragment if queries is not empty. +// If we don't need query functionality (just checking if a JSON is valid), +// then we can skip keeping track of the path we're currently in. +func (p *parserState) appendPath(path []byte, qs []query) { + if len(qs) != 0 { + p.currPath = append(p.currPath, path) + } +} +func (p *parserState) popLastPath(qs []query) { + if len(qs) != 0 { + p.currPath = p.currPath[:len(p.currPath)-1] + } +} + +func (p *parserState) consumeObject(b []byte, qs []query, lvl int) (n int) { + for n < len(b) { + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + if b[n] == '}' { + p.ib++ + return n + 1 + } + if b[n] != '"' { + return 0 + } else { + n += 1 + p.ib++ + } + // queryMatched stores the index of the query satisfying the current path. + queryMatched := -1 + if keyLen := p.consumeString(b[n:]); keyLen == 0 { + return 0 + } else { + p.appendPath(b[n:n+keyLen-1], qs) + if !p.querySatisfied { + queryMatched = queryPathMatch(qs, p.currPath) + } + n += keyLen + } + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + if b[n] != ':' { + return 0 + } else { + n += 1 + p.ib++ + } + n += p.consumeSpace(b[n:]) + if len(b[n:]) == 0 { + return 0 + } + + if valLen := p.consumeAny(b[n:], qs, lvl); valLen == 0 { + return 0 + } else { + if queryMatched != -1 { + q := qs[queryMatched] + if len(q.SearchVals) == 0 { + p.querySatisfied = true + } + for _, val := range q.SearchVals { + if bytes.Equal(val, bytes.TrimSpace(b[n:n+valLen])) { + p.querySatisfied = true + } + } + } + n += valLen + } + if len(b[n:]) == 0 { + return 0 + } + switch b[n] { + case ',': + p.popLastPath(qs) + n++ + p.ib++ + continue + case '}': + p.popLastPath(qs) + p.ib++ + return n + 1 + default: + return 0 + } + } + return 0 +} + +func (p *parserState) consumeAny(b []byte, qs []query, lvl int) (n int) { + // Avoid too much recursion. + if p.maxRecursion != 0 && lvl > p.maxRecursion { + return 0 + } + if len(qs) == 0 { + p.querySatisfied = true + } + n += p.consumeSpace(b) + if len(b[n:]) == 0 { + return 0 + } + + var t, rv int + switch b[n] { + case '"': + n++ + p.ib++ + rv = p.consumeString(b[n:]) + t = TokString + case '[': + n++ + p.ib++ + rv = p.consumeArray(b[n:], qs, lvl+1) + t = TokArray + case '{': + n++ + p.ib++ + rv = p.consumeObject(b[n:], qs, lvl+1) + t = TokObject + case 't': + rv = p.consumeConst(b[n:], []byte("true")) + t = TokTrue + case 'f': + rv = p.consumeConst(b[n:], []byte("false")) + t = TokFalse + case 'n': + rv = p.consumeConst(b[n:], []byte("null")) + t = TokNull + default: + rv = p.consumeNumber(b[n:]) + t = TokNumber + } + if lvl == 0 { + p.firstToken = t + } + if rv <= 0 { + return n + } + n += rv + n += p.consumeSpace(b[n:]) + return n +} + +func isSpace(c byte) bool { + return c == ' ' || c == '\t' || c == '\r' || c == '\n' +} +func isDigit(c byte) bool { + return '0' <= c && c <= '9' +} + +func isXDigit(c byte) bool { + if isDigit(c) { + return true + } + return ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F') +} + +const ( + TokInvalid = 0 + TokNull = 1 << iota + TokTrue + TokFalse + TokNumber + TokString + TokArray + TokObject + TokComma +) diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go new file mode 100644 index 0000000..0b4c62f --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/archive.go @@ -0,0 +1,221 @@ +package magic + +import ( + "bytes" + "encoding/binary" +) + +// SevenZ matches a 7z archive. +func SevenZ(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C}) +} + +// Gzip matches gzip files based on http://www.zlib.org/rfc-gzip.html#header-trailer. +func Gzip(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x1f, 0x8b}) +} + +// Fits matches an Flexible Image Transport System file. +func Fits(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{ + 0x53, 0x49, 0x4D, 0x50, 0x4C, 0x45, 0x20, 0x20, 0x3D, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, + 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x54, + }) +} + +// Xar matches an eXtensible ARchive format file. +func Xar(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x78, 0x61, 0x72, 0x21}) +} + +// Bz2 matches a bzip2 file. +func Bz2(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x42, 0x5A, 0x68}) +} + +// Ar matches an ar (Unix) archive file. +func Ar(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E}) +} + +// Deb matches a Debian package file. +func Deb(raw []byte, _ uint32) bool { + return offset(raw, []byte{ + 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, + 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79, + }, 8) +} + +// Warc matches a Web ARChive file. +func Warc(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("WARC/1.0")) || + bytes.HasPrefix(raw, []byte("WARC/1.1")) +} + +// Cab matches a Microsoft Cabinet archive file. +func Cab(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("MSCF\x00\x00\x00\x00")) +} + +// Xz matches an xz compressed stream based on https://tukaani.org/xz/xz-file-format.txt. +func Xz(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}) +} + +// Lzip matches an Lzip compressed file. +func Lzip(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x4c, 0x5a, 0x49, 0x50}) +} + +// RPM matches an RPM or Delta RPM package file. +func RPM(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0xed, 0xab, 0xee, 0xdb}) || + bytes.HasPrefix(raw, []byte("drpm")) +} + +// RAR matches a RAR archive file. +func RAR(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("Rar!\x1A\x07\x00")) || + bytes.HasPrefix(raw, []byte("Rar!\x1A\x07\x01\x00")) +} + +// InstallShieldCab matches an InstallShield Cabinet archive file. +func InstallShieldCab(raw []byte, _ uint32) bool { + return len(raw) > 7 && + bytes.Equal(raw[0:4], []byte("ISc(")) && + raw[6] == 0 && + (raw[7] == 1 || raw[7] == 2 || raw[7] == 4) +} + +// Zstd matches a Zstandard archive file. +// https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md +func Zstd(raw []byte, limit uint32) bool { + if len(raw) < 4 { + return false + } + sig := binary.LittleEndian.Uint32(raw) + // Check for Zstandard frames and skippable frames. + return (sig >= 0xFD2FB522 && sig <= 0xFD2FB528) || + (sig >= 0x184D2A50 && sig <= 0x184D2A5F) +} + +// CRX matches a Chrome extension file: a zip archive prepended by a package header. +func CRX(raw []byte, limit uint32) bool { + const minHeaderLen = 16 + if len(raw) < minHeaderLen || !bytes.HasPrefix(raw, []byte("Cr24")) { + return false + } + pubkeyLen := int64(binary.LittleEndian.Uint32(raw[8:12])) + sigLen := int64(binary.LittleEndian.Uint32(raw[12:16])) + zipOffset := minHeaderLen + pubkeyLen + sigLen + if zipOffset < 0 || int64(len(raw)) < zipOffset { + return false + } + return Zip(raw[zipOffset:], limit) +} + +// Cpio matches a cpio archive file. +func Cpio(raw []byte, _ uint32) bool { + if len(raw) < 6 { + return false + } + return binary.LittleEndian.Uint16(raw) == 070707 || // binary cpio + bytes.HasPrefix(raw, []byte("070707")) || // portable ASCII cpios + bytes.HasPrefix(raw, []byte("070701")) || + bytes.HasPrefix(raw, []byte("070702")) +} + +// Tar matches a (t)ape (ar)chive file. +// Tar files are divided into 512 bytes records. First record contains a 257 +// bytes header padded with NUL. +func Tar(raw []byte, _ uint32) bool { + const sizeRecord = 512 + + // The structure of a tar header: + // type TarHeader struct { + // Name [100]byte + // Mode [8]byte + // Uid [8]byte + // Gid [8]byte + // Size [12]byte + // Mtime [12]byte + // Chksum [8]byte + // Linkflag byte + // Linkname [100]byte + // Magic [8]byte + // Uname [32]byte + // Gname [32]byte + // Devmajor [8]byte + // Devminor [8]byte + // } + + if len(raw) < sizeRecord { + return false + } + raw = raw[:sizeRecord] + + // First 100 bytes of the header represent the file name. + // Check if file looks like Gentoo GLEP binary package. + if bytes.Contains(raw[:100], []byte("/gpkg-1\x00")) { + return false + } + + // Get the checksum recorded into the file. + recsum := tarParseOctal(raw[148:156]) + if recsum == -1 { + return false + } + sum1, sum2 := tarChksum(raw) + return recsum == sum1 || recsum == sum2 +} + +// tarParseOctal converts octal string to decimal int. +func tarParseOctal(b []byte) int64 { + // Because unused fields are filled with NULs, we need to skip leading NULs. + // Fields may also be padded with spaces or NULs. + // So we remove leading and trailing NULs and spaces to be sure. + b = bytes.Trim(b, " \x00") + + if len(b) == 0 { + return -1 + } + ret := int64(0) + for _, b := range b { + if b == 0 { + break + } + if b < '0' || b > '7' { + return -1 + } + ret = (ret << 3) | int64(b-'0') + } + return ret +} + +// tarChksum computes the checksum for the header block b. +// The actual checksum is written to same b block after it has been calculated. +// Before calculation the bytes from b reserved for checksum have placeholder +// value of ASCII space 0x20. +// POSIX specifies a sum of the unsigned byte values, but the Sun tar used +// signed byte values. We compute and return both. +func tarChksum(b []byte) (unsigned, signed int64) { + for i, c := range b { + if 148 <= i && i < 156 { + c = ' ' // Treat the checksum field itself as all spaces. + } + unsigned += int64(c) + signed += int64(int8(c)) + } + return unsigned, signed +} + +// Zlib matches zlib compressed files. +func Zlib(raw []byte, _ uint32) bool { + // https://www.ietf.org/rfc/rfc6713.txt + // This check has one fault: ASCII code can satisfy it; for ex: []byte("x ") + zlib := len(raw) > 1 && + raw[0] == 'x' && binary.BigEndian.Uint16(raw)%31 == 0 + // Check that the file is not a regular text to avoid false positives. + return zlib && !Text(raw, 0) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go new file mode 100644 index 0000000..ad48d8f --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/audio.go @@ -0,0 +1,154 @@ +package magic + +import ( + "bytes" + "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/mp3" +) + +// Flac matches a Free Lossless Audio Codec file. +func Flac(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x66\x4C\x61\x43\x00\x00\x00\x22")) +} + +// Midi matches a Musical Instrument Digital Interface file. +func Midi(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x4D\x54\x68\x64")) +} + +// Ape matches a Monkey's Audio file. +func Ape(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x4D\x41\x43\x20\x96\x0F\x00\x00\x34\x00\x00\x00\x18\x00\x00\x00\x90\xE3")) +} + +// MusePack matches a Musepack file. +func MusePack(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("MPCK")) +} + +// Au matches a Sun Microsystems au file. +func Au(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x2E\x73\x6E\x64")) +} + +// Amr matches an Adaptive Multi-Rate file. +func Amr(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x23\x21\x41\x4D\x52")) +} + +// Voc matches a Creative Voice file. +func Voc(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("Creative Voice File")) +} + +// M3U matches a Playlist file. +func M3U(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("#EXTM3U\n")) || + bytes.HasPrefix(raw, []byte("#EXTM3U\r\n")) +} + +// AAC matches an Advanced Audio Coding file. +func AAC(raw []byte, _ uint32) bool { + return len(raw) > 1 && ((raw[0] == 0xFF && raw[1] == 0xF1) || (raw[0] == 0xFF && raw[1] == 0xF9)) +} + +// MP3 matches a .mp3 file. +func MP3(raw []byte, limit uint32) bool { + if len(raw) < 3 { + return false + } + + // Any ID3v2 is reported as MP3. Not entirely correct, but the mimesniff + // standard says so. https://mimesniff.spec.whatwg.org/#matching-an-audio-or-video-type-pattern + // Despite the standard only checking for "ID3", we do more validations to + // avoid false positives. + if id3v2(raw) { + return true + } + + // If no ID3v2 tag found, then we will look for MP3 frames, but: + // a. Layer III files are a lot more prevalent than Layer I and II. + // b. Layer I frame header has looser constraints than the others: many files + // with regularly repeating 0xFFFF bytes can be misidentified as MP3. + // c. MP3 files are composed of individual frames and those frames can have + // leading garbage bytes: if we want to find all valid MP3s, we have to do a + // linear search. #775, #310 + // d. There are file formats that contain MP3s inside: .mo3 and .swa + // + // Given a, b, c and d, this code: + // - initially tries to match by first two bytes in header + // - checks for .mo3 and .swa and disqualifies them + // - does linear search for Layer III + switch binary.BigEndian.Uint16(raw[:2]) & 0xFFFE { + case 0xFFFA, 0xFFF2, 0xFFE2, // layer III: v1, v2, v2.5 + 0xFFFC, 0xFFF4, // layer II: v1, v2 + 0xFFF5: // layer I: v2 + return true + } + // http://lclevy.free.fr/mo3/ + if bytes.HasPrefix(raw, []byte("MO3")) { + return false + } + + // From PRONOM: + // Macromedia licensed the MP3 technology in 1995 to use in their Shockwave + // product. .swa or Shockwave Audio was originally added as a free plugin + // (Xtras) to SoundEdit 16 to export AIFF files to .swa. + // There is no media type assigned for .swa. + if bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x01, 0x40, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00}) { + return false + } + + _, size := mp3.ExtractFrame(raw) + return size > 0 +} + +// Based on https://id3.org/Developer%20Information. +func id3v2(raw []byte) bool { + if len(raw) < 10 || !bytes.HasPrefix(raw, []byte("ID3")) { + return false + } + if raw[3] < 2 || raw[3] > 4 { // Version: ID3v2.2 - ID3v2.4. + return false + } + if raw[4] != 0 { // Revision is 0 for all versions. + return false + } + + // v2.2 uses 2 bits, v2.3 uses 3 bits and v2.4 uses 4. + // For all versions least significant 4 bits should be 0 + if raw[5]&0b1111 != 0 { + return false + } + + // Size bytes are synchsafe: most significant bit always 0. + if raw[6]&0x80 != 0 || raw[7]&0x80 != 0 || raw[8]&0x80 != 0 || raw[9]&0x80 != 0 { + return false + } + + size := uint32(raw[6])<<21 | uint32(raw[7])<<14 | uint32(raw[8])<<7 | uint32(raw[9]) + // Disallow too big frames, let's say 10MB. + return size > 0 && size < 10*1024*1024 +} + +// Wav matches a Waveform Audio File Format file. +func Wav(raw []byte, limit uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], []byte("RIFF")) && + bytes.Equal(raw[8:12], []byte{0x57, 0x41, 0x56, 0x45}) +} + +// Aiff matches Audio Interchange File Format file. +func Aiff(raw []byte, limit uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], []byte{0x46, 0x4F, 0x52, 0x4D}) && + bytes.Equal(raw[8:12], []byte{0x41, 0x49, 0x46, 0x46}) +} + +// Qcp matches a Qualcomm Pure Voice file. +func Qcp(raw []byte, limit uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[:4], []byte("RIFF")) && + bytes.Equal(raw[8:12], []byte("QLCM")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go new file mode 100644 index 0000000..d217968 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/binary.go @@ -0,0 +1,286 @@ +package magic + +import ( + "bytes" + "debug/macho" + "encoding/binary" + "slices" +) + +// Lnk matches Microsoft lnk binary format. +func Lnk(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x4C, 0x00, 0x00, 0x00, 0x01, 0x14, 0x02, 0x00}) +} + +// Wasm matches a web assembly File Format file. +func Wasm(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x00, 0x61, 0x73, 0x6D}) +} + +// Exe matches a Windows/DOS executable file. +func Exe(raw []byte, _ uint32) bool { + return len(raw) > 1 && raw[0] == 0x4D && raw[1] == 0x5A +} + +// Elf matches an Executable and Linkable Format file. +func Elf(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x7F, 0x45, 0x4C, 0x46}) +} + +// Nes matches a Nintendo Entertainment system ROM file. +func Nes(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x4E, 0x45, 0x53, 0x1A}) +} + +// SWF matches an Adobe Flash swf file. +func SWF(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("CWS")) || + bytes.HasPrefix(raw, []byte("FWS")) || + bytes.HasPrefix(raw, []byte("ZWS")) +} + +// Torrent has bencoded text in the beginning. +func Torrent(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("d8:announce")) +} + +// PAR1 matches a parquet file. +func Par1(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x50, 0x41, 0x52, 0x31}) +} + +// CBOR matches a Concise Binary Object Representation https://cbor.io/ +func CBOR(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0xD9, 0xD9, 0xF7}) +} + +// Java bytecode and Mach-O binaries share the same magic number. +// More info here https://github.com/threatstack/libmagic/blob/master/magic/Magdir/cafebabe +func classOrMachOFat(in []byte) bool { + // There should be at least 8 bytes for both of them because the only way to + // quickly distinguish them is by comparing byte at position 7 + if len(in) < 8 { + return false + } + + return binary.BigEndian.Uint32(in) == macho.MagicFat +} + +// Class matches a java class file. +func Class(raw []byte, limit uint32) bool { + return classOrMachOFat(raw) && raw[7] > 30 +} + +// MachO matches Mach-O binaries format. +func MachO(raw []byte, limit uint32) bool { + if classOrMachOFat(raw) && raw[7] < 0x14 { + return true + } + + if len(raw) < 4 { + return false + } + + be := binary.BigEndian.Uint32(raw) + le := binary.LittleEndian.Uint32(raw) + + return be == macho.Magic32 || + le == macho.Magic32 || + be == macho.Magic64 || + le == macho.Magic64 +} + +// Dbf matches a dBase file. +// https://www.dbase.com/Knowledgebase/INT/db7_file_fmt.htm +func Dbf(raw []byte, limit uint32) bool { + if len(raw) < 68 { + return false + } + + // 3rd and 4th bytes contain the last update month and day of month. + if raw[2] == 0 || raw[2] > 12 || raw[3] == 0 || raw[3] > 31 { + return false + } + + // 12, 13, 30, 31 are reserved bytes and always filled with 0x00. + if raw[12] != 0x00 || raw[13] != 0x00 || raw[30] != 0x00 || raw[31] != 0x00 { + return false + } + // Production MDX flag; + // 0x01 if a production .MDX file exists for this table; + // 0x00 if no .MDX file exists. + if raw[28] > 0x01 { + return false + } + + // dbf type is dictated by the first byte. + dbfTypes := []byte{ + 0x02, 0x03, 0x04, 0x05, 0x30, 0x31, 0x32, 0x42, 0x62, 0x7B, 0x82, + 0x83, 0x87, 0x8A, 0x8B, 0x8E, 0xB3, 0xCB, 0xE5, 0xF5, 0xF4, 0xFB, + } + return slices.Contains(dbfTypes, raw[0]) +} + +// ElfObj matches an object file. +func ElfObj(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x01 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x01)) +} + +// ElfExe matches an executable file. +func ElfExe(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x02 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x02)) +} + +// ElfLib matches a shared library file. +func ElfLib(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x03 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x03)) +} + +// ElfDump matches a core dump file. +func ElfDump(raw []byte, limit uint32) bool { + return len(raw) > 17 && ((raw[16] == 0x04 && raw[17] == 0x00) || + (raw[16] == 0x00 && raw[17] == 0x04)) +} + +// Dcm matches a DICOM medical format file. +func Dcm(raw []byte, limit uint32) bool { + return len(raw) > 131 && + bytes.Equal(raw[128:132], []byte{0x44, 0x49, 0x43, 0x4D}) +} + +// Marc matches a MARC21 (MAchine-Readable Cataloging) file. +func Marc(raw []byte, limit uint32) bool { + // File is at least 24 bytes ("leader" field size). + if len(raw) < 24 { + return false + } + + // Fixed bytes at offset 20. + if !bytes.Equal(raw[20:24], []byte("4500")) { + return false + } + + // First 5 bytes are ASCII digits. + for i := 0; i < 5; i++ { + if raw[i] < '0' || raw[i] > '9' { + return false + } + } + + // Field terminator is present in first 2048 bytes. + return bytes.Contains(raw[:min(2048, len(raw))], []byte{0x1E}) +} + +// GLB matches a glTF model format file. +// GLB is the binary file format representation of 3D models saved in +// the GL transmission Format (glTF). +// GLB uses little endian and its header structure is as follows: +// +// <-- 12-byte header --> +// | magic | version | length | +// | (uint32) | (uint32) | (uint32) | +// | \x67\x6C\x54\x46 | \x01\x00\x00\x00 | ... | +// | g l T F | 1 | ... | +// +// Visit [glTF specification] and [IANA glTF entry] for more details. +// +// [glTF specification]: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html +// [IANA glTF entry]: https://www.iana.org/assignments/media-types/model/gltf-binary +func GLB(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x67\x6C\x54\x46\x02\x00\x00\x00")) || + bytes.HasPrefix(raw, []byte("\x67\x6C\x54\x46\x01\x00\x00\x00")) +} + +// TzIf matches a Time Zone Information Format (TZif) file. +// See more: https://tools.ietf.org/id/draft-murchison-tzdist-tzif-00.html#rfc.section.3 +// Its header structure is shown below: +// +// +---------------+---+ +// | magic (4) | <-+-- version (1) +// +---------------+---+---------------------------------------+ +// | [unused - reserved for future use] (15) | +// +---------------+---------------+---------------+-----------+ +// | isutccnt (4) | isstdcnt (4) | leapcnt (4) | +// +---------------+---------------+---------------+ +// | timecnt (4) | typecnt (4) | charcnt (4) | +func TzIf(raw []byte, limit uint32) bool { + // File is at least 44 bytes (header size). + if len(raw) < 44 { + return false + } + + if !bytes.HasPrefix(raw, []byte("TZif")) { + return false + } + + // Field "typecnt" MUST not be zero. + if binary.BigEndian.Uint32(raw[36:40]) == 0 { + return false + } + + // Version has to be NUL (0x00), '2' (0x32) or '3' (0x33). + return raw[4] == 0x00 || raw[4] == 0x32 || raw[4] == 0x33 +} + +// Pyc matches a Python compiled file. +// The signatures are sourced from libmagic v5.47 +func Pyc(raw []byte, limit uint32) bool { + if len(raw) < 8 { + return false + } + + // python 1.0 through 3.7 signatures, magic/Magdir/python:13:190 + pycMagic := []uint32{ + 0x02099900, 0x03099900, 0x892e0d0a, 0x04170d0a, 0x994e0d0a, 0xfcc40d0a, + 0xfdc40d0a, 0x87c60d0a, 0x88c60d0a, 0x2aeb0d0a, 0x2beb0d0a, 0x2ded0d0a, + 0x2eed0d0a, 0x3bf20d0a, 0x3cf20d0a, 0x45f20d0a, 0x59f20d0a, 0x63f20d0a, + 0x6df20d0a, 0x6ef20d0a, 0x77f20d0a, 0x81f20d0a, 0x8bf20d0a, 0x8cf20d0a, + 0x95f20d0a, 0x9ff20d0a, 0xa9f20d0a, 0xb3f20d0a, 0xb4f20d0a, 0xc7f20d0a, + 0xd1f20d0a, 0xd2f20d0a, 0xdbf20d0a, 0xe5f20d0a, 0xeff20d0a, 0xf9f20d0a, + 0x03f30d0a, 0x04f30d0a, 0x0af30d0a, 0xb80b0d0a, 0xc20b0d0a, 0xcc0b0d0a, + 0xd60b0d0a, 0xe00b0d0a, 0xea0b0d0a, 0xf40b0d0a, 0xf50b0d0a, 0xff0b0d0a, + 0x090c0d0a, 0x130c0d0a, 0x1d0c0d0a, 0x1f0c0d0a, 0x270c0d0a, 0x3b0c0d0a, + 0x450c0d0a, 0x4f0c0d0a, 0x580c0d0a, 0x620c0d0a, 0x6c0c0d0a, 0x760c0d0a, + 0x800c0d0a, 0x8a0c0d0a, 0x940c0d0a, 0x9e0c0d0a, 0xb20c0d0a, 0xbc0c0d0a, + 0xc60c0d0a, 0xd00c0d0a, 0xda0c0d0a, 0xe40c0d0a, 0xee0c0d0a, 0xf80c0d0a, + 0x020d0d0a, 0x0c0d0d0a, 0x160d0d0a, 0x170d0d0a, 0x200d0d0a, 0x210d0d0a, + 0x2a0d0d0a, 0x2b0d0d0a, 0x2c0d0d0a, 0x2d0d0d0a, 0x2f0d0d0a, 0x300d0d0a, + 0x310d0d0a, 0x320d0d0a, 0x330d0d0a, 0x3e0d0d0a, 0x3f0d0d0a, + } + + n := binary.BigEndian.Uint32(raw) + + if slices.Contains(pycMagic, n) { + return true + } + + if raw[2] == 0x0d && raw[3] == 0x0a { + // Only two bits of flag field are currently used. + if l := binary.LittleEndian.Uint32(raw[4:]); l > 3 { + return false + } + if raw[1] == 0x0d || raw[1] == 0x0e { + return true + } + // PyPy magic numbers, magic/Magdir/python:233 + n := binary.LittleEndian.Uint16(raw) + return n == 240 || n == 256 || n == 336 || n == 384 || n == 416 + } + + return false +} + +// Pcap identifies "libpcap" capture files. +// https://www.tcpdump.org/manpages/pcap-savefile.5.html +func Pcap(raw []byte, _ uint32) bool { + if len(raw) < 4 { + return false + } + be := binary.BigEndian.Uint32(raw) + le := binary.LittleEndian.Uint32(raw) + return be == 0xa1b2c3d4 || be == 0xa1b23c4d || + le == 0xa1b2c3d4 || le == 0xa1b23c4d +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/database.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/database.go new file mode 100644 index 0000000..35c3f91 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/database.go @@ -0,0 +1,21 @@ +package magic + +import "bytes" + +// Sqlite matches an SQLite database file. +func Sqlite(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{ + 0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, + 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00, + }) +} + +// MsAccessAce matches Microsoft Access dababase file. +func MsAccessAce(raw []byte, _ uint32) bool { + return offset(raw, []byte("Standard ACE DB"), 4) +} + +// MsAccessMdb matches legacy Microsoft Access database file (JET, 2003 and earlier). +func MsAccessMdb(raw []byte, _ uint32) bool { + return offset(raw, []byte("Standard Jet DB"), 4) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go new file mode 100644 index 0000000..4261a1d --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/document.go @@ -0,0 +1,125 @@ +package magic + +import ( + "bytes" + "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// Pdf matches a Portable Document Format file. +// https://github.com/file/file/blob/11010cc805546a3e35597e67e1129a481aed40e8/magic/Magdir/pdf +func Pdf(raw []byte, _ uint32) bool { + // usual pdf signature + return bytes.HasPrefix(raw, []byte("%PDF-")) || + // new-line prefixed signature + bytes.HasPrefix(raw, []byte("\012%PDF-")) || + // UTF-8 BOM prefixed signature + bytes.HasPrefix(raw, []byte("\xef\xbb\xbf%PDF-")) +} + +// Fdf matches a Forms Data Format file. +func Fdf(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("%FDF")) +} + +// Mobi matches a Mobi file. +func Mobi(raw []byte, _ uint32) bool { + return offset(raw, []byte("BOOKMOBI"), 60) +} + +// Lit matches a Microsoft Lit file. +func Lit(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("ITOLITLS")) +} + +// PDF matches a Portable Document Format file. +// The %PDF- header should be the first thing inside the file but many +// implementations don't follow the rule. The PDF spec at Appendix H says the +// signature can be prepended by anything. +// https://bugs.astron.com/view.php?id=446 +func PDF(raw []byte, _ uint32) bool { + raw = raw[:min(len(raw), 1024)] + return bytes.Contains(raw, []byte("%PDF-")) +} + +// DjVu matches a DjVu file. +func DjVu(raw []byte, _ uint32) bool { + if len(raw) < 12 { + return false + } + if !bytes.HasPrefix(raw, []byte{0x41, 0x54, 0x26, 0x54, 0x46, 0x4F, 0x52, 0x4D}) { + return false + } + return bytes.HasPrefix(raw[12:], []byte("DJVM")) || + bytes.HasPrefix(raw[12:], []byte("DJVU")) || + bytes.HasPrefix(raw[12:], []byte("DJVI")) || + bytes.HasPrefix(raw[12:], []byte("THUM")) +} + +// P7s matches an .p7s signature File (PEM, Base64). +func P7s(raw []byte, _ uint32) bool { + // Check for PEM Encoding. + if bytes.HasPrefix(raw, []byte("-----BEGIN PKCS7")) { + return true + } + // Check if DER Encoding is long enough. + if len(raw) < 20 { + return false + } + // Magic Bytes for the signedData ASN.1 encoding. + startHeader := [][]byte{{0x30, 0x80}, {0x30, 0x81}, {0x30, 0x82}, {0x30, 0x83}, {0x30, 0x84}} + signedDataMatch := []byte{0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07} + // Check if Header is correct. There are multiple valid headers. + for i, match := range startHeader { + // If first bytes match, then check for ASN.1 Object Type. + if bytes.HasPrefix(raw, match) { + if bytes.HasPrefix(raw[i+2:], signedDataMatch) { + return true + } + } + } + + return false +} + +// Lotus123 matches a Lotus 1-2-3 spreadsheet document. +func Lotus123(raw []byte, _ uint32) bool { + if len(raw) <= 20 { + return false + } + version := binary.BigEndian.Uint32(raw) + if version == 0x00000200 { + return raw[6] != 0 && raw[7] == 0 + } + + return version == 0x00001a00 && raw[20] > 0 && raw[20] < 32 +} + +// CHM matches a Microsoft Compiled HTML Help file. +func CHM(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("ITSF\003\000\000\000\x60\000\000\000")) +} + +// Inf matches an OS/2 .inf file. +func Inf(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("HSP\x01\x9b\x00")) +} + +// Hlp matches an OS/2 .hlp file. +func Hlp(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("HSP\x10\x9b\x00")) +} + +// FrameMaker matches an Adobe FrameMaker file. +func FrameMaker(raw []byte, _ uint32) bool { + b := scan.Bytes(raw) + if !bytes.HasPrefix(b, []byte(" 48 && bytes.HasPrefix(raw, []byte("OTTO\x00")) && + bytes.Contains(raw[12:48], []byte("CFF ")) +} + +// Ttf matches a TrueType font file. +func Ttf(raw []byte, limit uint32) bool { + if !bytes.HasPrefix(raw, []byte{0x00, 0x01, 0x00, 0x00}) { + return false + } + // We cannot rely on the first 4 bytes because of false-positives. + // We have to digg deeper into the SFNT tables. + return hasSFNTTable(raw) +} + +func hasSFNTTable(raw []byte) bool { + if len(raw) < 16 { + return false + } + + // libmagic says there are 47 table names in specification, but it seems + // they reached 49 in the meantime. + // https://github.com/file/file/blob/5184ca2471c0e801c156ee120a90e669fe27b31d/magic/Magdir/fonts#L279 + // At the same time, the TrueType docs seem misleading: + // 1. https://developer.apple.com/fonts/TrueType-Reference-Manual/index.html + // 2. https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6.html + // Page 1. has 48 tables. Page 2. has 49 tables. The diff is the gcid table. + // Take a permissive approach. + possibleTables := []uint32{ + 0x61636e74, // "acnt" + 0x616e6b72, // "ankr" + 0x61766172, // "avar" + 0x62646174, // "bdat" + 0x62686564, // "bhed" + 0x626c6f63, // "bloc" + 0x62736c6e, // "bsln" + 0x636d6170, // "cmap" + 0x63766172, // "cvar" + 0x63767420, // "cvt " + 0x45425343, // "EBSC" + 0x66647363, // "fdsc" + 0x66656174, // "feat" + 0x666d7478, // "fmtx" + 0x666f6e64, // "fond" + 0x6670676d, // "fpgm" + 0x66766172, // "fvar" + 0x67617370, // "gasp" + 0x67636964, // "gcid" + 0x676c7966, // "glyf" + 0x67766172, // "gvar" + 0x68646d78, // "hdmx" + 0x68656164, // "head" + 0x68686561, // "hhea" + 0x686d7478, // "hmtx" + 0x6876676c, // "hvgl" + 0x6876706d, // "hvpm" + 0x6a757374, // "just" + 0x6b65726e, // "kern" + 0x6b657278, // "kerx" + 0x6c636172, // "lcar" + 0x6c6f6361, // "loca" + 0x6c746167, // "ltag" + 0x6d617870, // "maxp" + 0x6d657461, // "meta" + 0x6d6f7274, // "mort" + 0x6d6f7278, // "morx" + 0x6e616d65, // "name" + 0x6f706264, // "opbd" + 0x4f532f32, // "OS/2" + // The above tables come from the original Apple TTF specification, + // but the later Microsoft specification has additional tables. + // Common tables: https://learn.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats + // Layout tables: https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2 + // Even if the Microsoft specification says OpenType, the tables are + // valid for TrueType as well. + 0x47535542, // "GSUB" + 0x47504f53, // "GPOS" + 0x42415345, // "BASE" + 0x4a535446, // "JSTF" + 0x47444546, // "GDEF" + 0x4d415448, // "MATH" + 0x43424454, // "CBDT" + 0x43424c43, // "CBLC" + 0x43464620, // "CFF " + 0x43464632, // "CFF2" + 0x434f4c52, // "COLR" + 0x4350414c, // "CPAL" + 0x44534947, // "DSIG" + 0x45424454, // "EBDT" + 0x45424c43, // "EBLC" + 0x48564152, // "HVAR" + 0x4c545348, // "LTSH" + 0x4d455247, // "MERG" + 0x4d564152, // "MVAR" + 0x50434c54, // "PCLT" + 0x706f7374, // "post" + 0x70726570, // "prep" + 0x73626978, // "sbix" + 0x53544154, // "STAT" + 0x53564720, // "SVG " + 0x56444d58, // "VDMX" + 0x76686561, // "vhea" + 0x766d7478, // "vmtx" + 0x564f5247, // "VORG" + 0x56564152, // "VVAR" + } + ourTable := binary.BigEndian.Uint32(raw[12:16]) + return slices.Contains(possibleTables, ourTable) +} + +// Eot matches an Embedded OpenType font file. +func Eot(raw []byte, limit uint32) bool { + return len(raw) > 35 && + bytes.Equal(raw[34:36], []byte{0x4C, 0x50}) && + (bytes.Equal(raw[8:11], []byte{0x02, 0x00, 0x01}) || + bytes.Equal(raw[8:11], []byte{0x01, 0x00, 0x00}) || + bytes.Equal(raw[8:11], []byte{0x02, 0x00, 0x02})) +} + +// Ttc matches a TrueType Collection font file. +func Ttc(raw []byte, limit uint32) bool { + return len(raw) > 7 && + bytes.HasPrefix(raw, []byte("ttcf")) && + (bytes.Equal(raw[4:8], []byte{0x00, 0x01, 0x00, 0x00}) || + bytes.Equal(raw[4:8], []byte{0x00, 0x02, 0x00, 0x00})) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ftyp.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ftyp.go new file mode 100644 index 0000000..fc642ef --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ftyp.go @@ -0,0 +1,146 @@ +package magic + +import ( + "bytes" +) + +// AVIF matches an AV1 Image File Format still or animated. +// Wikipedia page seems outdated listing image/avif-sequence for animations. +// https://github.com/AOMediaCodec/av1-avif/issues/59 +func AVIF(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("avif"), []byte("avis")) +} + +// ThreeGP matches a 3GPP file. +func ThreeGP(raw []byte, _ uint32) bool { + return ftyp(raw, + []byte("3gp1"), []byte("3gp2"), []byte("3gp3"), []byte("3gp4"), + []byte("3gp5"), []byte("3gp6"), []byte("3gp7"), []byte("3gs7"), + []byte("3ge6"), []byte("3ge7"), []byte("3gg6"), + ) +} + +// ThreeG2 matches a 3GPP2 file. +func ThreeG2(raw []byte, _ uint32) bool { + return ftyp(raw, + []byte("3g24"), []byte("3g25"), []byte("3g26"), []byte("3g2a"), + []byte("3g2b"), []byte("3g2c"), []byte("KDDI"), + ) +} + +// AMp4 matches an audio MP4 file. +func AMp4(raw []byte, _ uint32) bool { + return ftyp(raw, + // audio for Adobe Flash Player 9+ + []byte("F4A "), []byte("F4B "), + // Apple iTunes AAC-LC (.M4A) Audio + []byte("M4B "), []byte("M4P "), + // MPEG-4 (.MP4) for SonyPSP + []byte("MSNV"), + // Nero Digital AAC Audio + []byte("NDAS"), + ) +} + +// Mqv matches a Sony / Mobile QuickTime file. +func Mqv(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("mqt ")) +} + +// M4a matches an audio M4A file. +func M4a(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("M4A ")) +} + +// M4v matches an Appl4 M4V video file. +func M4v(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("M4V "), []byte("M4VH"), []byte("M4VP")) +} + +// Heic matches a High Efficiency Image Coding (HEIC) file. +func Heic(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("heic"), []byte("heix")) +} + +// HeicSequence matches a High Efficiency Image Coding (HEIC) file sequence. +func HeicSequence(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("hevc"), []byte("hevx")) +} + +// Heif matches a High Efficiency Image File Format (HEIF) file. +func Heif(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("mif1"), []byte("heim"), []byte("heis"), []byte("avic")) +} + +// HeifSequence matches a High Efficiency Image File Format (HEIF) file sequence. +func HeifSequence(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("msf1"), []byte("hevm"), []byte("hevs"), []byte("avcs")) +} + +// Mj2 matches a Motion JPEG 2000 file: https://en.wikipedia.org/wiki/Motion_JPEG_2000. +func Mj2(raw []byte, _ uint32) bool { + return ftyp(raw, []byte("mj2s"), []byte("mjp2"), []byte("MFSM"), []byte("MGSV")) +} + +// Dvb matches a Digital Video Broadcasting file: https://dvb.org. +// https://cconcolato.github.io/mp4ra/filetype.html +// https://github.com/file/file/blob/512840337ead1076519332d24fefcaa8fac36e06/magic/Magdir/animation#L135-L154 +func Dvb(raw []byte, _ uint32) bool { + return ftyp(raw, + []byte("dby1"), []byte("dsms"), []byte("dts1"), []byte("dts2"), + []byte("dts3"), []byte("dxo "), []byte("dmb1"), []byte("dmpf"), + []byte("drc1"), []byte("dv1a"), []byte("dv1b"), []byte("dv2a"), + []byte("dv2b"), []byte("dv3a"), []byte("dv3b"), []byte("dvr1"), + []byte("dvt1"), []byte("emsg")) +} + +// TODO: add support for remaining video formats at ftyps.com. + +// QuickTime matches a QuickTime File Format file. +// https://www.loc.gov/preservation/digital/formats/fdd/fdd000052.shtml +// https://developer.apple.com/library/archive/documentation/QuickTime/QTFF/QTFFChap1/qtff1.html#//apple_ref/doc/uid/TP40000939-CH203-38190 +// https://github.com/apache/tika/blob/0f5570691133c75ac4472c3340354a6c4080b104/tika-core/src/main/resources/org/apache/tika/mime/tika-mimetypes.xml#L7758-L7777 +func QuickTime(raw []byte, _ uint32) bool { + if len(raw) < 12 { + return false + } + // First 4 bytes represent the size of the atom as unsigned int. + // Next 4 bytes are the type of the atom. + // For `ftyp` atoms check if first byte in size is 0, otherwise, a text file + // which happens to contain 'ftypqt ' at index 4 will trigger a false positive. + if bytes.Equal(raw[4:12], []byte("ftypqt ")) || + bytes.Equal(raw[4:12], []byte("ftypmoov")) { + return raw[0] == 0x00 + } + basicAtomTypes := [][]byte{ + []byte("moov\x00"), + []byte("mdat\x00"), + []byte("free\x00"), + []byte("skip\x00"), + []byte("pnot\x00"), + } + for _, a := range basicAtomTypes { + if bytes.Equal(raw[4:9], a) { + return true + } + } + return bytes.Equal(raw[:8], []byte("\x00\x00\x00\x08wide")) +} + +// Mp4 detects an .mp4 file. Mp4 detections only does a basic ftyp check. +// Mp4 has many registered and unregistered code points so it's hard to keep track +// of all. Detection will default on video/mp4 for all ftyp files. +// ISO_IEC_14496-12 is the specification for the iso container. +func Mp4(raw []byte, _ uint32) bool { + if len(raw) < 12 { + return false + } + // ftyps are made out of boxes. The first 4 bytes of the box represent + // its size in big-endian uint32. First box is the ftyp box and it is small + // in size. Check most significant byte is 0 to filter out false positive + // text files that happen to contain the string "ftyp" at index 4. + if raw[0] != 0 { + return false + } + return bytes.Equal(raw[4:8], []byte("ftyp")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go new file mode 100644 index 0000000..6cd479c --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/geo.go @@ -0,0 +1,50 @@ +package magic + +import ( + "bytes" + "encoding/binary" + "slices" +) + +// Shp matches a shape format file. +// https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf +func Shp(raw []byte, limit uint32) bool { + if len(raw) < 112 { + return false + } + + if binary.BigEndian.Uint32(raw[0:4]) != 9994 || + binary.BigEndian.Uint32(raw[4:8]) != 0 || + binary.BigEndian.Uint32(raw[8:12]) != 0 || + binary.BigEndian.Uint32(raw[12:16]) != 0 || + binary.BigEndian.Uint32(raw[16:20]) != 0 || + binary.BigEndian.Uint32(raw[20:24]) != 0 || + binary.LittleEndian.Uint32(raw[28:32]) != 1000 { + return false + } + + shapeTypes := []int{ + 0, // Null shape + 1, // Point + 3, // Polyline + 5, // Polygon + 8, // MultiPoint + 11, // PointZ + 13, // PolylineZ + 15, // PolygonZ + 18, // MultiPointZ + 21, // PointM + 23, // PolylineM + 25, // PolygonM + 28, // MultiPointM + 31, // MultiPatch + } + + return slices.Contains(shapeTypes, int(binary.LittleEndian.Uint32(raw[108:112]))) +} + +// Shx matches a shape index format file. +// https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf +func Shx(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x27, 0x0A}) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go new file mode 100644 index 0000000..d46faca --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/image.go @@ -0,0 +1,239 @@ +package magic + +import ( + "bytes" + "encoding/binary" + "slices" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// Png matches a Portable Network Graphics file. +// https://www.w3.org/TR/PNG/ +func Png(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A}) +} + +// Apng matches an Animated Portable Network Graphics file. +// https://wiki.mozilla.org/APNG_Specification +func Apng(raw []byte, _ uint32) bool { + b := scan.Bytes(raw) + b.Advance(8) // the first 8 bytes matched by regular png + + // PNG chunks are composed of: + // 4 bytes: length in big endian + // 4 bytes: chunk type + // length bytes: chunk data + // 4 bytes: CRC + // + // Limit to 32, so we don't waste time on huge inputs. + // acTL chunk must come before any IDAT chunks. + // https://www.w3.org/TR/png-3/#structure + for i := 0; i < 32 && len(b) > 0; i++ { + sz, _ := b.Uint32be() + if bytes.HasPrefix(b, []byte("acTL")) { + return true + } + if bytes.HasPrefix(b, []byte("IDAT")) { + return false + } + if !b.Advance(int(sz + 8)) { + return false + } + } + return false +} + +// Jpg matches a Joint Photographic Experts Group file. +func Jpg(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0xFF, 0xD8, 0xFF}) +} + +// Jp2 matches a JPEG 2000 Image file (ISO 15444-1). +func Jp2(raw []byte, _ uint32) bool { + return jpeg2k(raw, []byte{0x6a, 0x70, 0x32, 0x20}) +} + +// Jpx matches a JPEG 2000 Image file (ISO 15444-2). +func Jpx(raw []byte, _ uint32) bool { + return jpeg2k(raw, []byte{0x6a, 0x70, 0x78, 0x20}) +} + +// Jpm matches a JPEG 2000 Image file (ISO 15444-6). +func Jpm(raw []byte, _ uint32) bool { + return jpeg2k(raw, []byte{0x6a, 0x70, 0x6D, 0x20}) +} + +// Gif matches a Graphics Interchange Format file. +func Gif(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("GIF87a")) || + bytes.HasPrefix(raw, []byte("GIF89a")) +} + +// Bmp matches a bitmap image file. +func Bmp(raw []byte, _ uint32) bool { + if len(raw) < 18 { + return false + } + if raw[0] != 'B' || raw[1] != 'M' { + return false + } + + bmpFormat := binary.LittleEndian.Uint32(raw[14:]) + // sourced from libmagic Magdir/images + possibleFormats := []uint32{ + 48, // PC bitmap, OS/2 2.x format (DIB header size=48) + 24, // PC bitmap, OS/2 2.x format (DIB header size=24) + 16, // PC bitmap, OS/2 2.x format (DIB header size=16) + 64, // PC bitmap, OS/2 2.x format + 52, // PC bitmap, Adobe Photoshop + 56, // PC bitmap, Adobe Photoshop with alpha channel mask + 40, // PC bitmap, Windows 3.x format + 124, // PC bitmap, Windows 98/2000 and newer format + 108, // PC bitmap, Windows 95/NT4 and newer format + } + + return slices.Contains(possibleFormats, bmpFormat) +} + +// Ps matches a PostScript file. +func Ps(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("%!PS-Adobe-")) +} + +// Psd matches a Photoshop Document file. +func Psd(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("8BPS")) +} + +// Ico matches an ICO file. +func Ico(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x01, 0x00}) || + bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x02, 0x00}) +} + +// Icns matches an ICNS (Apple Icon Image format) file. +func Icns(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("icns")) +} + +// Tiff matches a Tagged Image File Format file. +func Tiff(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x49, 0x49, 0x2A, 0x00}) || + bytes.HasPrefix(raw, []byte{0x4D, 0x4D, 0x00, 0x2A}) +} + +// Bpg matches a Better Portable Graphics file. +func Bpg(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x42, 0x50, 0x47, 0xFB}) +} + +// Xcf matches GIMP image data. +func Xcf(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("gimp xcf")) +} + +// Pat matches GIMP pattern data. +func Pat(raw []byte, _ uint32) bool { + return offset(raw, []byte("GPAT"), 20) +} + +// Gbr matches GIMP brush data. +func Gbr(raw []byte, _ uint32) bool { + return offset(raw, []byte("GIMP"), 20) +} + +// Hdr matches Radiance HDR image. +// https://web.archive.org/web/20060913152809/http://local.wasp.uwa.edu.au/~pbourke/dataformats/pic/ +func Hdr(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("#?RADIANCE\n")) +} + +// Xpm matches X PixMap image data. +func Xpm(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x2F, 0x2A, 0x20, 0x58, 0x50, 0x4D, 0x20, 0x2A, 0x2F}) +} + +// Jxs matches a JPEG XS coded image file (ISO/IEC 21122-3). +func Jxs(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x00, 0x0C, 0x4A, 0x58, 0x53, 0x20, 0x0D, 0x0A, 0x87, 0x0A}) +} + +// Jxr matches Microsoft HD JXR photo file. +func Jxr(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x49, 0x49, 0xBC, 0x01}) +} + +func jpeg2k(raw []byte, sig []byte) bool { + if len(raw) < 24 { + return false + } + + if !bytes.Equal(raw[4:8], []byte{0x6A, 0x50, 0x20, 0x20}) && + !bytes.Equal(raw[4:8], []byte{0x6A, 0x50, 0x32, 0x20}) { + return false + } + return bytes.Equal(raw[20:24], sig) +} + +// Webp matches a WebP file. +func Webp(raw []byte, _ uint32) bool { + return len(raw) > 12 && + bytes.Equal(raw[0:4], []byte("RIFF")) && + bytes.Equal(raw[8:12], []byte{0x57, 0x45, 0x42, 0x50}) +} + +// Dwg matches a CAD drawing file. +func Dwg(raw []byte, _ uint32) bool { + if len(raw) < 6 || raw[0] != 0x41 || raw[1] != 0x43 { + return false + } + dwgVersions := [][]byte{ + {0x31, 0x2E, 0x34, 0x30}, + {0x31, 0x2E, 0x35, 0x30}, + {0x32, 0x2E, 0x31, 0x30}, + {0x31, 0x30, 0x30, 0x32}, + {0x31, 0x30, 0x30, 0x33}, + {0x31, 0x30, 0x30, 0x34}, + {0x31, 0x30, 0x30, 0x36}, + {0x31, 0x30, 0x30, 0x39}, + {0x31, 0x30, 0x31, 0x32}, + {0x31, 0x30, 0x31, 0x34}, + {0x31, 0x30, 0x31, 0x35}, + {0x31, 0x30, 0x31, 0x38}, + {0x31, 0x30, 0x32, 0x31}, + {0x31, 0x30, 0x32, 0x34}, + {0x31, 0x30, 0x33, 0x32}, + } + + for _, d := range dwgVersions { + if bytes.Equal(raw[2:6], d) { + return true + } + } + + return false +} + +// Jxl matches JPEG XL image file. +func Jxl(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0xFF, 0x0A}) || + bytes.HasPrefix(raw, []byte("\x00\x00\x00\x0cJXL\x20\x0d\x0a\x87\x0a")) +} + +// DXF matches Drawing Exchange Format AutoCAD file. +// There does not seem to be a clear specification and the files in the wild +// differ wildly. +// https://images.autodesk.com/adsk/files/autocad_2012_pdf_dxf-reference_enu.pdf +// +// I collected these signatures by downloading a few dozen files from +// http://cd.textfiles.com/amigaenv/DXF/OBJEKTE/ and +// https://sembiance.com/fileFormatSamples/poly/dxf/ and then +// xxd -l 16 {} | sort | uniq. +// These signatures are only for the ASCII version of DXF. There is a binary version too. +func DXF(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte(" 0\x0ASECTION\x0A")) || + bytes.HasPrefix(raw, []byte(" 0\x0D\x0ASECTION\x0D\x0A")) || + bytes.HasPrefix(raw, []byte("0\x0ASECTION\x0A")) || + bytes.HasPrefix(raw, []byte("0\x0D\x0ASECTION\x0D\x0A")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go new file mode 100644 index 0000000..f078ff3 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/magic.go @@ -0,0 +1,167 @@ +// Package magic holds the matching functions used to find MIME types. +package magic + +import ( + "bytes" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +type ( + // Detector receiveѕ the raw data of a file and returns whether the data + // meets any conditions. The limit parameter is an upper limit to the number + // of bytes received and is used to tell if the byte slice represents the + // whole file or is just the header of a file: len(raw) < limit or len(raw)>limit. + Detector func(raw []byte, limit uint32) bool + xmlSig struct { + // the local name of the root tag + localName []byte + // the namespace of the XML document + xmlns []byte + } +) + +// offset returns true if the provided signature can be +// found at offset in the raw input. +func offset(raw []byte, sig []byte, offset int) bool { + return len(raw) > offset && bytes.HasPrefix(raw[offset:], sig) +} + +// ciPrefix is like prefix but the check is case insensitive. +func ciPrefix(raw []byte, sigs ...[]byte) bool { + for _, s := range sigs { + if ciCheck(s, raw) { + return true + } + } + return false +} +func ciCheck(sig, raw []byte) bool { + if len(raw) < len(sig)+1 { + return false + } + // perform case insensitive check + for i, b := range sig { + db := raw[i] + if 'A' <= b && b <= 'Z' { + db &= 0xDF + } + if b != db { + return false + } + } + + return true +} + +// xml returns true if any of the provided XML signatures matches the raw input. +func xml(b scan.Bytes, sigs ...xmlSig) bool { + b.TrimLWS() + if len(b) == 0 { + return false + } + for _, s := range sigs { + if xmlCheck(s, b) { + return true + } + } + return false +} +func xmlCheck(sig xmlSig, raw []byte) bool { + raw = raw[:min(len(raw), 512)] + + if len(sig.localName) == 0 { + return bytes.Index(raw, sig.xmlns) > 0 + } + if len(sig.xmlns) == 0 { + return bytes.Index(raw, sig.localName) > 0 + } + + localNameIndex := bytes.Index(raw, sig.localName) + return localNameIndex != -1 && localNameIndex < bytes.Index(raw, sig.xmlns) +} + +// markup returns true is any of the HTML signatures matches the raw input. +func markup(b scan.Bytes, sigs ...[]byte) bool { + if bytes.HasPrefix(b, []byte{0xEF, 0xBB, 0xBF}) { + // We skip the UTF-8 BOM if present to ensure we correctly + // process any leading whitespace. The presence of the BOM + // is taken into account during charset detection in charset.go. + b.Advance(3) + } + b.TrimLWS() + if len(b) == 0 { + return false + } + for _, s := range sigs { + if markupCheck(s, b) { + return true + } + } + return false +} +func markupCheck(sig, raw []byte) bool { + if len(raw) < len(sig)+1 { + return false + } + + // perform case insensitive check + for i, b := range sig { + db := raw[i] + if 'A' <= b && b <= 'Z' { + db &= 0xDF + } + if b != db { + return false + } + } + // Next byte must be space or right angle bracket. + if db := raw[len(sig)]; !scan.ByteIsWS(db) && db != '>' { + return false + } + + return true +} + +// ftyp returns true if any of the FTYP signatures matches the raw input. +func ftyp(raw []byte, sigs ...[]byte) bool { + if len(raw) < 12 { + return false + } + for _, s := range sigs { + if bytes.Equal(raw[8:12], s) { + return true + } + } + return false +} + +type shebangSig struct { + sig []byte + flag scan.Flags +} + +// A valid shebang starts with the "#!" characters, +// followed by any number of spaces, +// followed by the path to the interpreter, +// and, optionally, followed by the arguments for the interpreter. +// +// Ex: +// +// #! /usr/bin/env php +// +// /usr/bin/env is the interpreter, php is the first and only argument. +func shebang(b scan.Bytes, sigs ...shebangSig) bool { + line := b.Line() + if len(line) < 2 || line[0] != '#' || line[1] != '!' { + return false + } + line = line[2:] + line.TrimLWS() + for _, s := range sigs { + if line.Match(s.sig, s.flag) != -1 { + return true + } + } + return false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/meteo.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/meteo.go new file mode 100644 index 0000000..9f5f7d6 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/meteo.go @@ -0,0 +1,20 @@ +package magic + +import "bytes" + +// GRIB matches a GRIdded Binary meteorological file. +// https://www.nco.ncep.noaa.gov/pmb/docs/on388/ +// https://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_doc/ +func GRIB(raw []byte, _ uint32) bool { + return len(raw) > 7 && + bytes.HasPrefix(raw, []byte("GRIB")) && + (raw[7] == 1 || raw[7] == 2) +} + +// BUFR matches meteorological data format for storing point or time series data. +// https://confluence.ecmwf.int/download/attachments/31064617/ecCodes_BUFR_in_a_nutshell.pdf?version=1&modificationDate=1457000352419&api=v2 +func BUFR(raw []byte, _ uint32) bool { + return len(raw) > 7 && + bytes.HasPrefix(raw, []byte("BUFR")) && + (raw[7] == 0x03 || raw[7] == 0x04) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go new file mode 100644 index 0000000..62cced0 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ms_office.go @@ -0,0 +1,238 @@ +package magic + +import ( + "bytes" + "encoding/binary" + + "github.com/gabriel-vasile/mimetype/internal/cdf" +) + +// Xlsx matches a Microsoft Excel 2007 file. +func Xlsx(raw []byte, limit uint32) bool { + return msoxml(raw, zipEntries{{ + name: []byte("xl/"), + dir: true, + }}, 100) +} + +// Docx matches a Microsoft Word 2007 file. +func Docx(raw []byte, limit uint32) bool { + return msoxml(raw, zipEntries{{ + name: []byte("word/"), + dir: true, + }}, 100) +} + +// Pptx matches a Microsoft PowerPoint 2007 file. +func Pptx(raw []byte, limit uint32) bool { + return msoxml(raw, zipEntries{{ + name: []byte("ppt/"), + dir: true, + }}, 100) +} + +// Visio matches a Microsoft Visio 2013+ file. +func Visio(raw []byte, limit uint32) bool { + return msoxml(raw, zipEntries{{ + name: []byte("visio/"), + dir: true, + }}, 100) +} + +// Ole matches an Open Linking and Embedding file. +// +// https://en.wikipedia.org/wiki/Object_Linking_and_Embedding +func Ole(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}) +} + +// Doc matches a Microsoft Word 97-2003 file. +// See: https://github.com/decalage2/oletools/blob/412ee36ae45e70f42123e835871bac956d958461/oletools/common/clsid.py +func Doc(raw []byte, _ uint32) bool { + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypeDoc { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory is past the read limit: match + // the root storage CLSID, which often lies within the first sectors. + clsids := [][]byte{ + // Microsoft Word 97-2003 Document (Word.Document.8) + {0x06, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word 6.0-7.0 Document (Word.Document.6) + {0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + // Microsoft Word Picture (Word.Picture.8) + {0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}, + } + for _, clsid := range clsids { + if matchOleClsid(raw, clsid) { + return true + } + } + return false +} + +// Ppt matches a Microsoft PowerPoint 97-2003 file or a PowerPoint 95 presentation. +func Ppt(raw []byte, limit uint32) bool { + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypePpt { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory is past the read limit. + // Root CLSID test is the safest way to identify the OLE, however, the format + // often places the root CLSID at the end of the file. + if matchOleClsid(raw, []byte{ + 0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11, + 0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8, + }) || matchOleClsid(raw, []byte{ + 0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11, + 0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3, + }) { + return true + } + + lin := len(raw) + if lin < 520 { + return false + } + pptSubHeaders := [][]byte{ + {0xA0, 0x46, 0x1D, 0xF0}, + {0x00, 0x6E, 0x1E, 0xF0}, + {0x0F, 0x00, 0xE8, 0x03}, + } + for _, h := range pptSubHeaders { + if bytes.HasPrefix(raw[512:], h) { + return true + } + } + + return lin > 1152 && bytes.Contains(raw[1152:min(4096, lin)], + []byte("P\x00o\x00w\x00e\x00r\x00P\x00o\x00i\x00n\x00t\x00 D\x00o\x00c\x00u\x00m\x00e\x00n\x00t")) +} + +// Xls matches a Microsoft Excel 97-2003 file. +func Xls(raw []byte, limit uint32) bool { + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypeXls { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory is past the read limit. + // Root CLSID test is the safest way to identify the OLE, however, the format + // often places the root CLSID at the end of the file. + if matchOleClsid(raw, []byte{ + 0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + }) || matchOleClsid(raw, []byte{ + 0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + }) { + return true + } + + lin := len(raw) + if lin < 520 { + return false + } + xlsSubHeaders := [][]byte{ + {0x09, 0x08, 0x10, 0x00, 0x00, 0x06, 0x05, 0x00}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x10}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x1F}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x22}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x23}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x28}, + {0xFD, 0xFF, 0xFF, 0xFF, 0x29}, + } + for _, h := range xlsSubHeaders { + if bytes.HasPrefix(raw[512:], h) { + return true + } + } + + return lin > 1152 && bytes.Contains(raw[1152:min(4096, lin)], + []byte("W\x00k\x00s\x00S\x00S\x00W\x00o\x00r\x00k\x00B\x00o\x00o\x00k")) +} + +// Pub matches a Microsoft Publisher file. +func Pub(raw []byte, limit uint32) bool { + return matchOleClsid(raw, []byte{ + 0x01, 0x12, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, + }) +} + +// Msg matches a Microsoft Outlook email file. +func Msg(raw []byte, limit uint32) bool { + fromParsing := cdf.Detect(raw) + if fromParsing == cdf.CDFTypeMsg { + return true + } + if fromParsing != cdf.CDFTypeGeneric { + return false + } + // Fallback for inputs where the CDF directory does not carry the streams the + // parser keys on: match the root storage CLSID instead. + return matchOleClsid(raw, []byte{ + 0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, + }) +} + +// Msi matches a Microsoft Windows Installer file. +// http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File +func Msi(raw []byte, limit uint32) bool { + return cdf.Detect(raw) == cdf.CDFTypeInstaller +} + +// One matches a Microsoft OneNote file. +func One(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte{ + 0xe4, 0x52, 0x5c, 0x7b, 0x8c, 0xd8, 0xa7, 0x4d, + 0xae, 0xb1, 0x53, 0x78, 0xd0, 0x29, 0x96, 0xd3, + }) +} + +// Helper to match by a specific CLSID of a compound file. +// +// http://fileformats.archiveteam.org/wiki/Microsoft_Compound_File +func matchOleClsid(in []byte, clsid []byte) bool { + // Microsoft Compound files v3 have a sector length of 512, while v4 has 4096. + // Change sector offset depending on file version. + // https://www.loc.gov/preservation/digital/formats/fdd/fdd000392.shtml + sectorLength := 512 + if len(in) < sectorLength { + return false + } + if in[26] == 0x04 && in[27] == 0x00 { + sectorLength = 4096 + } + + // SecID of first sector of the directory stream. + firstSecID := int(binary.LittleEndian.Uint32(in[48:52])) + + // Expected offset of CLSID for root storage object. + clsidOffset := sectorLength*(1+firstSecID) + 80 + + // #731 offset is outside in or wrapped around due to integer overflow. + if len(in) <= clsidOffset+16 || clsidOffset < 0 { + return false + } + + return bytes.HasPrefix(in[clsidOffset:], clsid) +} + +// WPD matches a WordPerfect document. +func WPD(raw []byte, _ uint32) bool { + if len(raw) < 10 { + return false + } + if !bytes.HasPrefix(raw, []byte("\xffWPC")) { + return false + } + return raw[8] == 1 && raw[9] == 10 +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go new file mode 100644 index 0000000..4baa257 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/netpbm.go @@ -0,0 +1,111 @@ +package magic + +import ( + "bytes" + "strconv" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// NetPBM matches a Netpbm Portable BitMap ASCII/Binary file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPBM(raw []byte, _ uint32) bool { + return netp(raw, "P1\n", "P4\n") +} + +// NetPGM matches a Netpbm Portable GrayMap ASCII/Binary file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPGM(raw []byte, _ uint32) bool { + return netp(raw, "P2\n", "P5\n") +} + +// NetPPM matches a Netpbm Portable PixMap ASCII/Binary file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPPM(raw []byte, _ uint32) bool { + return netp(raw, "P3\n", "P6\n") +} + +// NetPAM matches a Netpbm Portable Arbitrary Map file. +// +// See: https://en.wikipedia.org/wiki/Netpbm +func NetPAM(raw []byte, _ uint32) bool { + if !bytes.HasPrefix(raw, []byte("P7\n")) { + return false + } + w, h, d, m, e := false, false, false, false, false + s := scan.Bytes(raw) + var l scan.Bytes + // Read line by line. + for i := 0; i < 128; i++ { + l = s.Line() + // If the line is empty or a comment, skip. + if len(l) == 0 || l.Peek() == '#' { + if len(s) == 0 { + return false + } + continue + } else if bytes.HasPrefix(l, []byte("TUPLTYPE")) { + continue + } else if bytes.HasPrefix(l, []byte("WIDTH ")) { + w = true + } else if bytes.HasPrefix(l, []byte("HEIGHT ")) { + h = true + } else if bytes.HasPrefix(l, []byte("DEPTH ")) { + d = true + } else if bytes.HasPrefix(l, []byte("MAXVAL ")) { + m = true + } else if bytes.HasPrefix(l, []byte("ENDHDR")) { + e = true + } + // When we reached header, return true if we collected all four required headers. + // WIDTH, HEIGHT, DEPTH and MAXVAL. + if e { + return w && h && d && m + } + } + return false +} + +func netp(s scan.Bytes, prefixes ...string) bool { + foundPrefix := "" + for _, p := range prefixes { + if bytes.HasPrefix(s, []byte(p)) { + foundPrefix = p + } + } + if foundPrefix == "" { + return false + } + s.Advance(len(foundPrefix)) // jump over P1, P2, P3, etc. + + var l scan.Bytes + // Read line by line. + for i := 0; i < 128; i++ { + l = s.Line() + // If the line is a comment, skip. + if l.Peek() == '#' { + continue + } + // If line has leading whitespace, then skip over whitespace. + for scan.ByteIsWS(l.Peek()) { + l.Advance(1) + } + if len(s) == 0 || len(l) > 0 { + break + } + } + + // At this point l should be the two integers denoting the size of the matrix. + width := l.PopUntil(scan.ASCIISpaces...) + for scan.ByteIsWS(l.Peek()) { + l.Advance(1) + } + height := l.PopUntil(scan.ASCIISpaces...) + + w, errw := strconv.ParseInt(string(width), 10, 64) + h, errh := strconv.ParseInt(string(height), 10, 64) + return errw == nil && errh == nil && w > 0 && h > 0 +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ogg.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ogg.go new file mode 100644 index 0000000..bb4cd78 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/ogg.go @@ -0,0 +1,42 @@ +package magic + +import ( + "bytes" +) + +/* + NOTE: + + In May 2003, two Internet RFCs were published relating to the format. + The Ogg bitstream was defined in RFC 3533 (which is classified as + 'informative') and its Internet content type (application/ogg) in RFC + 3534 (which is, as of 2006, a proposed standard protocol). In + September 2008, RFC 3534 was obsoleted by RFC 5334, which added + content types video/ogg, audio/ogg and filename extensions .ogx, .ogv, + .oga, .spx. + + See: + https://tools.ietf.org/html/rfc3533 + https://developer.mozilla.org/en-US/docs/Web/HTTP/Configuring_servers_for_Ogg_media#Serve_media_with_the_correct_MIME_type + https://github.com/file/file/blob/master/magic/Magdir/vorbis +*/ + +// Ogg matches an Ogg file. +func Ogg(raw []byte, limit uint32) bool { + return bytes.HasPrefix(raw, []byte("\x4F\x67\x67\x53\x00")) +} + +// OggAudio matches an audio ogg file. +func OggAudio(raw []byte, limit uint32) bool { + return len(raw) >= 37 && (bytes.HasPrefix(raw[28:], []byte("\x7fFLAC")) || + bytes.HasPrefix(raw[28:], []byte("\x01vorbis")) || + bytes.HasPrefix(raw[28:], []byte("OpusHead")) || + bytes.HasPrefix(raw[28:], []byte("Speex\x20\x20\x20"))) +} + +// OggVideo matches a video ogg file. +func OggVideo(raw []byte, limit uint32) bool { + return len(raw) >= 37 && (bytes.HasPrefix(raw[28:], []byte("\x80theora")) || + bytes.HasPrefix(raw[28:], []byte("fishead\x00")) || + bytes.HasPrefix(raw[28:], []byte("\x01video\x00\x00\x00"))) // OGM video +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go new file mode 100644 index 0000000..d36dc3c --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text.go @@ -0,0 +1,666 @@ +package magic + +import ( + "bytes" + "time" + + "github.com/gabriel-vasile/mimetype/internal/charset" + "github.com/gabriel-vasile/mimetype/internal/json" + mkup "github.com/gabriel-vasile/mimetype/internal/markup" + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// HTML matches a Hypertext Markup Language file. +func HTML(raw []byte, _ uint32) bool { + return markup(raw, + []byte(" 0 && firstNonWS == '[') + hasTargetTok = hasTargetTok || (t&json.TokObject > 0 && firstNonWS == '{') + } + if !hasTargetTok { + return false + } + lraw := len(raw) + parsed, inspected, _, querySatisfied := json.Parse(q, raw) + if !querySatisfied { + return false + } + + // If the full file content was provided, check that the whole input was parsed. + if limit == 0 || lraw < int(limit) { + return parsed == lraw + } + + // If a section of the file was provided, check if all of it was inspected. + // In other words, check that if there was a problem parsing, that problem + // occurred after the last byte in the input. + return inspected == lraw && lraw > 0 +} + +// NdJSON matches a Newline delimited JSON file. All complete lines from raw +// must be valid JSON documents meaning they contain one of the valid JSON data +// types. +func NdJSON(raw []byte, limit uint32) bool { + lCount, objOrArr := 0, 0 + + s := scan.Bytes(raw) + var l scan.Bytes + for len(s) != 0 { + l = s.Line() + parsed, inspected, firstToken, _ := json.Parse(json.QueryNone, l) + // Only the last line may be truncated by the read limit; for it, it is + // enough that the parser inspected all of it. Every other line must be a + // complete, valid JSON document, otherwise a single JSON document spread + // over multiple lines would be mistaken for NDJSON. #803 + if len(s) == 0 { + if inspected != len(l) { + return false + } + } else if parsed != len(l) { + return false + } + if firstToken == json.TokArray || firstToken == json.TokObject { + objOrArr++ + } + lCount++ + } + + return lCount > 1 && objOrArr > 0 +} + +// Svg matches a SVG file. +func Svg(raw []byte, limit uint32) bool { + return svgWithoutXMLDeclaration(raw) || svgWithXMLDeclaration(raw) +} + +// svgWithoutXMLDeclaration matches a SVG image that does not have an XML header. +// Example: +// +// +// +// +// +func svgWithoutXMLDeclaration(s scan.Bytes) bool { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + for mkup.SkipAComment(&s) { + } + if !bytes.HasPrefix(s, []byte(" +// +// +// +func svgWithXMLDeclaration(s scan.Bytes) bool { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + if !bytes.HasPrefix(s, []byte(" 4096 { + s = s[:4096] + } + return hasVersion && bytes.Contains(s, []byte(" 00:02:19,376) limits second line + // length to exactly 29 characters. + if len(line) != 29 { + return false + } + // Decimal separator of fractional seconds in the timestamps must be a + // comma, not a period. + if bytes.IndexByte(line, '.') != -1 { + return false + } + sep := []byte(" --> ") + i := bytes.Index(line, sep) + if i == -1 { + return false + } + const layout = "15:04:05,000" + t0, err := time.Parse(layout, string(line[:i])) + if err != nil { + return false + } + t1, err := time.Parse(layout, string(line[i+len(sep):])) + if err != nil { + return false + } + if t0.After(t1) { + return false + } + + line = s.Line() + // A third line must exist and not be empty. This is the actual subtitle text. + return len(line) != 0 +} + +// Vtt matches a Web Video Text Tracks (WebVTT) file. See +// https://www.iana.org/assignments/media-types/text/vtt. +func Vtt(raw []byte, limit uint32) bool { + // Prefix match. + prefixes := [][]byte{ + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // UTF-8 BOM, "WEBVTT" and a line feed + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // UTF-8 BOM, "WEBVTT" and a carriage return + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // UTF-8 BOM, "WEBVTT" and a space + {0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // UTF-8 BOM, "WEBVTT" and a horizontal tab + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0A}, // "WEBVTT" and a line feed + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x0D}, // "WEBVTT" and a carriage return + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x20}, // "WEBVTT" and a space + {0x57, 0x45, 0x42, 0x56, 0x54, 0x54, 0x09}, // "WEBVTT" and a horizontal tab + } + for _, p := range prefixes { + if bytes.HasPrefix(raw, p) { + return true + } + } + + // Exact match. + return bytes.Equal(raw, []byte{0xEF, 0xBB, 0xBF, 0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) || // UTF-8 BOM and "WEBVTT" + bytes.Equal(raw, []byte{0x57, 0x45, 0x42, 0x56, 0x54, 0x54}) // "WEBVTT" +} + +type rfc822Hint struct { + h []byte + matchFlags scan.Flags +} + +// The hints come from libmagic, but the implementation is bit different. libmagic +// only checks if the file starts with the hint, while we additionally look for +// a secondary hint in the first few lines of input. +func RFC822(raw []byte, limit uint32) bool { + b := scan.Bytes(raw) + + // Keep hints here to avoid instantiating them several times in lineHasRFC822Hint. + // The alternative is to make them a package level var, but then they'd go + // on the heap. + // Some of the hints are IgnoreCase, some not. I selected based on what libmagic + // does and based on personal observations from sample files. + hints := []rfc822Hint{ + // Enron dataset has Message-ID, Message-Id and Message-id. + {[]byte("Message-ID: "), scan.IgnoreCase}, + {[]byte("From: "), 0}, + {[]byte("To: "), 0}, + {[]byte("CC: "), scan.IgnoreCase}, + {[]byte("Date: "), 0}, + {[]byte("Subject: "), 0}, + {[]byte("Received: "), 0}, + {[]byte("Relay-Version: "), 0}, + {[]byte("#! rnews"), 0}, + {[]byte("N#! rnews"), 0}, + {[]byte("Forward to"), 0}, + {[]byte("Pipe to"), 0}, + {[]byte("DELIVERED-TO: "), scan.IgnoreCase}, + {[]byte("RETURN-PATH: "), scan.IgnoreCase}, + {[]byte("Content-Type: "), 0}, + {[]byte("Content-Transfer-Encoding: "), 0}, + } + if !lineHasRFC822Hint(b.Line(), hints) { + return false + } + for i := 0; i < 20; i++ { + if lineHasRFC822Hint(b.Line(), hints) { + return true + } + } + + return false +} + +func lineHasRFC822Hint(b scan.Bytes, hints []rfc822Hint) bool { + for _, h := range hints { + if b.Match(h.h, h.matchFlags) > -1 { + return true + } + } + return false +} + +func GEDCOM(raw []byte, limit uint32) bool { + // Skip if empty + if len(raw) == 0 { + return false + } + + // GEDCOM header fits within first 4KB + searchLimit := min(len(raw), 4096) + raw = raw[:searchLimit] + + b := scan.Bytes(raw) + + // Skip BOM if present: UTF-8, UTF-16BE, UTF-16LE + for _, bom := range [][]byte{ + {0xEF, 0xBB, 0xBF}, // UTF-8 + {0xFE, 0xFF}, // UTF-16BE + {0xFF, 0xFE}, // UTF-16LE + } { + if bytes.HasPrefix(b, bom) { + b.Advance(len(bom)) + break // Only one BOM can exist at the start + } + } + + b.TrimLWS() + + firstLine := b.Line() + if !bytes.Equal(firstLine, []byte("0 HEAD")) { + return false + } + + // "1 GEDC" is mandatory in the header + for i := 0; i < 10; i++ { + line := b.Line() + if bytes.Equal(line, []byte("1 GEDC")) { + return true + } + } + return false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go new file mode 100644 index 0000000..6fc35bd --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/text_csv.go @@ -0,0 +1,56 @@ +package magic + +import ( + "github.com/gabriel-vasile/mimetype/internal/csv" + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// CSV matches a comma-separated values file. +func CSV(raw []byte, limit uint32) bool { + return sv(raw, ',', limit) +} + +// TSV matches a tab-separated values file. +func TSV(raw []byte, limit uint32) bool { + return sv(raw, '\t', limit) +} + +func sv(in []byte, comma byte, limit uint32) bool { + s := scan.Bytes(in) + r := csv.NewParser(comma, '#', &s) + + headerFields, _, hasMore := r.CountFields(false) + if headerFields < 2 || !hasMore { + return false + } + csvLines := 1 // 1 for header + for { + fields, _, hasMore := r.CountFields(false) + if !hasMore && fields == 0 { + break + } + if fields == headerFields { + csvLines++ + } else { + // maybeTruncated signals the input was cut at the read limit, + // meaning the last line may be an incomplete CSV record. + maybeTruncated := limit > 0 && uint64(len(in)) >= uint64(limit) + if maybeTruncated && fields < headerFields { + // Allow the last row to have any number of fields + // if the input is maybeTruncated. + // BUG: if len(input) == limit, then the input is not truncated + // but it is still allowed to have the wrong number of fields + // and it will be reported as valid CSV. + if len(s) == 0 { + break + } + } + return false + } + if csvLines >= 10 { + return true + } + } + + return csvLines >= 2 +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go new file mode 100644 index 0000000..a730a24 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/video.go @@ -0,0 +1,89 @@ +package magic + +import ( + "bytes" +) + +// Flv matches a Flash video file. +func Flv(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte("\x46\x4C\x56\x01")) +} + +// Asf matches an Advanced Systems Format file. +func Asf(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{ + 0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, + 0xA6, 0xD9, 0x00, 0xAA, 0x00, 0x62, 0xCE, 0x6C, + }) +} + +// Rmvb matches a RealMedia Variable Bitrate file. +func Rmvb(raw []byte, _ uint32) bool { + return bytes.HasPrefix(raw, []byte{0x2E, 0x52, 0x4D, 0x46}) +} + +// WebM matches a WebM file. +func WebM(raw []byte, limit uint32) bool { + return isMatroskaFileTypeMatched(raw, "webm") +} + +// Mkv matches a mkv file. +func Mkv(raw []byte, limit uint32) bool { + return isMatroskaFileTypeMatched(raw, "matroska") +} + +// isMatroskaFileTypeMatched is used for webm and mkv file matching. +// It checks for .Eߣ sequence. If the sequence is found, +// then it means it is Matroska media container, including WebM. +// Then it verifies which of the file type it is representing by matching the +// file specific string. +func isMatroskaFileTypeMatched(in []byte, flType string) bool { + if bytes.HasPrefix(in, []byte("\x1A\x45\xDF\xA3")) { + return isFileTypeNamePresent(in, flType) + } + return false +} + +// isFileTypeNamePresent accepts the matroska input data stream and searches +// for the given file type in the stream. Return whether a match is found. +// The logic of search is: find first instance of \x42\x82 and then +// search for given string after n bytes of above instance. +func isFileTypeNamePresent(in []byte, flType string) bool { + ind, lenIn := 0, len(in) + maxInd := min(4096, lenIn) + ind = bytes.Index(in[:maxInd], []byte("\x42\x82")) + if ind > 0 && lenIn > ind+2 { + ind += 2 + + // filetype name will be present exactly + // n bytes after the match of the two bytes "\x42\x82" + n := vintWidth(int(in[ind])) + if lenIn > ind+n { + return bytes.HasPrefix(in[ind+n:], []byte(flType)) + } + } + return false +} + +// vintWidth parses the variable-integer width in matroska containers +func vintWidth(v int) int { + mask, nTimes, num := 128, 8, 1 + for num < nTimes && v&mask == 0 { + mask >>= 1 + num++ + } + return num +} + +// Mpeg matches a Moving Picture Experts Group file. +func Mpeg(raw []byte, limit uint32) bool { + return len(raw) > 3 && bytes.HasPrefix(raw, []byte{0x00, 0x00, 0x01}) && + raw[3] >= 0xB0 && raw[3] <= 0xBF +} + +// Avi matches an Audio Video Interleaved file. +func Avi(raw []byte, limit uint32) bool { + return len(raw) > 16 && + bytes.Equal(raw[:4], []byte("RIFF")) && + bytes.Equal(raw[8:16], []byte("AVI LIST")) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go new file mode 100644 index 0000000..9b2611b --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/magic/zip.go @@ -0,0 +1,304 @@ +package magic + +import ( + "bytes" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// Odt matches an OpenDocument Text file. +func Odt(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.text"), 30) +} + +// Ott matches an OpenDocument Text Template file. +func Ott(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.text-template"), 30) +} + +// Ods matches an OpenDocument Spreadsheet file. +func Ods(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.spreadsheet"), 30) +} + +// Ots matches an OpenDocument Spreadsheet Template file. +func Ots(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.spreadsheet-template"), 30) +} + +// Odp matches an OpenDocument Presentation file. +func Odp(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.presentation"), 30) +} + +// Otp matches an OpenDocument Presentation Template file. +func Otp(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.presentation-template"), 30) +} + +// Odg matches an OpenDocument Drawing file. +func Odg(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.graphics"), 30) +} + +// Otg matches an OpenDocument Drawing Template file. +func Otg(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.graphics-template"), 30) +} + +// Odf matches an OpenDocument Formula file. +func Odf(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.formula"), 30) +} + +// Odc matches an OpenDocument Chart file. +func Odc(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.oasis.opendocument.chart"), 30) +} + +// Epub matches an EPUB file. +func Epub(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/epub+zip"), 30) +} + +// Sxc matches an OpenOffice Spreadsheet file. +func Sxc(raw []byte, _ uint32) bool { + return offset(raw, []byte("mimetypeapplication/vnd.sun.xml.calc"), 30) +} + +// Zip matches a zip archive. +func Zip(raw []byte, limit uint32) bool { + return len(raw) > 3 && + raw[0] == 0x50 && raw[1] == 0x4B && + (raw[2] == 0x3 || raw[2] == 0x5 || raw[2] == 0x7) && + (raw[3] == 0x4 || raw[3] == 0x6 || raw[3] == 0x8) +} + +// Jar matches a Java archive file. There are two types of Jar files: +// 1. the ones that can be opened with jexec and have 0xCAFE optional flag +// https://stackoverflow.com/tags/executable-jar/info +// 2. regular jars, same as above, just without the executable flag +// https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=262278#c0 +// There is an argument to only check for manifest, since it's the common nominator +// for both executable and non-executable versions. But the traversing zip entries +// is unreliable because it does linear search for signatures +// (instead of relying on offsets told by the file.) +func Jar(raw []byte, limit uint32) bool { + return executableJar(raw) || + // First entry must be an empty META-INF directory or the manifest. + // There is no specification saying that, but the jar reader and writer + // implementations from Java do it that way. + // https://github.com/openjdk/jdk/blob/88c4678eed818cbe9380f35352e90883fed27d33/src/java.base/share/classes/java/util/jar/JarInputStream.java#L170-L173 + zipHas(raw, zipEntries{{ + name: []byte("META-INF/"), + }, { + name: []byte("META-INF/MANIFEST.MF"), + }}, 1) +} + +// KMZ matches a zipped KML file, which is "doc.kml" by convention. +func KMZ(raw []byte, _ uint32) bool { + return zipHas(raw, zipEntries{{ + name: []byte("doc.kml"), + }}, 100) +} + +// An executable Jar has a 0xCAFE flag enabled in the first zip entry. +// The rule from file/file is: +// >(26.s+30) leshort 0xcafe Java archive data (JAR) +func executableJar(b scan.Bytes) bool { + b.Advance(0x1A) + offset, ok := b.Uint16() + if !ok { + return false + } + b.Advance(int(offset) + 2) + + cafe, ok := b.Uint16() + return ok && cafe == 0xCAFE +} + +// zipIterator iterates over a zip file returning the name of the zip entries +// in that file. +type zipIterator struct { + b scan.Bytes +} + +type zipEntries []struct { + name []byte + dir bool // dir means checking just the prefix of the entry, not the whole path +} + +func (z zipEntries) match(file []byte) bool { + for i := range z { + if z[i].dir { + if bytes.HasPrefix(file, z[i].name) { + return true + } + } else { + if bytes.Equal(file, z[i].name) { + return true + } + } + } + return false +} + +func zipHas(raw scan.Bytes, searchFor zipEntries, stopAfter int) bool { + iter := zipIterator{raw} + for i := 0; i < stopAfter; i++ { + f := iter.next() + if len(f) == 0 { + break + } + if searchFor.match(f) { + return true + } + } + + return false +} + +// msoxml behaves like zipHas, but it puts restrictions on what the first zip +// entry can be. +func msoxml(raw scan.Bytes, searchFor zipEntries, stopAfter int) bool { + iter := zipIterator{raw} + for i := 0; i < stopAfter; i++ { + f := iter.next() + if len(f) == 0 { + break + } + if searchFor.match(f) { + return true + } + // If the first is not one of the next usually expected entries, + // then abort this check. + if i == 0 { + if !bytes.Equal(f, []byte("[Content_Types].xml")) && // this is a file + !bytes.HasPrefix(f, []byte("_rels/")) && // these are directories + !bytes.HasPrefix(f, []byte("docProps/")) && + !bytes.HasPrefix(f, []byte("customXml/")) && + !bytes.HasPrefix(f, []byte("[trash]/")) { + return false + } + } + } + + return false +} + +var zipLocalFileHeader = []byte("PK\003\004") + +// next extracts the name of the next zip entry. +func (i *zipIterator) next() []byte { + n := bytes.Index(i.b, zipLocalFileHeader) + if n == -1 { + return nil + } + i.b.Advance(n) + if !i.b.Advance(0x1A) { + return nil + } + l, ok := i.b.Uint16() + if !ok { + return nil + } + if !i.b.Advance(0x02) { + return nil + } + if len(i.b) < int(l) { + return nil + } + return i.b[:l] +} + +// skipZipflingerEntry tries to detect a Zipflinger virtual entry and skips it. +// The detection is based on the following properties: +// - compression method is 0 +// - CRC32 is 0 +// - compressed size is 0 +// - uncompressed size is 0 +// - file name is empty +// Returns true if it was found and skipped. +func (i *zipIterator) skipZipflingerEntry() (skipped bool) { + // Make a backup of the data so the inspection does not loses it. + b := i.b + defer func() { + // If no zipflinger was found, restore the original data. + if !skipped { + i.b = b + } + }() + + n := bytes.Index(i.b, zipLocalFileHeader) + if n == -1 { + return false + } + if !i.b.Advance(0x08) { + return false + } + + // Check compression method + if cm, ok := i.b.Uint16(); !ok || cm != 0 { + return false + } + + // Advance up to the CRC32 field + if !i.b.Advance(0x04) { + return false + } + + // Check CRC32 + if crc32, ok := i.b.Uint32(); !ok || crc32 != 0 { + return false + } + + // Check compressed size + if compressedSize, ok := i.b.Uint32(); !ok || compressedSize != 0 { + return false + } + + // Check uncompressed size + if uncompressedSize, ok := i.b.Uint32(); !ok || uncompressedSize != 0 { + return false + } + + // Check for empty file name + if l, ok := i.b.Uint16(); !ok || l != 0 { + return false + } + + // Reached a zipflinger virtual entry: skip extra data + l, ok := i.b.Uint16() + if !ok { + return false + } + + if !i.b.Advance(int(l)) { + return false + } + return true +} + +// APK matches an Android Package Archive. +// The source of signatures is https://github.com/file/file/blob/1778642b8ba3d947a779a36fcd81f8e807220a19/magic/Magdir/archive#L1820-L1887 +func APK(raw []byte, _ uint32) bool { + iter := zipIterator{raw} + + // If a Zipflinger Virtual Entry is detected, then the data is considered APK + if iter.skipZipflingerEntry() { + return true + } + + return zipHas(iter.b, zipEntries{{ + name: []byte("AndroidManifest.xml"), + }, { + name: []byte("META-INF/com/android/build/gradle/app-metadata.properties"), + }, { + name: []byte("classes.dex"), + }, { + name: []byte("resources.arsc"), + }, { + name: []byte("res/drawable"), + }}, 100) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go b/vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go new file mode 100644 index 0000000..b9abc6d --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/markup/markup.go @@ -0,0 +1,105 @@ +// Package markup implements functions for extracting info from +// HTML and XML documents. +package markup + +import ( + "bytes" + + "github.com/gabriel-vasile/mimetype/internal/scan" +) + +// GetAnAttribute assumes we passed over an SGML tag and extracts first +// attribute and its value. +// +// Initially, this code existed inside charset/charset.go, because it was part of +// implementing the https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding +// algorithm. But because extracting an attribute from a tag is the same for +// both HTML and XML, then the code was moved here. +func GetAnAttribute(s *scan.Bytes) (name, val []byte, hasMore bool) { + for scan.ByteIsWS(s.Peek()) || s.Peek() == '/' { + s.Advance(1) + } + if s.Peek() == '>' { + return nil, nil, false + } + origS, end := *s, 0 + // step 4 and 5 + for { + // bap means byte at position in the specification. + bap := s.Pop() + if bap == 0 { + return nil, nil, false + } + if bap == '=' && end > 0 { + val, hasMore := getAValue(s) + return origS[:end], val, hasMore + } else if scan.ByteIsWS(bap) { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + if s.Peek() != '=' { + return origS[:end], nil, true + } + s.Advance(1) + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + val, hasMore := getAValue(s) + return origS[:end], val, hasMore + } else if bap == '/' || bap == '>' { + return origS[:end], nil, false + } else { // for any ASCII, non-ASCII, just advance + end++ + } + } +} + +func getAValue(s *scan.Bytes) (_ []byte, hasMore bool) { + for scan.ByteIsWS(s.Peek()) { + s.Advance(1) + } + origS, end := *s, 0 + bap := s.Pop() + if bap == 0 { + return nil, false + } + end++ + // Step 10 + switch bap { + case '"', '\'': + val := s.PopUntil(bap) + if s.Pop() != bap { + return nil, false + } + return val, s.Peek() != 0 && s.Peek() != '>' + case '>': + return nil, false + } + + // Step 11 + for { + bap = s.Pop() + if bap == 0 { + return nil, false + } + switch { + case scan.ByteIsWS(bap): + return origS[:end], true + case bap == '>': + return origS[:end], false + default: + end++ + } + } +} + +func SkipAComment(s *scan.Bytes) (skipped bool) { + if bytes.HasPrefix(*s, []byte("")); i != -1 { + s.Advance(i + 2 + 3) // 2 comes from len(). + return true + } + } + return false +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/mp3/frame.go b/vendor/github.com/gabriel-vasile/mimetype/internal/mp3/frame.go new file mode 100644 index 0000000..e1ea6f2 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/mp3/frame.go @@ -0,0 +1,140 @@ +package mp3 + +import "bytes" + +// minTruncatedSyncMatches is the minimum number of confirmed successive +// header matches required to accept a candidate frame when the buffer ends +// before maxFrameSyncMatches confirmations can be performed. +const minTruncatedSyncMatches = 2 + +func ExtractFrame(b []byte) (start, size int) { + limit := min(len(b), 2048+headerSize) + for i := 0; i < limit-headerSize; i++ { + j := bytes.IndexByte(b[i:limit-headerSize], 0xFF) + if j < 0 { + break + } + i += j + hdr := header{b[i], b[i+1], b[i+2], b[i+3]} + if !hdr.valid() { + continue + } + frameBytes := hdr.frameBytes() + frameAndPad := frameBytes + hdr.padding() + + validHere := frameBytes > 0 && i+frameAndPad <= len(b) && matchFrame(b[i:]) + // When the buffer is exactly one frame, matchFrame cannot look ahead for + // a subsequent header to confirm the stream. Trust the validated header. + exact := i == 0 && frameAndPad == len(b) + if validHere || exact { + return i, frameAndPad + } + } + return 0, 0 +} + +// matchFrame confirms a candidate header by stepping forward and checking that +// subsequent headers are consistent. +func matchFrame(buf []byte) bool { + // maxFrameSyncMatches limits how many valid frames we look at. + const maxFrameSyncMatches = 10 + hdr := header{buf[0], buf[1], buf[2], buf[3]} + i := hdr.frameBytes() + hdr.padding() + for nmatch := 0; nmatch < maxFrameSyncMatches; nmatch++ { + if i+headerSize > len(buf) { + return nmatch >= minTruncatedSyncMatches + } + cmp := header{buf[i], buf[i+1], buf[i+2], buf[i+3]} + if !hdr.compatibleWith(cmp) { + return false + } + i += cmp.frameBytes() + cmp.padding() + } + return true +} + +const headerSize = 4 + +type header [headerSize]byte + +func (h header) isFreeFormat() bool { return h[2]&0xF0 == 0 } +func (h header) isMPEG1() bool { return h[1]&0x8 != 0 } +func (h header) isMPEG25() bool { return h[1]&0x10 == 0 } +func (h header) rawLayer() byte { return h[1] >> 1 & 3 } +func (h header) rawBitrate() byte { return h[2] >> 4 } +func (h header) rawSampleRate() byte { return h[2] >> 2 & 3 } +func (h header) rawEmphasis() byte { return h[3] & 0b11 } +func (h header) isFrame576() bool { return h[1]&14 == 2 } +func (h header) padding() int { + if h[2]&0x2 != 0 { + return 1 + } + return 0 +} + +// valid reports whether the four bytes form a syntactically valid MP3 header. +func (h header) valid() bool { + return h[0] == 0xff && + ((h[1]&0xF0) == 0xf0 || (h[1]&0xFE) == 0xe2) && + h.rawLayer() == 1 && // Layer III + h.rawBitrate() != 15 && // Not allowed by spec. + h.rawSampleRate() != 3 && + h.rawEmphasis() != 2 && + // The code for extracting frame size for free-format is tedious and + // free-format MP3s are extinct. + !h.isFreeFormat() +} + +// compatibleWith reports whether two headers describe frames belonging to the +// same MP3 stream — same MPEG version, layer, sample-rate index. +func (h header) compatibleWith(o header) bool { + return o.valid() && + (h[1]^o[1])&0xFE == 0 && + (h[2]^o[2])&0x0C == 0 +} + +// bitrateKbps returns the bitrate of the frame in kilobits per second. +func (h header) bitrateKbps() int { + // halfrate[mpeg1?][bitrate_idx] holds bitrate/2 in kbps. + halfrate := [2][15]uint8{ + {0, 4, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 72, 80}, + {0, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160}, + } + mpeg1 := 0 + if h.isMPEG1() { + mpeg1 = 1 + } + return 2 * int(halfrate[mpeg1][h.rawBitrate()]) +} + +// sampleRateHz returns the sampling rate of the frame in Hz. +func (h header) sampleRateHz() int { + base := [3]int{44100, 48000, 32000}[h.rawSampleRate()] + if !h.isMPEG1() { + base >>= 1 + } + if h.isMPEG25() { + base >>= 1 + } + return base +} + +// frameSamples returns the number of audio samples per channel encoded in +// the frame. +func (h header) frameSamples() int { + if h.isFrame576() { + return 576 + } + return 1152 +} + +// frameBytes returns the size of the frame body (header + side info + audio +// data, excluding padding) in bytes. +func (h header) frameBytes() int { + br := h.bitrateKbps() + sr := h.sampleRateHz() + if br == 0 || sr == 0 { + return 0 + } + return h.frameSamples() * br * 125 / sr +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go b/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go new file mode 100644 index 0000000..0503719 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/internal/scan/bytes.go @@ -0,0 +1,271 @@ +// Package scan has functions for scanning byte slices. +package scan + +import ( + "bytes" + "encoding/binary" +) + +// Bytes is a byte slice with helper methods for easier scanning. +type Bytes []byte + +func (b *Bytes) Advance(n int) bool { + if n < 0 || len(*b) < n { + return false + } + *b = (*b)[n:] + return true +} + +// TrimLWS trims whitespace from beginning of the bytes. +func (b *Bytes) TrimLWS() { + firstNonWS := 0 + for ; firstNonWS < len(*b) && ByteIsWS((*b)[firstNonWS]); firstNonWS++ { + } + + *b = (*b)[firstNonWS:] +} + +// TrimRWS trims whitespace from the end of the bytes. +func (b *Bytes) TrimRWS() { + lb := len(*b) + for lb > 0 && ByteIsWS((*b)[lb-1]) { + *b = (*b)[:lb-1] + lb-- + } +} + +// FirstNonWS returns the first non-whitespace character from b, +// or 0x00 if no such character is found. +func (b Bytes) FirstNonWS() byte { + for i := range b { + if ByteIsWS(b[i]) { + continue + } + return b[i] + } + + return 0x00 +} + +// Peek one byte from b or 0x00 if b is empty. +func (b *Bytes) Peek() byte { + if len(*b) > 0 { + return (*b)[0] + } + return 0 +} + +// Pop one byte from b or 0x00 if b is empty. +func (b *Bytes) Pop() byte { + if len(*b) > 0 { + ret := (*b)[0] + *b = (*b)[1:] + return ret + } + return 0 +} + +// PopN pops n bytes from b or nil if b is empty. +func (b *Bytes) PopN(n int) []byte { + if len(*b) >= n { + ret := (*b)[:n] + *b = (*b)[n:] + return ret + } + return nil +} + +// PopUntil will advance b until, but not including, the first occurrence of stopAt +// character. If no occurrence is found, then it will advance until the end of b. +// The returned Bytes is a slice of all the bytes that we're advanced over. +func (b *Bytes) PopUntil(stopAt ...byte) Bytes { + if len(*b) == 0 { + return Bytes{} + } + i := bytes.IndexAny(*b, string(stopAt)) + if i == -1 { + i = len(*b) + } + + prefix := (*b)[:i] + *b = (*b)[i:] + return prefix +} + +// ReadSlice is the same as PopUntil, but the returned value includes stopAt as well. +func (b *Bytes) ReadSlice(stopAt byte) Bytes { + if len(*b) == 0 { + return Bytes{} + } + i := bytes.IndexByte(*b, stopAt) + if i == -1 { + i = len(*b) + } else { + i++ + } + + prefix := (*b)[:i] + *b = (*b)[i:] + return prefix +} + +// Line returns the first line from b and advances b with the length of the +// line. One new line character is trimmed after the line if it exists. +func (b *Bytes) Line() Bytes { + line := b.PopUntil('\n') + lline := len(line) + if lline > 0 && line[lline-1] == '\r' { + line = line[:lline-1] + } + b.Advance(1) + return line +} + +func (b *Bytes) Uint16() (uint16, bool) { + if len(*b) < 2 { + return 0, false + } + v := binary.LittleEndian.Uint16(*b) + *b = (*b)[2:] + return v, true +} + +func (b *Bytes) Uint32() (uint32, bool) { + if len(*b) < 4 { + return 0, false + } + v := binary.LittleEndian.Uint32(*b) + *b = (*b)[4:] + return v, true +} + +func (b *Bytes) Uint32be() (uint32, bool) { + if len(*b) < 4 { + return 0, false + } + v := binary.BigEndian.Uint32(*b) + *b = (*b)[4:] + return v, true +} + +type Flags int + +const ( + // CompactWS will make one whitespace from pattern to match one or more spaces from input. + CompactWS Flags = 1 << iota + // IgnoreCase will match lower case from pattern with lower case from input. + // IgnoreCase will match upper case from pattern with both lower and upper case from input. + // This flag is not really well named, + IgnoreCase + // FullWord ensures the input ends with a full word (it's followed by spaces.) + FullWord +) + +// Search for occurrences of pattern p inside b at any index. +// It returns the index where p was found in b and how many bytes were needed +// for matching the pattern. +func (b Bytes) Search(p []byte, flags Flags) (i int, l int) { + lb, lp := len(b), len(p) + if lp == 0 { + return 0, 0 + } + if lb == 0 { + return -1, 0 + } + if flags == 0 { + if i = bytes.Index(b, p); i == -1 { + return -1, 0 + } else { + return i, lp + } + } + + for i := range b { + if lb-i < lp { + return -1, 0 + } + if l = b[i:].Match(p, flags); l != -1 { + return i, l + } + } + + return -1, 0 +} + +// Match returns how many bytes were needed to match pattern p. +// It returns -1 if p does not match b. +func (b Bytes) Match(p []byte, flags Flags) int { + l := len(b) + if len(p) == 0 { + return 0 + } + if l == 0 { + return -1 + } + // Some cases we can handle with a simple bytes.HasPrefix. + if flags == 0 || flags == FullWord { + if bytes.HasPrefix(b, p) { + b = b[len(p):] + p = p[len(p):] + goto out + } + return -1 + } + for len(b) > 0 { + // If we finished all we were looking for from p. + if len(p) == 0 { + goto out + } + if flags&IgnoreCase > 0 && isUpper(p[0]) { + if upper(b[0]) != p[0] { + return -1 + } + b, p = b[1:], p[1:] + } else if flags&CompactWS > 0 && ByteIsWS(p[0]) { + p = p[1:] + if !ByteIsWS(b[0]) { + return -1 + } + b = b[1:] + if len(p) > 0 && !ByteIsWS(p[0]) { + b.TrimLWS() + } + } else { + if b[0] != p[0] { + return -1 + } + b, p = b[1:], p[1:] + } + } +out: + // If p still has leftover characters, it means it didn't fully match b. + if len(p) > 0 { + return -1 + } + if flags&FullWord > 0 { + if len(b) > 0 && !ByteIsWS(b[0]) { + return -1 + } + } + return l - len(b) +} + +func isUpper(c byte) bool { + return c >= 'A' && c <= 'Z' +} +func upper(c byte) byte { + if c >= 'a' && c <= 'z' { + return c - ('a' - 'A') + } + return c +} + +func ByteIsWS(b byte) bool { + return b == '\t' || b == '\n' || b == '\x0c' || b == '\r' || b == ' ' +} + +var ( + ASCIISpaces = []byte{' ', '\r', '\n', '\x0c', '\t'} + ASCIIDigits = []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'} +) diff --git a/vendor/github.com/gabriel-vasile/mimetype/mime.go b/vendor/github.com/gabriel-vasile/mimetype/mime.go new file mode 100644 index 0000000..5382fb1 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/mime.go @@ -0,0 +1,221 @@ +package mimetype + +import ( + stdmime "mime" + "slices" + "strings" + + "github.com/gabriel-vasile/mimetype/internal/charset" + "github.com/gabriel-vasile/mimetype/internal/magic" +) + +// MIME struct holds information about a file format: the string representation +// of the MIME type, the extension and the parent file format. +type MIME struct { + mime string + aliases []string + extension string + // detector receives the raw input and a limit for the number of bytes it is + // allowed to check. It returns whether the input matches a signature or not. + detector magic.Detector + children []*MIME + parent *MIME +} + +// String returns the string representation of the MIME type, e.g., "application/zip". +// String return values can change between releases, for example, when [IANA] +// assigns a new media type. Use [MIME.Is] to avoid breaking changes. +// +// mtype := mimetype.Detect(zipFile) +// if mtype.String() == "application/zip" { /* Plain string comparison is brittle. */ } +// if mtype.Is("application/zip") { /* Will continue to work between releases */ } +// +// [IANA]: https://www.iana.org/assignments/media-types/media-types.xhtml +func (m *MIME) String() string { + return m.mime +} + +// Extension returns the file extension associated with the MIME type. +// It includes the leading dot, as in ".html". When the file format does not +// have an extension, the empty string is returned. +func (m *MIME) Extension() string { + return m.extension +} + +// Parent returns the parent MIME type from the hierarchy. +// Each MIME type has a non-nil parent, except for the root MIME type. +// +// For example, the application/json and text/html MIME types have text/plain as +// their parent because they are text files that happen to contain JSON or HTML. +// Another example is the ZIP format, which is used as container +// for Microsoft Office files, EPUB files, JAR files, and others. +func (m *MIME) Parent() *MIME { + return m.parent +} + +// Is checks whether this MIME type, or any of its [aliases], is equal to the +// expected MIME type. MIME type equality test is done on the "type/subtype" +// section, ignores any optional MIME parameters, ignores any leading and +// trailing whitespace, and is case insensitive. +// +// [aliases]: https://github.com/gabriel-vasile/mimetype/blob/master/supported_mimes.md +func (m *MIME) Is(expectedMIME string) bool { + // Parsing is needed because some detected MIME types contain parameters + // that need to be stripped for the comparison. + expectedMIME, _, _ = stdmime.ParseMediaType(expectedMIME) + found, _, _ := stdmime.ParseMediaType(m.mime) + + if expectedMIME == found { + return true + } + + if slices.Contains(m.aliases, expectedMIME) { + return true + } + + return false +} + +func newMIME( + mime, extension string, + detector magic.Detector, + children ...*MIME) *MIME { + m := &MIME{ + mime: mime, + extension: extension, + detector: detector, + children: children, + } + + for _, c := range children { + c.parent = m + } + + return m +} + +func (m *MIME) alias(aliases ...string) *MIME { + m.aliases = aliases + return m +} + +// match does a depth-first search on the signature tree. It returns the deepest +// successful node for which all the children detection functions fail. +func (m *MIME) match(in []byte, readLimit uint32) *MIME { + for _, c := range m.children { + if c.detector(in, readLimit) { + return c.match(in, readLimit) + } + } + + needsCharset := map[string]func([]byte) string{ + "text/plain": charset.FromPlain, + "text/html": charset.FromHTML, + "text/xml": charset.FromXML, + } + charset := "" + if f, ok := needsCharset[m.mime]; ok { + // The charset comes from BOM, from HTML headers, from XML headers. + // Limit the number of bytes searched for to 1024. + charset = f(in[:min(len(in), 1024)]) + } + if m == root || charset == "" { + return m + } + + return m.cloneHierarchy(charset) +} + +// flatten transforms an hierarchy of MIMEs into a slice of MIMEs. +func (m *MIME) flatten() []*MIME { + out := []*MIME{m} //nolint:prealloc + for _, c := range m.children { + out = append(out, c.flatten()...) + } + + return out +} + +// hierarchy returns an easy to read list of ancestors for m. +// For example, application/json would return json>txt>root. +func (m *MIME) hierarchy() string { + var h strings.Builder + for m := m; m != nil; m = m.Parent() { + e := strings.TrimPrefix(m.Extension(), ".") + if e == "" { + // There are some MIME without extensions. When generating the hierarchy, + // it would be confusing to use empty string as extension. + // Use the subtype instead; ex: application/x-executable -> x-executable. + e = strings.Split(m.String(), "/")[1] + if m.Is("application/octet-stream") { + // for octet-stream use root, because it's short and used in many places + e = "root" + } + } + h.WriteString(">" + e) + } + return strings.TrimPrefix(h.String(), ">") +} + +// clone creates a new MIME with the provided optional MIME parameters. +func (m *MIME) clone(charset string) *MIME { + clonedMIME := m.mime + if charset != "" { + clonedMIME = m.mime + "; charset=" + charset + } + + return &MIME{ + mime: clonedMIME, + aliases: m.aliases, + extension: m.extension, + } +} + +// cloneHierarchy creates a clone of m and all its ancestors. The optional MIME +// parameters are set on the last child of the hierarchy. +func (m *MIME) cloneHierarchy(charset string) *MIME { + ret := m.clone(charset) + lastChild := ret + for p := m.Parent(); p != nil; p = p.Parent() { + pClone := p.clone("") + lastChild.parent = pClone + lastChild = pClone + } + + return ret +} + +func (m *MIME) lookup(mime string) *MIME { + if mime == m.mime { + return m + } + if slices.Contains(m.aliases, mime) { + return m + } + + for _, c := range m.children { + if m := c.lookup(mime); m != nil { + return m + } + } + return nil +} + +// Extend adds detection for a sub-format. The detector is a function +// returning true when the raw input file satisfies a signature. +// The sub-format will be detected if all the detectors in the parent chain return true. +// The extension should include the leading dot, as in ".html". +func (m *MIME) Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) { + mime, _, _ = stdmime.ParseMediaType(mime) + c := &MIME{ + mime: mime, + extension: extension, + detector: detector, + parent: m, + aliases: aliases, + } + + mu.Lock() + m.children = append([]*MIME{c}, m.children...) + mu.Unlock() +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/mimetype.go b/vendor/github.com/gabriel-vasile/mimetype/mimetype.go new file mode 100644 index 0000000..e6f1e77 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/mimetype.go @@ -0,0 +1,129 @@ +// Package mimetype uses magic number signatures to detect the MIME type of a file. +// +// File formats are stored in a hierarchy with "application/octet-stream" at its root. +// For example, the hierarchy for HTML format is application/octet-stream -> +// text/plain -> text/html. +package mimetype + +import ( + "io" + "mime" + "os" + "sync/atomic" +) + +const defaultLimit uint32 = 4096 + +// readLimit is the maximum number of bytes from the input used when detecting. +var readLimit uint32 = defaultLimit + +// Detect returns the MIME type found from the provided byte slice. +// +// The result is always a valid MIME type, with "application/octet-stream" +// returned when identification failed. +func Detect(in []byte) *MIME { + // Using atomic because readLimit can be written at the same time in other goroutine. + l := atomic.LoadUint32(&readLimit) + if l > 0 && len(in) > int(l) { + in = in[:l] + } + mu.RLock() + defer mu.RUnlock() + return root.match(in, l) +} + +// DetectReader returns the MIME type of the provided reader. +// +// The result is always a valid MIME type, with "application/octet-stream" +// returned when identification failed with or without an error. +// Any error returned is related to the reading from the input reader. +// +// DetectReader assumes the reader offset is at the start. If the input is an +// io.ReadSeeker you previously read from, it should be rewinded before detection: +// +// reader.Seek(0, io.SeekStart) +func DetectReader(r io.Reader) (*MIME, error) { + var in []byte + var err error + + // Using atomic because readLimit can be written at the same time in other goroutine. + l := atomic.LoadUint32(&readLimit) + if l == 0 { + in, err = io.ReadAll(r) + if err != nil { + return errMIME, err + } + } else { + var n int + in = make([]byte, l) + // io.UnexpectedEOF means len(r) < len(in). It is not an error in this case, + // it just means the input file is smaller than the allocated bytes slice. + n, err = io.ReadFull(r, in) + if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { + return errMIME, err + } + in = in[:n] + } + + mu.RLock() + defer mu.RUnlock() + return root.match(in, l), nil +} + +// DetectFile returns the MIME type of the provided file. +// +// The result is always a valid MIME type, with "application/octet-stream" +// returned when identification failed with or without an error. +// Any error returned is related to the opening and reading from the input file. +func DetectFile(path string) (*MIME, error) { + f, err := os.Open(path) + if err != nil { + return errMIME, err + } + defer f.Close() + + return DetectReader(f) +} + +// EqualsAny reports whether s MIME type is equal to any MIME type in mimes. +// MIME type equality test is done on the "type/subtype" section, ignores +// any optional MIME parameters, ignores any leading and trailing whitespace, +// and is case insensitive. +func EqualsAny(s string, mimes ...string) bool { + s, _, _ = mime.ParseMediaType(s) + for _, m := range mimes { + m, _, _ = mime.ParseMediaType(m) + if s == m { + return true + } + } + + return false +} + +// SetLimit sets the maximum number of bytes read from input when detecting the MIME type. +// Increasing the limit provides better detection for file formats which store +// their magical numbers towards the end of the file: docx, pptx, xlsx, etc. +// During detection data is read in a single block of size limit, i.e. it is not buffered. +// A limit of 0 means the whole input file will be used. +func SetLimit(limit uint32) { + // Using atomic because readLimit can be read at the same time in other goroutine. + atomic.StoreUint32(&readLimit, limit) +} + +// Extend adds detection for other file formats. +// It is equivalent to calling [MIME.Extend] on the root MIME type "application/octet-stream". +func Extend(detector func(raw []byte, limit uint32) bool, mime, extension string, aliases ...string) { + root.Extend(detector, mime, extension, aliases...) +} + +// Lookup finds a MIME object by its string representation. +// The representation can be the main MIME type, or any of its aliases. +func Lookup(m string) *MIME { + // We store the MIME types without optional params, so + // perform parsing to extract the target MIME type without optional params. + m, _, _ = mime.ParseMediaType(m) + mu.RLock() + defer mu.RUnlock() + return root.lookup(m) +} diff --git a/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md new file mode 100644 index 0000000..f014ff4 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/supported_mimes.md @@ -0,0 +1,209 @@ +## 204 Supported MIME types +This file is automatically generated when running tests. Do not edit manually. + +Extension | MIME type
Aliases | Hierarchy +--------- | ---------------------- | --------- +**n/a** | **application/octet-stream** | root +**.xpm** | **image/x-xpixmap** | xpm>root +**.7z** | **application/x-7z-compressed** | 7z>root +**.zip** | **application/zip**
application/x-zip, application/x-zip-compressed | zip>root +**.docx** | **application/vnd.openxmlformats-officedocument.wordprocessingml.document** | docx>zip>root +**.pptx** | **application/vnd.openxmlformats-officedocument.presentationml.presentation** | pptx>zip>root +**.xlsx** | **application/vnd.openxmlformats-officedocument.spreadsheetml.sheet** | xlsx>zip>root +**.epub** | **application/epub+zip** | epub>zip>root +**.apk** | **application/vnd.android.package-archive** | apk>zip>root +**.jar** | **application/java-archive**
application/jar, application/jar-archive, application/x-java-archive | jar>zip>root +**.odt** | **application/vnd.oasis.opendocument.text**
application/x-vnd.oasis.opendocument.text | odt>zip>root +**.ott** | **application/vnd.oasis.opendocument.text-template**
application/x-vnd.oasis.opendocument.text-template | ott>odt>zip>root +**.ods** | **application/vnd.oasis.opendocument.spreadsheet**
application/x-vnd.oasis.opendocument.spreadsheet | ods>zip>root +**.ots** | **application/vnd.oasis.opendocument.spreadsheet-template**
application/x-vnd.oasis.opendocument.spreadsheet-template | ots>ods>zip>root +**.odp** | **application/vnd.oasis.opendocument.presentation**
application/x-vnd.oasis.opendocument.presentation | odp>zip>root +**.otp** | **application/vnd.oasis.opendocument.presentation-template**
application/x-vnd.oasis.opendocument.presentation-template | otp>odp>zip>root +**.odg** | **application/vnd.oasis.opendocument.graphics**
application/x-vnd.oasis.opendocument.graphics | odg>zip>root +**.otg** | **application/vnd.oasis.opendocument.graphics-template**
application/x-vnd.oasis.opendocument.graphics-template | otg>odg>zip>root +**.odf** | **application/vnd.oasis.opendocument.formula**
application/x-vnd.oasis.opendocument.formula | odf>zip>root +**.odc** | **application/vnd.oasis.opendocument.chart**
application/x-vnd.oasis.opendocument.chart | odc>zip>root +**.sxc** | **application/vnd.sun.xml.calc** | sxc>zip>root +**.kmz** | **application/vnd.google-earth.kmz** | kmz>zip>root +**.vsdx** | **application/vnd.ms-visio.drawing.main+xml** | vsdx>zip>root +**.pdf** | **application/pdf**
application/x-pdf | pdf>root +**.fdf** | **application/vnd.fdf** | fdf>root +**n/a** | **application/x-ole-storage** | x-ole-storage>root +**.msi** | **application/x-ms-installer**
application/x-windows-installer, application/x-msi | msi>x-ole-storage>root +**.msg** | **application/vnd.ms-outlook** | msg>x-ole-storage>root +**.xls** | **application/vnd.ms-excel**
application/msexcel | xls>x-ole-storage>root +**.pub** | **application/vnd.ms-publisher** | pub>x-ole-storage>root +**.ppt** | **application/vnd.ms-powerpoint**
application/mspowerpoint | ppt>x-ole-storage>root +**.doc** | **application/msword**
application/vnd.ms-word | doc>x-ole-storage>root +**.ps** | **application/postscript** | ps>root +**.psd** | **image/vnd.adobe.photoshop**
image/x-psd, application/photoshop | psd>root +**.p7s** | **application/pkcs7-signature** | p7s>root +**.ogg** | **application/ogg**
application/x-ogg | ogg>root +**.oga** | **audio/ogg** | oga>ogg>root +**.ogv** | **video/ogg** | ogv>ogg>root +**.png** | **image/png** | png>root +**.apng** | **image/apng**
image/vnd.mozilla.apng | apng>png>root +**.jpg** | **image/jpeg** | jpg>root +**.jxl** | **image/jxl** | jxl>root +**.jp2** | **image/jp2** | jp2>root +**.jpf** | **image/jpx** | jpf>root +**.jpm** | **image/jpm**
video/jpm | jpm>root +**.jxs** | **image/jxs** | jxs>root +**.gif** | **image/gif** | gif>root +**.webp** | **image/webp** | webp>root +**.exe** | **application/vnd.microsoft.portable-executable** | exe>root +**n/a** | **application/x-elf** | x-elf>root +**n/a** | **application/x-object** | x-object>x-elf>root +**n/a** | **application/x-executable** | x-executable>x-elf>root +**.so** | **application/x-sharedlib** | so>x-elf>root +**n/a** | **application/x-coredump** | x-coredump>x-elf>root +**.a** | **application/x-archive**
application/x-unix-archive | a>root +**.deb** | **application/vnd.debian.binary-package** | deb>a>root +**.tar** | **application/x-tar** | tar>root +**.xar** | **application/x-xar** | xar>root +**.bz2** | **application/x-bzip2** | bz2>root +**.fits** | **application/fits**
image/fits | fits>root +**.tiff** | **image/tiff** | tiff>root +**.bmp** | **image/bmp**
image/x-bmp, image/x-ms-bmp | bmp>root +**.123** | **application/vnd.lotus-1-2-3** | 123>root +**.ico** | **image/x-icon** | ico>root +**.flac** | **audio/flac** | flac>root +**.midi** | **audio/midi**
audio/mid, audio/sp-midi, audio/x-mid, audio/x-midi | midi>root +**.ape** | **audio/ape** | ape>root +**.mpc** | **audio/musepack** | mpc>root +**.amr** | **audio/amr**
audio/amr-nb | amr>root +**.wav** | **audio/wav**
audio/x-wav, audio/vnd.wave, audio/wave | wav>root +**.aiff** | **audio/aiff**
audio/x-aiff | aiff>root +**.au** | **audio/basic** | au>root +**.mpeg** | **video/mpeg** | mpeg>root +**.mov** | **video/quicktime** | mov>root +**.mp4** | **video/mp4** | mp4>root +**.avif** | **image/avif** | avif>mp4>root +**.3gp** | **video/3gpp**
video/3gp, audio/3gpp | 3gp>mp4>root +**.3g2** | **video/3gpp2**
video/3g2, audio/3gpp2 | 3g2>mp4>root +**.mp4** | **audio/mp4**
audio/x-mp4a | mp4>mp4>root +**.mqv** | **video/quicktime** | mqv>mp4>root +**.m4a** | **audio/x-m4a** | m4a>mp4>root +**.m4v** | **video/x-m4v** | m4v>mp4>root +**.heic** | **image/heic** | heic>mp4>root +**.heic** | **image/heic-sequence** | heic>mp4>root +**.heif** | **image/heif** | heif>mp4>root +**.heif** | **image/heif-sequence** | heif>mp4>root +**.mj2** | **video/mj2** | mj2>mp4>root +**.dvb** | **video/vnd.dvb.file** | dvb>mp4>root +**.webm** | **video/webm**
audio/webm | webm>root +**.avi** | **video/x-msvideo**
video/avi, video/msvideo | avi>root +**.flv** | **video/x-flv** | flv>root +**.mkv** | **video/matroska**
video/x-matroska | mkv>root +**.asf** | **video/x-ms-asf**
video/asf, video/x-ms-wmv | asf>root +**.aac** | **audio/aac** | aac>root +**.voc** | **audio/x-unknown** | voc>root +**.m3u** | **application/vnd.apple.mpegurl**
audio/mpegurl, application/x-mpegurl | m3u>root +**.rmvb** | **application/vnd.rn-realmedia-vbr** | rmvb>root +**.gz** | **application/gzip**
application/x-gzip, application/x-gunzip, application/gzipped, application/gzip-compressed, application/x-gzip-compressed, gzip/document | gz>root +**.class** | **application/x-java-applet** | class>root +**.swf** | **application/x-shockwave-flash** | swf>root +**.crx** | **application/x-chrome-extension** | crx>root +**.ttf** | **font/ttf**
font/sfnt, application/x-font-ttf, application/font-sfnt | ttf>root +**.woff** | **font/woff** | woff>root +**.woff2** | **font/woff2** | woff2>root +**.otf** | **font/otf** | otf>root +**.ttc** | **font/collection** | ttc>root +**.eot** | **application/vnd.ms-fontobject** | eot>root +**.wasm** | **application/wasm** | wasm>root +**.shx** | **application/vnd.shx** | shx>root +**.shp** | **application/vnd.shp** | shp>shx>root +**.dbf** | **application/x-dbf** | dbf>root +**.dcm** | **application/dicom** | dcm>root +**.rar** | **application/vnd.rar**
application/x-rar-compressed, application/x-rar | rar>root +**.djvu** | **image/vnd.djvu** | djvu>root +**.mobi** | **application/x-mobipocket-ebook** | mobi>root +**.lit** | **application/x-ms-reader** | lit>root +**.bpg** | **image/bpg** | bpg>root +**.cbor** | **application/cbor** | cbor>root +**.sqlite** | **application/vnd.sqlite3**
application/x-sqlite3 | sqlite>root +**.dwg** | **image/vnd.dwg**
image/x-dwg, application/acad, application/x-acad, application/autocad_dwg, application/dwg, application/x-dwg, application/x-autocad, drawing/dwg | dwg>root +**.nes** | **application/vnd.nintendo.snes.rom** | nes>root +**.lnk** | **application/x-ms-shortcut** | lnk>root +**.macho** | **application/x-mach-binary** | macho>root +**.qcp** | **audio/qcelp** | qcp>root +**.icns** | **image/x-icns** | icns>root +**.hdr** | **image/vnd.radiance** | hdr>root +**.mrc** | **application/marc** | mrc>root +**.mdb** | **application/x-msaccess** | mdb>root +**.accdb** | **application/x-msaccess** | accdb>root +**.zst** | **application/zstd** | zst>root +**.cab** | **application/vnd.ms-cab-compressed** | cab>root +**.rpm** | **application/x-rpm** | rpm>root +**.xz** | **application/x-xz** | xz>root +**.lz** | **application/lzip**
application/x-lzip | lz>root +**.torrent** | **application/x-bittorrent** | torrent>root +**.cpio** | **application/x-cpio** | cpio>root +**n/a** | **application/tzif** | tzif>root +**.xcf** | **image/x-xcf** | xcf>root +**.pat** | **image/x-gimp-pat** | pat>root +**.gbr** | **image/x-gimp-gbr** | gbr>root +**.glb** | **model/gltf-binary** | glb>root +**.cab** | **application/x-installshield** | cab>root +**.jxr** | **image/jxr**
image/vnd.ms-photo | jxr>root +**.parquet** | **application/vnd.apache.parquet**
application/x-parquet | parquet>root +**.one** | **application/onenote** | one>root +**.chm** | **application/vnd.ms-htmlhelp** | chm>root +**.wpd** | **application/vnd.wordperfect** | wpd>root +**.dxf** | **image/vnd.dxf** | dxf>root +**.grb** | **application/grib** | grb>root +**n/a** | **application/zlib** | zlib>root +**.inf** | **application/x-os2-inf** | inf>root +**.hlp** | **application/x-os2-hlp** | hlp>root +**.fm** | **application/vnd.framemaker** | fm>root +**.bufr** | **application/bufr** | bufr>root +**.pyc** | **application/x-bytecode.python** | pyc>root +**.pcap** | **application/vnd.tcpdump.pcap** | pcap>root +**.mp3** | **audio/mpeg**
audio/x-mpeg, audio/mp3 | mp3>root +**.txt** | **text/plain** | txt>root +**.svg** | **image/svg+xml** | svg>txt>root +**.html** | **text/html** | html>txt>root +**.xml** | **text/xml**
application/xml | xml>txt>root +**.rss** | **application/rss+xml**
text/rss | rss>xml>txt>root +**.atom** | **application/atom+xml** | atom>xml>txt>root +**.x3d** | **model/x3d+xml** | x3d>xml>txt>root +**.kml** | **application/vnd.google-earth.kml+xml** | kml>xml>txt>root +**.xlf** | **application/x-xliff+xml** | xlf>xml>txt>root +**.dae** | **model/vnd.collada+xml** | dae>xml>txt>root +**.gml** | **application/gml+xml** | gml>xml>txt>root +**.gpx** | **application/gpx+xml** | gpx>xml>txt>root +**.tcx** | **application/vnd.garmin.tcx+xml** | tcx>xml>txt>root +**.amf** | **application/x-amf** | amf>xml>txt>root +**.3mf** | **application/vnd.ms-package.3dmanufacturing-3dmodel+xml** | 3mf>xml>txt>root +**.xfdf** | **application/vnd.adobe.xfdf** | xfdf>xml>txt>root +**.owl** | **application/owl+xml** | owl>xml>txt>root +**.html** | **application/xhtml+xml** | html>xml>txt>root +**.xml** | **application/vnd.cyclonedx+xml** | xml>xml>txt>root +**.php** | **text/x-php** | php>txt>root +**.js** | **text/javascript**
application/x-javascript, application/javascript | js>txt>root +**.lua** | **text/x-lua** | lua>txt>root +**.pl** | **text/x-perl** | pl>txt>root +**.py** | **text/x-python**
text/x-script.python, application/x-python | py>txt>root +**.rb** | **text/x-ruby**
application/x-ruby | rb>txt>root +**.json** | **application/json** | json>txt>root +**.geojson** | **application/geo+json** | geojson>json>txt>root +**.har** | **application/json** | har>json>txt>root +**.gltf** | **model/gltf+json** | gltf>json>txt>root +**.json** | **application/vnd.cyclonedx+json** | json>json>txt>root +**.ndjson** | **application/x-ndjson** | ndjson>txt>root +**.rtf** | **text/rtf**
application/rtf | rtf>txt>root +**.srt** | **application/x-subrip**
application/x-srt, text/x-srt | srt>txt>root +**.tcl** | **text/x-tcl**
application/x-tcl | tcl>txt>root +**.csv** | **text/csv** | csv>txt>root +**.tsv** | **text/tab-separated-values** | tsv>txt>root +**.vcf** | **text/vcard** | vcf>txt>root +**.ics** | **text/calendar** | ics>txt>root +**.warc** | **application/warc** | warc>txt>root +**.vtt** | **text/vtt** | vtt>txt>root +**.sh** | **text/x-shellscript**
text/x-sh, application/x-shellscript, application/x-sh | sh>txt>root +**.pbm** | **image/x-portable-bitmap** | pbm>txt>root +**.pgm** | **image/x-portable-graymap** | pgm>txt>root +**.ppm** | **image/x-portable-pixmap** | ppm>txt>root +**.pam** | **image/x-portable-arbitrarymap** | pam>txt>root +**.eml** | **message/rfc822** | eml>txt>root +**.ged** | **text/vnd.familysearch.gedcom** | ged>txt>root diff --git a/vendor/github.com/gabriel-vasile/mimetype/tree.go b/vendor/github.com/gabriel-vasile/mimetype/tree.go new file mode 100644 index 0000000..bec8b43 --- /dev/null +++ b/vendor/github.com/gabriel-vasile/mimetype/tree.go @@ -0,0 +1,308 @@ +package mimetype + +import ( + "sync" + + "github.com/gabriel-vasile/mimetype/internal/magic" +) + +// mimetype stores the list of MIME types in a tree structure with +// "application/octet-stream" at the root of the hierarchy. The hierarchy +// approach minimizes the number of checks that need to be done on the input +// and allows for more precise results once the base type of file has been +// identified. +// +// root is a detector which passes for any slice of bytes. +// When a detector passes the check, the children detectors +// are tried in order to find a more accurate MIME type. +var root = newMIME("application/octet-stream", "", + func([]byte, uint32) bool { return true }, + xpm, sevenZ, zip, pdf, fdf, ole, ps, psd, p7s, ogg, png, jpg, jxl, jp2, jpx, + jpm, jxs, gif, webp, exe, elf, ar, tar, xar, bz2, fits, tiff, bmp, lotus, ico, + flac, midi, ape, musePack, amr, wav, aiff, au, mpeg, quickTime, mp4, webM, + avi, flv, mkv, asf, aac, voc, m3u, rmvb, gzip, class, swf, crx, ttf, woff, + woff2, otf, ttc, eot, wasm, shx, dbf, dcm, rar, djvu, mobi, lit, bpg, cbor, + sqlite3, dwg, nes, lnk, macho, qcp, icns, hdr, mrc, mdb, accdb, zstd, cab, + rpm, xz, lzip, torrent, cpio, tzif, xcf, pat, gbr, glb, cabIS, jxr, parquet, + oneNote, chm, wpd, dxf, grib, zlib, inf, hlp, fm, bufr, pyc, pcap, + // MP3 is late because it does a linear search in the input. That means + // containers that embed an MP3, for example: an mp4 file, or a zip without + // compression, would pass as MP3s. + mp3, + // Keep text last because it is the slowest check. + text, +) + +// errMIME is returned from Detect functions when err is not nil. +// Detect could return root for erroneous cases, but it needs to lock mu in order to do so. +// errMIME is same as root but it does not require locking. +var errMIME = newMIME("application/octet-stream", "", func([]byte, uint32) bool { return false }) + +// mu guards access to the root MIME tree. Access to root must be synchronized with this lock. +var mu = &sync.RWMutex{} + +// The list of nodes appended to the root node. +var ( + xz = newMIME("application/x-xz", ".xz", magic.Xz) + gzip = newMIME("application/gzip", ".gz", magic.Gzip).alias( + "application/x-gzip", "application/x-gunzip", "application/gzipped", + "application/gzip-compressed", "application/x-gzip-compressed", + "gzip/document") + sevenZ = newMIME("application/x-7z-compressed", ".7z", magic.SevenZ) + // APK must be checked before JAR because APK is a subset of JAR. + // This means APK should be a child of JAR detector, but in practice, + // the decisive signature for JAR might be located at the end of the file + // and not reachable because of library readLimit. + zip = newMIME("application/zip", ".zip", magic.Zip, docx, pptx, xlsx, epub, apk, jar, odt, ods, odp, odg, odf, odc, sxc, kmz, visio). + alias("application/x-zip", "application/x-zip-compressed") + tar = newMIME("application/x-tar", ".tar", magic.Tar) + xar = newMIME("application/x-xar", ".xar", magic.Xar) + bz2 = newMIME("application/x-bzip2", ".bz2", magic.Bz2) + pdf = newMIME("application/pdf", ".pdf", magic.PDF). + alias("application/x-pdf") + fdf = newMIME("application/vnd.fdf", ".fdf", magic.Fdf) + xlsx = newMIME("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx", magic.Xlsx) + docx = newMIME("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx", magic.Docx) + pptx = newMIME("application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx", magic.Pptx) + visio = newMIME("application/vnd.ms-visio.drawing.main+xml", ".vsdx", magic.Visio) + epub = newMIME("application/epub+zip", ".epub", magic.Epub) + jar = newMIME("application/java-archive", ".jar", magic.Jar). + alias("application/jar", "application/jar-archive", "application/x-java-archive") + apk = newMIME("application/vnd.android.package-archive", ".apk", magic.APK) + ole = newMIME("application/x-ole-storage", "", magic.Ole, msi, msg, xls, pub, ppt, doc) + msi = newMIME("application/x-ms-installer", ".msi", magic.Msi). + alias("application/x-windows-installer", "application/x-msi") + doc = newMIME("application/msword", ".doc", magic.Doc). + alias("application/vnd.ms-word") + ppt = newMIME("application/vnd.ms-powerpoint", ".ppt", magic.Ppt). + alias("application/mspowerpoint") + pub = newMIME("application/vnd.ms-publisher", ".pub", magic.Pub) + xls = newMIME("application/vnd.ms-excel", ".xls", magic.Xls). + alias("application/msexcel") + msg = newMIME("application/vnd.ms-outlook", ".msg", magic.Msg) + ps = newMIME("application/postscript", ".ps", magic.Ps) + fits = newMIME("application/fits", ".fits", magic.Fits).alias("image/fits") + ogg = newMIME("application/ogg", ".ogg", magic.Ogg, oggAudio, oggVideo). + alias("application/x-ogg") + oggAudio = newMIME("audio/ogg", ".oga", magic.OggAudio) + oggVideo = newMIME("video/ogg", ".ogv", magic.OggVideo) + text = newMIME("text/plain", ".txt", magic.Text, svg, html, xml, php, js, lua, perl, python, ruby, json, ndJSON, rtf, srt, tcl, csv, tsv, vCard, iCalendar, warc, vtt, shell, netpbm, netpgm, netppm, netpam, rfc822, gedcom) + xml = newMIME("text/xml", ".xml", magic.XML, rss, atom, x3d, kml, xliff, collada, gml, gpx, tcx, amf, threemf, xfdf, owl2, xhtml, cdxxml). + alias("application/xml") + xhtml = newMIME("application/xhtml+xml", ".html", magic.XHTML) + json = newMIME("application/json", ".json", magic.JSON, geoJSON, har, gltf, cdxJSON) + har = newMIME("application/json", ".har", magic.HAR) + csv = newMIME("text/csv", ".csv", magic.CSV) + tsv = newMIME("text/tab-separated-values", ".tsv", magic.TSV) + geoJSON = newMIME("application/geo+json", ".geojson", magic.GeoJSON) + ndJSON = newMIME("application/x-ndjson", ".ndjson", magic.NdJSON) + cdxJSON = newMIME("application/vnd.cyclonedx+json", ".json", magic.CDXJSON) + html = newMIME("text/html", ".html", magic.HTML) + php = newMIME("text/x-php", ".php", magic.Php) + rtf = newMIME("text/rtf", ".rtf", magic.Rtf).alias("application/rtf") + js = newMIME("text/javascript", ".js", magic.Js). + alias("application/x-javascript", "application/javascript") + srt = newMIME("application/x-subrip", ".srt", magic.Srt). + alias("application/x-srt", "text/x-srt") + vtt = newMIME("text/vtt", ".vtt", magic.Vtt) + lua = newMIME("text/x-lua", ".lua", magic.Lua) + perl = newMIME("text/x-perl", ".pl", magic.Perl) + python = newMIME("text/x-python", ".py", magic.Python). + alias("text/x-script.python", "application/x-python") + pyc = newMIME("application/x-bytecode.python", ".pyc", magic.Pyc) + ruby = newMIME("text/x-ruby", ".rb", magic.Ruby). + alias("application/x-ruby") + shell = newMIME("text/x-shellscript", ".sh", magic.Shell). + alias("text/x-sh", "application/x-shellscript", "application/x-sh") + tcl = newMIME("text/x-tcl", ".tcl", magic.Tcl). + alias("application/x-tcl") + vCard = newMIME("text/vcard", ".vcf", magic.VCard) + iCalendar = newMIME("text/calendar", ".ics", magic.ICalendar) + svg = newMIME("image/svg+xml", ".svg", magic.Svg) + rss = newMIME("application/rss+xml", ".rss", magic.Rss). + alias("text/rss") + owl2 = newMIME("application/owl+xml", ".owl", magic.Owl2) + atom = newMIME("application/atom+xml", ".atom", magic.Atom) + x3d = newMIME("model/x3d+xml", ".x3d", magic.X3d) + kml = newMIME("application/vnd.google-earth.kml+xml", ".kml", magic.Kml) + kmz = newMIME("application/vnd.google-earth.kmz", ".kmz", magic.KMZ) + xliff = newMIME("application/x-xliff+xml", ".xlf", magic.Xliff) + collada = newMIME("model/vnd.collada+xml", ".dae", magic.Collada) + gml = newMIME("application/gml+xml", ".gml", magic.Gml) + gpx = newMIME("application/gpx+xml", ".gpx", magic.Gpx) + tcx = newMIME("application/vnd.garmin.tcx+xml", ".tcx", magic.Tcx) + amf = newMIME("application/x-amf", ".amf", magic.Amf) + threemf = newMIME("application/vnd.ms-package.3dmanufacturing-3dmodel+xml", ".3mf", magic.Threemf) + cdxxml = newMIME("application/vnd.cyclonedx+xml", ".xml", magic.CDXXML) + png = newMIME("image/png", ".png", magic.Png, apng) + apng = newMIME("image/apng", ".apng", magic.Apng). + alias("image/vnd.mozilla.apng") + jpg = newMIME("image/jpeg", ".jpg", magic.Jpg) + jxl = newMIME("image/jxl", ".jxl", magic.Jxl) + jp2 = newMIME("image/jp2", ".jp2", magic.Jp2) + jpx = newMIME("image/jpx", ".jpf", magic.Jpx) + jpm = newMIME("image/jpm", ".jpm", magic.Jpm). + alias("video/jpm") + jxs = newMIME("image/jxs", ".jxs", magic.Jxs) + xpm = newMIME("image/x-xpixmap", ".xpm", magic.Xpm) + bpg = newMIME("image/bpg", ".bpg", magic.Bpg) + gif = newMIME("image/gif", ".gif", magic.Gif) + webp = newMIME("image/webp", ".webp", magic.Webp) + tiff = newMIME("image/tiff", ".tiff", magic.Tiff) + bmp = newMIME("image/bmp", ".bmp", magic.Bmp). + alias("image/x-bmp", "image/x-ms-bmp") + // lotus check must be done before ico because some ico detection is a bit + // relaxed and some lotus files are wrongfully identified as ico otherwise. + lotus = newMIME("application/vnd.lotus-1-2-3", ".123", magic.Lotus123) + ico = newMIME("image/x-icon", ".ico", magic.Ico) + icns = newMIME("image/x-icns", ".icns", magic.Icns) + psd = newMIME("image/vnd.adobe.photoshop", ".psd", magic.Psd). + alias("image/x-psd", "application/photoshop") + heic = newMIME("image/heic", ".heic", magic.Heic) + heicSeq = newMIME("image/heic-sequence", ".heic", magic.HeicSequence) + heif = newMIME("image/heif", ".heif", magic.Heif) + heifSeq = newMIME("image/heif-sequence", ".heif", magic.HeifSequence) + hdr = newMIME("image/vnd.radiance", ".hdr", magic.Hdr) + avif = newMIME("image/avif", ".avif", magic.AVIF) + mp3 = newMIME("audio/mpeg", ".mp3", magic.MP3). + alias("audio/x-mpeg", "audio/mp3") + flac = newMIME("audio/flac", ".flac", magic.Flac) + midi = newMIME("audio/midi", ".midi", magic.Midi). + alias("audio/mid", "audio/sp-midi", "audio/x-mid", "audio/x-midi") + ape = newMIME("audio/ape", ".ape", magic.Ape) + musePack = newMIME("audio/musepack", ".mpc", magic.MusePack) + wav = newMIME("audio/wav", ".wav", magic.Wav). + alias("audio/x-wav", "audio/vnd.wave", "audio/wave") + aiff = newMIME("audio/aiff", ".aiff", magic.Aiff).alias("audio/x-aiff") + au = newMIME("audio/basic", ".au", magic.Au) + amr = newMIME("audio/amr", ".amr", magic.Amr). + alias("audio/amr-nb") + aac = newMIME("audio/aac", ".aac", magic.AAC) + voc = newMIME("audio/x-unknown", ".voc", magic.Voc) + aMp4 = newMIME("audio/mp4", ".mp4", magic.AMp4). + alias("audio/x-mp4a") + m4a = newMIME("audio/x-m4a", ".m4a", magic.M4a) + m3u = newMIME("application/vnd.apple.mpegurl", ".m3u", magic.M3U). + alias("audio/mpegurl", "application/x-mpegurl") + m4v = newMIME("video/x-m4v", ".m4v", magic.M4v) + mj2 = newMIME("video/mj2", ".mj2", magic.Mj2) + dvb = newMIME("video/vnd.dvb.file", ".dvb", magic.Dvb) + mp4 = newMIME("video/mp4", ".mp4", magic.Mp4, avif, threeGP, threeG2, aMp4, mqv, m4a, m4v, heic, heicSeq, heif, heifSeq, mj2, dvb) + webM = newMIME("video/webm", ".webm", magic.WebM). + alias("audio/webm") + mpeg = newMIME("video/mpeg", ".mpeg", magic.Mpeg) + quickTime = newMIME("video/quicktime", ".mov", magic.QuickTime) + mqv = newMIME("video/quicktime", ".mqv", magic.Mqv) + threeGP = newMIME("video/3gpp", ".3gp", magic.ThreeGP). + alias("video/3gp", "audio/3gpp") + threeG2 = newMIME("video/3gpp2", ".3g2", magic.ThreeG2). + alias("video/3g2", "audio/3gpp2") + avi = newMIME("video/x-msvideo", ".avi", magic.Avi). + alias("video/avi", "video/msvideo") + flv = newMIME("video/x-flv", ".flv", magic.Flv) + mkv = newMIME("video/matroska", ".mkv", magic.Mkv). + alias("video/x-matroska") + asf = newMIME("video/x-ms-asf", ".asf", magic.Asf). + alias("video/asf", "video/x-ms-wmv") + rmvb = newMIME("application/vnd.rn-realmedia-vbr", ".rmvb", magic.Rmvb) + class = newMIME("application/x-java-applet", ".class", magic.Class) + swf = newMIME("application/x-shockwave-flash", ".swf", magic.SWF) + crx = newMIME("application/x-chrome-extension", ".crx", magic.CRX) + ttf = newMIME("font/ttf", ".ttf", magic.Ttf). + alias("font/sfnt", "application/x-font-ttf", "application/font-sfnt") + woff = newMIME("font/woff", ".woff", magic.Woff) + woff2 = newMIME("font/woff2", ".woff2", magic.Woff2) + otf = newMIME("font/otf", ".otf", magic.Otf) + ttc = newMIME("font/collection", ".ttc", magic.Ttc) + eot = newMIME("application/vnd.ms-fontobject", ".eot", magic.Eot) + wasm = newMIME("application/wasm", ".wasm", magic.Wasm) + shp = newMIME("application/vnd.shp", ".shp", magic.Shp) + shx = newMIME("application/vnd.shx", ".shx", magic.Shx, shp) + dbf = newMIME("application/x-dbf", ".dbf", magic.Dbf) + exe = newMIME("application/vnd.microsoft.portable-executable", ".exe", magic.Exe) + elf = newMIME("application/x-elf", "", magic.Elf, elfObj, elfExe, elfLib, elfDump) + elfObj = newMIME("application/x-object", "", magic.ElfObj) + elfExe = newMIME("application/x-executable", "", magic.ElfExe) + elfLib = newMIME("application/x-sharedlib", ".so", magic.ElfLib) + elfDump = newMIME("application/x-coredump", "", magic.ElfDump) + ar = newMIME("application/x-archive", ".a", magic.Ar, deb). + alias("application/x-unix-archive") + deb = newMIME("application/vnd.debian.binary-package", ".deb", magic.Deb) + rpm = newMIME("application/x-rpm", ".rpm", magic.RPM) + dcm = newMIME("application/dicom", ".dcm", magic.Dcm) + odt = newMIME("application/vnd.oasis.opendocument.text", ".odt", magic.Odt, ott). + alias("application/x-vnd.oasis.opendocument.text") + ott = newMIME("application/vnd.oasis.opendocument.text-template", ".ott", magic.Ott). + alias("application/x-vnd.oasis.opendocument.text-template") + ods = newMIME("application/vnd.oasis.opendocument.spreadsheet", ".ods", magic.Ods, ots). + alias("application/x-vnd.oasis.opendocument.spreadsheet") + ots = newMIME("application/vnd.oasis.opendocument.spreadsheet-template", ".ots", magic.Ots). + alias("application/x-vnd.oasis.opendocument.spreadsheet-template") + odp = newMIME("application/vnd.oasis.opendocument.presentation", ".odp", magic.Odp, otp). + alias("application/x-vnd.oasis.opendocument.presentation") + otp = newMIME("application/vnd.oasis.opendocument.presentation-template", ".otp", magic.Otp). + alias("application/x-vnd.oasis.opendocument.presentation-template") + odg = newMIME("application/vnd.oasis.opendocument.graphics", ".odg", magic.Odg, otg). + alias("application/x-vnd.oasis.opendocument.graphics") + otg = newMIME("application/vnd.oasis.opendocument.graphics-template", ".otg", magic.Otg). + alias("application/x-vnd.oasis.opendocument.graphics-template") + odf = newMIME("application/vnd.oasis.opendocument.formula", ".odf", magic.Odf). + alias("application/x-vnd.oasis.opendocument.formula") + odc = newMIME("application/vnd.oasis.opendocument.chart", ".odc", magic.Odc). + alias("application/x-vnd.oasis.opendocument.chart") + sxc = newMIME("application/vnd.sun.xml.calc", ".sxc", magic.Sxc) + rar = newMIME("application/vnd.rar", ".rar", magic.RAR). + alias("application/x-rar-compressed", "application/x-rar") + djvu = newMIME("image/vnd.djvu", ".djvu", magic.DjVu) + mobi = newMIME("application/x-mobipocket-ebook", ".mobi", magic.Mobi) + lit = newMIME("application/x-ms-reader", ".lit", magic.Lit) + sqlite3 = newMIME("application/vnd.sqlite3", ".sqlite", magic.Sqlite). + alias("application/x-sqlite3") + dwg = newMIME("image/vnd.dwg", ".dwg", magic.Dwg). + alias("image/x-dwg", "application/acad", "application/x-acad", + "application/autocad_dwg", "application/dwg", "application/x-dwg", + "application/x-autocad", "drawing/dwg") + warc = newMIME("application/warc", ".warc", magic.Warc) + nes = newMIME("application/vnd.nintendo.snes.rom", ".nes", magic.Nes) + lnk = newMIME("application/x-ms-shortcut", ".lnk", magic.Lnk) + macho = newMIME("application/x-mach-binary", ".macho", magic.MachO) + qcp = newMIME("audio/qcelp", ".qcp", magic.Qcp) + mrc = newMIME("application/marc", ".mrc", magic.Marc) + mdb = newMIME("application/x-msaccess", ".mdb", magic.MsAccessMdb) + accdb = newMIME("application/x-msaccess", ".accdb", magic.MsAccessAce) + zstd = newMIME("application/zstd", ".zst", magic.Zstd) + cab = newMIME("application/vnd.ms-cab-compressed", ".cab", magic.Cab) + cabIS = newMIME("application/x-installshield", ".cab", magic.InstallShieldCab) + lzip = newMIME("application/lzip", ".lz", magic.Lzip).alias("application/x-lzip") + torrent = newMIME("application/x-bittorrent", ".torrent", magic.Torrent) + cpio = newMIME("application/x-cpio", ".cpio", magic.Cpio) + tzif = newMIME("application/tzif", "", magic.TzIf) + p7s = newMIME("application/pkcs7-signature", ".p7s", magic.P7s) + xcf = newMIME("image/x-xcf", ".xcf", magic.Xcf) + pat = newMIME("image/x-gimp-pat", ".pat", magic.Pat) + gbr = newMIME("image/x-gimp-gbr", ".gbr", magic.Gbr) + xfdf = newMIME("application/vnd.adobe.xfdf", ".xfdf", magic.Xfdf) + glb = newMIME("model/gltf-binary", ".glb", magic.GLB) + gltf = newMIME("model/gltf+json", ".gltf", magic.GLTF) + jxr = newMIME("image/jxr", ".jxr", magic.Jxr).alias("image/vnd.ms-photo") + parquet = newMIME("application/vnd.apache.parquet", ".parquet", magic.Par1). + alias("application/x-parquet") + netpbm = newMIME("image/x-portable-bitmap", ".pbm", magic.NetPBM) + netpgm = newMIME("image/x-portable-graymap", ".pgm", magic.NetPGM) + netppm = newMIME("image/x-portable-pixmap", ".ppm", magic.NetPPM) + netpam = newMIME("image/x-portable-arbitrarymap", ".pam", magic.NetPAM) + cbor = newMIME("application/cbor", ".cbor", magic.CBOR) + oneNote = newMIME("application/onenote", ".one", magic.One) + chm = newMIME("application/vnd.ms-htmlhelp", ".chm", magic.CHM) + wpd = newMIME("application/vnd.wordperfect", ".wpd", magic.WPD) + dxf = newMIME("image/vnd.dxf", ".dxf", magic.DXF) + rfc822 = newMIME("message/rfc822", ".eml", magic.RFC822) + grib = newMIME("application/grib", ".grb", magic.GRIB) + zlib = newMIME("application/zlib", "", magic.Zlib) + inf = newMIME("application/x-os2-inf", ".inf", magic.Inf) + hlp = newMIME("application/x-os2-hlp", ".hlp", magic.Hlp) + fm = newMIME("application/vnd.framemaker", ".fm", magic.FrameMaker) + bufr = newMIME("application/bufr", ".bufr", magic.BUFR) + gedcom = newMIME("text/vnd.familysearch.gedcom", ".ged", magic.GEDCOM) + pcap = newMIME("application/vnd.tcpdump.pcap", ".pcap", magic.Pcap) +) diff --git a/vendor/github.com/getsentry/sentry-go/.codecov.yml b/vendor/github.com/getsentry/sentry-go/.codecov.yml new file mode 100644 index 0000000..c44ceb2 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/.codecov.yml @@ -0,0 +1,12 @@ +coverage: + status: + project: + default: + # Do not fail the commit status if the coverage was reduced up to this value + threshold: 0.5% + patch: + default: + informational: true +ignore: + - "log_fallback.go" + - "internal/testutils" diff --git a/vendor/github.com/getsentry/sentry-go/.craft.yml b/vendor/github.com/getsentry/sentry-go/.craft.yml new file mode 100644 index 0000000..6c923e3 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/.craft.yml @@ -0,0 +1,59 @@ +minVersion: 2.24.1 +changelog: + policy: auto +versioning: + policy: auto +artifactProvider: + name: none +preReleaseCommand: bash scripts/bump-version.sh +targets: + - name: github + tagPrefix: v + - name: github + tagPrefix: otel/v + tagOnly: true + - name: github + tagPrefix: otel/otlp/v + tagOnly: true + - name: github + tagPrefix: echo/v + tagOnly: true + - name: github + tagPrefix: fasthttp/v + tagOnly: true + - name: github + tagPrefix: fiber/v + tagOnly: true + - name: github + tagPrefix: fiberv3/v + tagOnly: true + - name: github + tagPrefix: gin/v + tagOnly: true + - name: github + tagPrefix: grpc/v + tagOnly: true + - name: github + tagPrefix: iris/v + tagOnly: true + - name: github + tagPrefix: negroni/v + tagOnly: true + - name: github + tagPrefix: logrus/v + tagOnly: true + - name: github + tagPrefix: slog/v + tagOnly: true + - name: github + tagPrefix: sql/v + tagOnly: true + - name: github + tagPrefix: zerolog/v + tagOnly: true + - name: github + tagPrefix: zap/v + tagOnly: true + - name: registry + sdks: + github:getsentry/sentry-go: diff --git a/vendor/github.com/getsentry/sentry-go/.gitattributes b/vendor/github.com/getsentry/sentry-go/.gitattributes new file mode 100644 index 0000000..bccfeea --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/.gitattributes @@ -0,0 +1,5 @@ +# Tell Git to use LF for line endings on all platforms. +# Required to have correct test data on Windows. +# https://github.com/mvdan/github-actions-golang#caveats +# https://github.com/actions/checkout/issues/135#issuecomment-613361104 +* text eol=lf diff --git a/vendor/github.com/getsentry/sentry-go/.gitignore b/vendor/github.com/getsentry/sentry-go/.gitignore new file mode 100644 index 0000000..213d49a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/.gitignore @@ -0,0 +1,21 @@ +# Code coverage artifacts +coverage.txt +coverage.out +coverage.html +.coverage/ + +# Just my personal way of tracking stuff — Kamil +FIXME.md +TODO.md +!NOTES.md + +# IDE system files +.idea +.vscode + +# Local Claude Code settings that should not be committed +.claude/settings.local.json +# .agents/.gitignore is generated by dotagents — don't commit it. +.agents/.gitignore +# Auto-generated by dotagents — do not commit these files. +agents.lock diff --git a/vendor/github.com/getsentry/sentry-go/.golangci.yml b/vendor/github.com/getsentry/sentry-go/.golangci.yml new file mode 100644 index 0000000..6dc3dc9 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/.golangci.yml @@ -0,0 +1,66 @@ +version: "2" +linters: + default: none + enable: + - bodyclose + - dogsled + - dupl + - errcheck + - gochecknoinits + - goconst + - gocritic + - gocyclo + - godot + - gosec + - govet + - ineffassign + - misspell + - nakedret + - prealloc + - revive + - staticcheck + - unconvert + - unparam + - unused + - whitespace + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - goconst + - prealloc + path: _test\.go + - linters: + - gosec + path: _test\.go + text: "G306:" + - linters: + - staticcheck + path: _test\.go + text: "SA5011" + - linters: + - unused + path: errors_test\.go + - linters: + - bodyclose + - errcheck + path: http/example_test\.go + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gofmt + - goimports + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/vendor/github.com/getsentry/sentry-go/AGENTS.md b/vendor/github.com/getsentry/sentry-go/AGENTS.md new file mode 100644 index 0000000..f040abe --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/AGENTS.md @@ -0,0 +1,107 @@ +# Sentry Go SDK + +Single-module Go SDK with integration sub-modules in `github.com/getsentry/sentry-go`. + +## Commit Attribution + +AI commits MUST include: + +``` +Co-Authored-By: +``` + +## Before Every Commit + +1. `make fmt` 2. `make lint` 3. `make vet` 4. `make test-race` + +## Architecture + +### Core (`/`) + +The root package `sentry` contains the entire public API. + +### Attribute Package (`/attribute/`) + +Type-safe key-value builders used by structured logging and metrics: + +```go +attribute.String("key", "value") +attribute.Int("count", 42) +attribute.Float64("ratio", 0.5) +attribute.Bool("flag", true) +``` + +### Integration Sub-Modules + +Each lives in its own directory with a separate `go.mod`: + +- **HTTP middleware** — `http/`, `gin/`, `echo/`, `fiber/`, `fasthttp/`, `iris/`, `negroni/` +- **Logging hooks** — `logrus/`, `zerolog/`, `zap/`, `slog/` +- **Instrumentation** — `httpclient/`, `otel/` + +When adding a new integration, mirror an existing one. + +### Transport Architecture + +**Current: `transport.go` (active)** — `HTTPTransport` is the default implementation of an async transport. `HTTPSyncTransport` is the blocking variant for serverless. + +**Next: `internal/telemetry/` + `internal/http/` (not yet enabled)** — Processor/buffer/scheduler architecture. Wired up in `client.go` (`setupTelemetryProcessor`) but **commented out** behind `DisableTelemetryBuffer`. Key parts: + +- `internal/telemetry/processor.go` — orchestrator; routes items to category-specific buffers +- `internal/telemetry/scheduler.go` — weighted round-robin; errors get 5x priority over logs +- `internal/telemetry/ring_buffer.go` — circular buffer with overflow policies and batch/timeout flushing +- `internal/telemetry/bucketed_buffer.go` — groups items by trace ID +- `internal/http/transport.go` — `AsyncTransport` with `HasCapacity()` backpressure +- `internal/protocol/` — `Envelope`, `TelemetryItem` interfaces; log/metric batch types + +The `internalAsyncTransportAdapter` in `transport.go` bridges old `Transport` to new `TelemetryTransport`. + +## Coding Standards + +- Follow existing conventions — check neighboring files first +- Maintain existing Go versions and dependencies unless explicitly asked to change them +- `gofmt -s` formatting, doc comments on exports +- Public API in root package; internals in `/internal` +- Thread safety required — guard shared state with mutexes +- Update tests when modifying behavior + +## Testing + +Test tier preference (use the highest tier that covers what you need): + +1. **Integration tests** (default) — Prefer `internal/sentrytest` with `sentrytest.Run` or `sentrytest.NewFixture`, plus real routers / `httptest` requests where needed. Prefer tests that use the public API. +2. **Context-level tests** — Prefer `sentrytest.NewContext` or `fixture.NewContext(parent)` for tracing / context propagation tests. Prefer `sentrytest.NewFixture` for isolated client + hub setup when no HTTP server is needed. +3. **Unit tests** (sparingly) — Direct `NewClient` + `MockScope` only for self-contained logic where `sentrytest` would add unnecessary indirection. + +Conventions: + +- Table-driven tests for multiple inputs through the same code path +- `t.Parallel()` for tests that don't share global state +- `cmp.Diff` with `cmpopts.IgnoreFields` for `*Event` comparison — ignore `EventID`, `Timestamp`, `Sdk`, `sdkMetaData` +- Prefer `fixture.Flush()` over direct `sentry.Flush(...)` in tests built on `internal/sentrytest` +- Prefer `fixture.Events()` as the captured event stream; inspect `event.Type` in assertions instead of relying on separate fixture streams +- `testify` for assertions, `internal/testutils/` for non-assert test helpers like mocks and flush timing +- All tests must pass `make test-race` + +What to test: + +- Behavior users observe: Does middleware capture panics? Does `Flush` deliver events? Do trace headers propagate? +- Edge cases at system boundaries: malformed DSN, nil `Hub`, concurrent captures, context cancellation +- Regressions: reproduce the failure before applying the fix + +Thread safety: + +- The SDK is used concurrently. Any test touching shared state (`Hub`, `Scope`, `CurrentHub`) must either use `t.Parallel()` with isolated instances, or explicitly verify safety with goroutines and `sync.WaitGroup`. + +## Reference + +- [SDK Development Guide](https://develop.sentry.dev/sdk/) +- [Commit Guidelines](https://develop.sentry.dev/engineering-practices/commit-messages/) +- [Hubs & Scopes](https://develop.sentry.dev/sdk/unified-api/#hub) + +## Skills + +- `/commit` — Commit with Sentry conventional format +- `/create-pr` — Create PRs following Sentry conventions +- `/code-review` — Review PRs following Sentry practices +- `/find-bugs` — Audit local changes for bugs and security issues diff --git a/vendor/github.com/getsentry/sentry-go/CHANGELOG.md b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md new file mode 100644 index 0000000..8da887e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/CHANGELOG.md @@ -0,0 +1,1730 @@ +# 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 🛠 + +- Remove issue creation from logging integrations by @giortzisg in [#1340](https://github.com/getsentry/sentry-go/pull/1340) + +### New Features ✨ + +- Add `ClientOptions.DataCollection` for granular control over data collected by automatic instrumentation, replacing the broad `SendDefaultPII` switch. `DataCollection` can independently configure automatic `user.*` population, cookies, request/response headers, HTTP bodies, and query parameters. When configured, it is the source of truth and `SendDefaultPII` is ignored. by @giortzisg in [#1339](https://github.com/getsentry/sentry-go/pull/1339) + - For backwards compatibility, clients that do not configure `DataCollection` keep a best-effort mapping of the previous `SendDefaultPII` behavior. To opt in to the new defaults, pass an empty `DataCollection` and then restrict individual categories as needed. + ```go + sentry.Init(sentry.ClientOptions{ + Dsn: "https://public@example.com/1", + + // Opt in to the new data collection defaults. Omitted fields use their + // defaults: user info, cookies, headers, query params, and supported HTTP + // bodies are collected, with sensitive values filtered. + DataCollection: &sentry.DataCollection{}, + }) + ``` + - To opt in while disabling automatic user info and HTTP bodies, configure those fields explicitly: + ```go + sentry.Init(sentry.ClientOptions{ + Dsn: "https://public@example.com/1", + DataCollection: &sentry.DataCollection{ + UserInfo: sentry.Set(false), + HTTPBodies: []sentry.BodyType{}, + }, + }) + ``` +- PushScope shorthand now returns the new scope reference by @DoctorJohn in [#1335](https://github.com/getsentry/sentry-go/pull/1335) + +### Bug Fixes 🐛 + +- Fix fiber route name when using middlewares by @giortzisg in [#1363](https://github.com/getsentry/sentry-go/pull/1363) +- Omit empty event id for standalone client reports by @giortzisg in [#1362](https://github.com/getsentry/sentry-go/pull/1362) +- Preserve '%' literal in log messages by @giortzisg in [#1358](https://github.com/getsentry/sentry-go/pull/1358) +- Unaligned 64-bit atomic panic on 32-bit platforms in telemetry buffers by @Kirill-INQ in [#1355](https://github.com/getsentry/sentry-go/pull/1355) +- Isolate event processor across clones by @giortzisg in [#1337](https://github.com/getsentry/sentry-go/pull/1337) + +### Internal Changes 🔧 + +#### Deps + +- Bump fiber/v2 to 2.52.14 by @giortzisg in [#1359](https://github.com/getsentry/sentry-go/pull/1359) +- Bump actions/checkout from 6.0.3 to 7.0.0 by @dependabot in [#1349](https://github.com/getsentry/sentry-go/pull/1349) +- Bump golangci/golangci-lint-action from 9.2.1 to 9.3.0 by @dependabot in [#1346](https://github.com/getsentry/sentry-go/pull/1346) +- Bump codecov/codecov-action from 6.0.0 to 7.0.0 by @dependabot in [#1347](https://github.com/getsentry/sentry-go/pull/1347) +- Bump actions/setup-go from 6.4.0 to 6.5.0 by @dependabot in [#1343](https://github.com/getsentry/sentry-go/pull/1343) +- Bump golang.org/x/crypto to 0.52.0 and golang/x/net to 0.55.0 by @giortzisg in [#1341](https://github.com/getsentry/sentry-go/pull/1341) +- Bump getsentry/github-workflows/validate-pr from c802283cd9075b7a2b7a32655019c21c21676e34 to 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 by @dependabot in [#1344](https://github.com/getsentry/sentry-go/pull/1344) + +#### Other + +- Remove changelog-preview and codecov actions by @giortzisg in [#1357](https://github.com/getsentry/sentry-go/pull/1357) +- Add govulncheck audit action by @giortzisg in [#1342](https://github.com/getsentry/sentry-go/pull/1342) +- Limit changelog-preview secret access by @giortzisg in [#1350](https://github.com/getsentry/sentry-go/pull/1350) +- Move limited buffer under utils by @giortzisg in [#1338](https://github.com/getsentry/sentry-go/pull/1338) + +## 0.47.0 + +### Breaking Changes 🛠 + +- Fix `transaction_info` source getting set incorrectly across HTTP middleware integrations (http, fasthttp, fiber). Users should now expect traces to properly get grouped with their parameterized path. Transactions in affected integrations may regroup after upgrading. by @giortzisg in [#1325](https://github.com/getsentry/sentry-go/pull/1325) +- remove deprecated`otel.NewSentrySpanProcessor`. Users should now use the `sentryotlp.NewTraceExporter` instead by @giortzisg in [#1307](https://github.com/getsentry/sentry-go/pull/1307) + ```go + // Before + sentry.Init(sentry.ClientOptions{Dsn: dsn, EnableTracing: true, TracesSampleRate: 1.0}) + + tp := sdktrace.NewTracerProvider( + sdktrace.WithSpanProcessor(sentryotel.NewSentrySpanProcessor()), + ) + otel.SetTextMapPropagator(sentryotel.NewSentryPropagator()) + otel.SetTracerProvider(tp) + + // After: + sentry.Init(sentry.ClientOptions{ + Dsn: dsn, EnableTracing: true, TracesSampleRate: 1.0, + Integrations: func(i []sentry.Integration) []sentry.Integration { + return append(i, sentryotel.NewOtelIntegration()) + }, + }) + + exporter, _ := sentryotlp.NewTraceExporter(ctx, dsn) + tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter)) + otel.SetTracerProvider(tp) + ``` +- Enable logs by default to skip double allow behavior. Enabling logs now happens once when setting up either `sentry.NewLogger` or any supported integration. Also the EnableLogs flag changes to DisableLogs for a global override switch by @giortzisg in [#1306](https://github.com/getsentry/sentry-go/pull/1306) +- Remove the `ContextifyFrames` integration. The recommended way to add source context is [SCM](https://docs.sentry.io/integrations/source-code-mgmt/source-context/) by @giortzisg in [#1302](https://github.com/getsentry/sentry-go/pull/1302) + +### New Features ✨ + +- Add fiber v3 integration by @giortzisg in [#1324](https://github.com/getsentry/sentry-go/pull/1324) +- Bump fasthttp from 1.51.0 to 1.71.0 by @giortzisg in [#1324](https://github.com/getsentry/sentry-go/pull/1324) +- Add sentrysql SQL tracing integration by @giortzisg in [#1305](https://github.com/getsentry/sentry-go/pull/1305) + - Supports multiple integration paths depending on how your app opens database connections: `sentrysql.Open(...)`, `sentrysql.OpenDB(...)`, and wrapped drivers/connectors for custom setups. + - Database metadata is not inferred in every setup. If the database name is not discoverable automatically, pass `sentrysql.WithDatabaseName(...)` so spans are populated correctly. + - Example: + ```go + // Simple driver-based setup + db, err := sentrysql.Open("sqlite", ":memory:", + sentrysql.WithDatabaseSystem(sentrysql.SystemSQLite), + sentrysql.WithDatabaseName("main"), + ) + ``` + +### Internal Changes 🔧 + +#### Deps + +- Sync go.work by @giortzisg in [#1326](https://github.com/getsentry/sentry-go/pull/1326) +- Bump github.com/stretchr/testify from 1.8.4 to 1.11.1 by @giortzisg in [#1326](https://github.com/getsentry/sentry-go/pull/1326) +- Bump github.com/google/go-cmp from 0.5.9 to 0.7.0 by @giortzisg in [#1326](https://github.com/getsentry/sentry-go/pull/1326) +- Bump getsentry/github-workflows from 71588ddf95134f804e82c5970a8098588e2eaecd to c802283cd9075b7a2b7a32655019c21c21676e34 by @dependabot in [#1314](https://github.com/getsentry/sentry-go/pull/1314) +- Bump actions/create-github-app-token from 3.0.0 to 3.2.0 by @dependabot in [#1316](https://github.com/getsentry/sentry-go/pull/1316) +- Bump actions/checkout from 6.0.2 to 6.0.3 by @dependabot in [#1313](https://github.com/getsentry/sentry-go/pull/1313) +- Bump getsentry/craft/.github/workflows/changelog-preview.yml from 2.26.2 to 2.26.6 by @dependabot in [#1317](https://github.com/getsentry/sentry-go/pull/1317) +- Bump getsentry/craft from 2.26.2 to 2.26.6 by @dependabot in [#1318](https://github.com/getsentry/sentry-go/pull/1318) +- Bump golangci/golangci-lint-action from 9.2.0 to 9.2.1 by @dependabot in [#1315](https://github.com/getsentry/sentry-go/pull/1315) +- Bump github.com/gofiber/fiber/v2 from 2.52.12 to 2.52.13 in /fiber by @dependabot in [#1300](https://github.com/getsentry/sentry-go/pull/1300) +- Bump github.com/gofiber/fiber/v2 from 2.52.12 to 2.52.13 in /crosstest by @dependabot in [#1301](https://github.com/getsentry/sentry-go/pull/1301) +- Bump getsentry/craft from 2.25.2 to 2.26.2 by @dependabot in [#1293](https://github.com/getsentry/sentry-go/pull/1293) +- Bump getsentry/craft/.github/workflows/changelog-preview.yml from 2.25.2 to 2.26.2 by @dependabot in [#1294](https://github.com/getsentry/sentry-go/pull/1294) + +#### Other + +- (otel) Remove unused semconv helpers by @giortzisg in [#1321](https://github.com/getsentry/sentry-go/pull/1321) +- Update bump-version script to also bump crosstest by @giortzisg in [#1327](https://github.com/getsentry/sentry-go/pull/1327) + +## 0.46.2 + +### Bug Fixes 🐛 + +- Add attachments to new event path by @giortzisg in [#1295](https://github.com/getsentry/sentry-go/pull/1295) + +## 0.46.1 + +### Bug Fixes 🐛 + +- Correctly capture request body for fasthttp and fiber. by @giortzisg in [#1284](https://github.com/getsentry/sentry-go/pull/1284) +- (http) Avoid async transport shutdown panics by @giortzisg in [#1288](https://github.com/getsentry/sentry-go/pull/1288) +- (httpclient) Clone request before adding trace headers by @giortzisg in [#1290](https://github.com/getsentry/sentry-go/pull/1290) +- (scope) Use scoped client for request PII by @giortzisg in [#1289](https://github.com/getsentry/sentry-go/pull/1289) +- Safe concurrent access for span and scope by @giortzisg in [#1285](https://github.com/getsentry/sentry-go/pull/1285) + +## 0.46.0 + +### Breaking Changes 🛠 + +- Remove SetExtra by @giortzisg in [#1274](https://github.com/getsentry/sentry-go/pull/1274) +- Update compatibility policy to align with Go, supporting only the last two major Go versions by @giortzisg in [#1264](https://github.com/getsentry/sentry-go/pull/1264) +- Drop support for Go 1.24 by @giortzisg in [#1264](https://github.com/getsentry/sentry-go/pull/1264) + +### New Features ✨ + +- Add internal_sdk_error client report on serialization fail by @giortzisg in [#1273](https://github.com/getsentry/sentry-go/pull/1273) +- Add grpc integration support by @ribice in [#938](https://github.com/getsentry/sentry-go/pull/938) +- Re-enable Telemetry Processor by default. To disable the behavior use the `DisableTelemetryBuffer` flag by @giortzisg in [#1254](https://github.com/getsentry/sentry-go/pull/1254) +- Simplify client DSN storage to `internal/protocol.Dsn` and make it safe to access by @giortzisg in [#1254](https://github.com/getsentry/sentry-go/pull/1254) + +### Internal Changes 🔧 + +#### Deps + +- Bump github.com/labstack/echo/v5 from 5.0.0 to 5.0.3 in /echo by @dependabot in [#1253](https://github.com/getsentry/sentry-go/pull/1253) +- Bump github.com/labstack/echo/v5 from 5.0.0 to 5.0.3 in /crosstest by @dependabot in [#1272](https://github.com/getsentry/sentry-go/pull/1272) +- Bump golangci-lint action from 2.1.1 to 2.11.4 by @giortzisg in [#1265](https://github.com/getsentry/sentry-go/pull/1265) +- Bump go.opentelemetry.io/otel/sdk from 1.40.0 to 1.43.0 in /otel by @dependabot in [#1256](https://github.com/getsentry/sentry-go/pull/1256) +- Bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.40.0 to 1.43.0 in /otel/otlp by @dependabot in [#1255](https://github.com/getsentry/sentry-go/pull/1255) + +#### Other + +- Improve ci by @giortzisg in [#1271](https://github.com/getsentry/sentry-go/pull/1271) +- Add crosstest package by @giortzisg in [#1269](https://github.com/getsentry/sentry-go/pull/1269) +- Add sentrytest package by @giortzisg in [#1267](https://github.com/getsentry/sentry-go/pull/1267) + +## 0.45.1 + +### Bug Fixes 🐛 + +- Add missing TracesSampler fields for SamplingContext by @giortzisg in [#1259](https://github.com/getsentry/sentry-go/pull/1259) + +## 0.45.0 + +### Breaking Changes 🛠 + +- Add support for Echo v5 by @Scorfly in [#1183](https://github.com/getsentry/sentry-go/pull/1183) + +### New Features ✨ + +- Add OTLP trace exporter via new otel/otlp sub-module by @giortzisg in [#1229](https://github.com/getsentry/sentry-go/pull/1229) + - sentryotlp.NewTraceExporter sends OTel spans directly to Sentry's OTLP endpoint. + - sentryotel.NewOtelIntegration links Sentry errors, logs, and metrics to the active OTel trace. Works with both direct-to-Sentry and collector-based setups. + - NewSentrySpanProcessor, NewSentryPropagator, and SentrySpanMap are deprecated and will be removed in 0.47.0. To Migrate use `sentryotlp.NewTraceExporter` instead: + ```go + // Before + sentry.Init(sentry.ClientOptions{Dsn: dsn, EnableTracing: true, TracesSampleRate: 1.0}) + + tp := sdktrace.NewTracerProvider( + sdktrace.WithSpanProcessor(sentryotel.NewSentrySpanProcessor()), + ) + otel.SetTextMapPropagator(sentryotel.NewSentryPropagator()) + otel.SetTracerProvider(tp) + + // After: + sentry.Init(sentry.ClientOptions{ + Dsn: dsn, EnableTracing: true, TracesSampleRate: 1.0, + Integrations: func(i []sentry.Integration) []sentry.Integration { + return append(i, sentryotel.NewOtelIntegration()) + }, + }) + + exporter, _ := sentryotlp.NewTraceExporter(ctx, dsn) + tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter)) + otel.SetTracerProvider(tp) + ``` +- Add IsSensitiveHeader helper to easily distinguish which headers to scrub for PII. by @giortzisg in [#1239](https://github.com/getsentry/sentry-go/pull/1239) + +### Bug Fixes 🐛 + +- (ci) Update validate-pr action to remove draft enforcement by @stephanie-anderson in [#1237](https://github.com/getsentry/sentry-go/pull/1237) +- (fiber) Use UserContext for transaction to enable OTel trace linking by @giortzisg in [#1252](https://github.com/getsentry/sentry-go/pull/1252) +- Race condition when getting envelope identifier by @giortzisg in [#1250](https://github.com/getsentry/sentry-go/pull/1250) + +### Internal Changes 🔧 + +#### Deps + +- Bump OpenTelemetry SDK to 1.40.0 by @giortzisg in [#1243](https://github.com/getsentry/sentry-go/pull/1243) +- Bump changelog-preview.yml from 2.24.1 to 2.25.2 by @dependabot in [#1247](https://github.com/getsentry/sentry-go/pull/1247) +- Bump getsentry/craft from 2.24.1 to 2.25.2 by @dependabot in [#1248](https://github.com/getsentry/sentry-go/pull/1248) +- Bump codecov/codecov-action from 5.5.2 to 6.0.0 by @dependabot in [#1245](https://github.com/getsentry/sentry-go/pull/1245) +- Bump actions/create-github-app-token from 2.2.1 to 3.0.0 by @dependabot in [#1246](https://github.com/getsentry/sentry-go/pull/1246) +- Bump actions/setup-go from 6.3.0 to 6.4.0 by @dependabot in [#1244](https://github.com/getsentry/sentry-go/pull/1244) + +#### Other + +- Update validate-pr workflow by @stephanie-anderson in [#1242](https://github.com/getsentry/sentry-go/pull/1242) +- Add PR validation workflow by @stephanie-anderson in [#1234](https://github.com/getsentry/sentry-go/pull/1234) + +## 0.44.1 + +> [!NOTE] +> The v0.44.0 is missing due to a technical issue and had to be released again as v0.44.1 + +### New Features ✨ + +- Add RemoveAttribute api on the scope. by @giortzisg in [#1224](https://github.com/getsentry/sentry-go/pull/1224) +- Deprecate `Scope.SetExtra`, `Scope.SetExtras`, and `Scope.RemoveExtra` in favor of `Scope.SetAttributes` and `Scope.RemoveAttribute` by @giortzisg in [#1224](https://github.com/getsentry/sentry-go/pull/1224) + - The recommended migration path is to use `SetAttributes` to attach values to logs and metrics. Note that attributes do not appear on error events; if you only capture errors, use `SetTag` or `SetContext` instead. + - Before: + ```go + scope.SetExtra("key.string", "str") + scope.SetExtra("key.int", 42) + ``` + - After (for error events) — use tags and contexts: + ```go + scope.SetTag("key.string", "str") + scope.SetContext("my_data", sentry.Context{"key.int": 42}) + ``` + - After (for logs and metrics) — use attributes: + ```go + scope.SetAttributes( + attribute.String("key.string", "str"), + attribute.Int("key.int", 42), + ) + ``` +- Add support for homogenous arrays by @giortzisg in [#1203](https://github.com/getsentry/sentry-go/pull/1203) +- Add support for client reports by @giortzisg in [#1192](https://github.com/getsentry/sentry-go/pull/1192) +- Add org id propagation in sentry_baggage by @giortzisg in [#1210](https://github.com/getsentry/sentry-go/pull/1210) +- Add OrgID and StrictTraceContinuation client options. by @giortzisg in [#1210](https://github.com/getsentry/sentry-go/pull/1210) +- Add the option to set attributes on the scope by @giortzisg in [#1208](https://github.com/getsentry/sentry-go/pull/1208) + +### Bug Fixes 🐛 + +- (serialization) Pre-serialize mutable event fields to prevent race panics by @giortzisg in [#1214](https://github.com/getsentry/sentry-go/pull/1214) +- Use HEROKU_BUILD_COMMIT with HEROKU_SLUG_COMMIT as fallback by @ericapisani in [#1220](https://github.com/getsentry/sentry-go/pull/1220) + +### Internal Changes 🔧 + +#### Ai + +- Add AGENTS.md and testing guidelines by @giortzisg in [#1216](https://github.com/getsentry/sentry-go/pull/1216) +- Add dotagents configuration by @giortzisg in [#1211](https://github.com/getsentry/sentry-go/pull/1211) + +#### Deps + +- Bump github.com/buger/jsonparser from 1.1.1 to 1.1.2 in /zerolog by @dependabot in [#1231](https://github.com/getsentry/sentry-go/pull/1231) +- Bump github.com/gofiber/fiber/v2 from 2.52.11 to 2.52.12 in /fiber by @dependabot in [#1209](https://github.com/getsentry/sentry-go/pull/1209) + +#### Other + +- Pin GitHub Actions to full-length commit SHAs by @joshuarli in [#1230](https://github.com/getsentry/sentry-go/pull/1230) +- Bump getsentry/craft to 2.24.1 by @giortzisg in [#1225](https://github.com/getsentry/sentry-go/pull/1225) +- Handle independent go module versions for integrations by @giortzisg in [#1217](https://github.com/getsentry/sentry-go/pull/1217) + +## 0.43.0 + +### Breaking Changes 🛠 + +- Add support for go 1.26 by @giortzisg in [#1193](https://github.com/getsentry/sentry-go/pull/1193) + - bump minimum supported go version to 1.24 +- change type signature of attributes for Logs and Metrics. by @giortzisg in [#1205](https://github.com/getsentry/sentry-go/pull/1205) + - users are not supposed to modify Attributes directly on the Log/Metric itself, but this is still is a breaking change on the type. +- Send uint64 overflowing attributes as numbers. by @giortzisg in [#1198](https://github.com/getsentry/sentry-go/pull/1198) + - The SDK was converting overflowing uint64 attributes to strings for slog and logrus integrations. To eliminate double types for these attributes, the SDK now sends the overflowing attribute as is, and lets the server handle the overflow appropriately. + - It is expected that overflowing unsigned integers would now get dropped, instead of converted to strings. + +### New Features ✨ + +- Add zap logging integration by @giortzisg in [#1184](https://github.com/getsentry/sentry-go/pull/1184) +- Log specific message for RequestEntityTooLarge by @giortzisg in [#1185](https://github.com/getsentry/sentry-go/pull/1185) + +### Bug Fixes 🐛 + +- Improve otel span map cleanup performance by @giortzisg in [#1200](https://github.com/getsentry/sentry-go/pull/1200) +- Ensure correct signal delivery on multi-client setups by @giortzisg in [#1190](https://github.com/getsentry/sentry-go/pull/1190) + +### Internal Changes 🔧 + +#### Deps + +- Bump golang.org/x/crypto to 0.48.0 by @giortzisg in [#1196](https://github.com/getsentry/sentry-go/pull/1196) +- Use go1.24.0 by @giortzisg in [#1195](https://github.com/getsentry/sentry-go/pull/1195) +- Bump github.com/gofiber/fiber/v2 from 2.52.9 to 2.52.11 in /fiber by @dependabot in [#1191](https://github.com/getsentry/sentry-go/pull/1191) +- Bump getsentry/craft from 2.19.0 to 2.20.1 by @dependabot in [#1187](https://github.com/getsentry/sentry-go/pull/1187) + +#### Other + +- Add omitzero and remove custom serialization by @giortzisg in [#1197](https://github.com/getsentry/sentry-go/pull/1197) +- Rename Telemetry Processor components by @giortzisg in [#1186](https://github.com/getsentry/sentry-go/pull/1186) + +## 0.42.0 + +### Breaking Changes 🛠 + +- refactor Telemetry Processor to use TelemetryItem instead of ItemConvertible by @giortzisg in [#1180](https://github.com/getsentry/sentry-go/pull/1180) + - remove ToEnvelopeItem from single log items + - rename TelemetryBuffer to Telemetry Processor to adhere to spec + - remove unsed ToEnvelopeItem(dsn) from Event. + +### New Features ✨ + +- Add metric support by @aldy505 in [#1151](https://github.com/getsentry/sentry-go/pull/1151) + - support for three metric methods (counter, gauge, distribution) + - custom metric units + - unexport batchlogger + +### Internal Changes 🔧 + +#### Release + +- Fix changelog-preview permissions by @BYK in [#1181](https://github.com/getsentry/sentry-go/pull/1181) +- Switch from action-prepare-release to Craft by @BYK in [#1167](https://github.com/getsentry/sentry-go/pull/1167) + +#### Other + +- (repo) Add Claude Code settings with basic permissions by @philipphofmann in [#1175](https://github.com/getsentry/sentry-go/pull/1175) +- Update release and changelog-preview workflows by @giortzisg in [#1177](https://github.com/getsentry/sentry-go/pull/1177) +- Bump echo to 4.10.1 by @giortzisg in [#1174](https://github.com/getsentry/sentry-go/pull/1174) + +## 0.41.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.41.0. + +### Features + +- Add HTTP client integration for distributed tracing via `sentryhttpclient` package ([#876](https://github.com/getsentry/sentry-go/pull/876)) + - Provides an `http.RoundTripper` implementation that automatically creates spans for outgoing HTTP requests + - Supports trace propagation targets configuration via `WithTracePropagationTargets` option + - Example usage: + ```go + import sentryhttpclient "github.com/getsentry/sentry-go/httpclient" + + roundTripper := sentryhttpclient.NewSentryRoundTripper(nil) + client := &http.Client{ + Transport: roundTripper, + } + ``` +- Add `ClientOptions.PropagateTraceparent` option to control W3C `traceparent` header propagation in outgoing HTTP requests ([#1161](https://github.com/getsentry/sentry-go/pull/1161)) +- Add `SpanID` field to structured logs ([#1169](https://github.com/getsentry/sentry-go/pull/1169)) + +## 0.40.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.40.0. + +### Bug Fixes + +- Disable `DisableTelemetryBuffer` flag and noop Telemetry Buffer, to prevent a panic at runtime ([#1149](https://github.com/getsentry/sentry-go/pull/1149)). + +## 0.39.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.39.0. + +### Features + +- Drop events from the telemetry buffer when rate-limited or transport is full, allowing the buffer queue to empty itself under load ([#1138](https://github.com/getsentry/sentry-go/pull/1138)). + +### Bug Fixes + +- Fix scheduler's `hasWork()` method to check if buffers are ready to flush. The previous implementation was causing CPU spikes ([#1143](https://github.com/getsentry/sentry-go/pull/1143)). + +## 0.38.0 + +### Breaking Changes + +### Features + +- Introduce a new async envelope transport and telemetry buffer to prioritize and batch events ([#1094](https://github.com/getsentry/sentry-go/pull/1094), [#1093](https://github.com/getsentry/sentry-go/pull/1093), [#1107](https://github.com/getsentry/sentry-go/pull/1107)). + - Advantages: + - Prioritized, per-category buffers (errors, transactions, logs, check-ins) reduce starvation and improve resilience under load + - Batching for high-volume logs (up to 100 items or 5s) cuts network overhead + - Bounded memory with eviction policies + - Improved flush behavior with context-aware flushing +- Add `ClientOptions.DisableTelemetryBuffer` to opt out and fall back to the legacy transport layer (`HTTPTransport` / `HTTPSyncTransport`). + + ```go + err := sentry.Init(sentry.ClientOptions{ + Dsn: "__DSN__", + DisableTelemetryBuffer: true, // fallback to legacy transport + }) + ``` + +### Notes + +- If a custom `Transport` is provided, the SDK automatically disables the telemetry buffer and uses the legacy transport for compatibility. + +## 0.37.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.37.0. + +### Breaking Changes + +- Behavioral change for the `TraceIgnoreStatusCodes` option. The option now defaults to ignoring 404 status codes ([#1122](https://github.com/getsentry/sentry-go/pull/1122)). + +### Features + +- Add `sentry.origin` attribute to structured logs to identify log origin for `slog` and `logrus` integrations (`auto.log.slog`, `auto.log.logrus`) ([#1121](https://github.com/getsentry/sentry-go/pull/1121)). + +### Bug Fixes + +- Fix `slog` event handler to use the initial context, ensuring events use the correct hub/span when the emission context lacks one ([#1133](https://github.com/getsentry/sentry-go/pull/1133)). +- Improve exception chain processing by checking pointer values when tracking visited errors, avoiding instability for certain wrapped errors ([#1132](https://github.com/getsentry/sentry-go/pull/1132)). + +### Misc + +- Bump `golang.org/x/net` to v0.38.0 ([#1126](https://github.com/getsentry/sentry-go/pull/1126)). + +## 0.36.2 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.2. + +### Bug Fixes + +- Fix context propagation for logs to ensure logger instances correctly inherit span and hub information from their creation context ([#1118](https://github.com/getsentry/sentry-go/pull/1118)) + - Logs now properly propagate trace context from the logger's original context, even when emitted in a different context + - The logger will first check the emission context, then fall back to its creation context, and finally to the current hub + +## 0.36.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.1. + +### Bug Fixes + +- Prevent panic when converting error chains containing non-comparable error types by using a safe fallback for visited detection in exception conversion ([#1113](https://github.com/getsentry/sentry-go/pull/1113)) + +## 0.36.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.0. + +### Breaking Changes + +- Behavioral change for the `MaxBreadcrumbs` client option. Removed the hard limit of 100 breadcrumbs, allowing users to set a larger limit and also changed the default limit from 30 to 100 ([#1106](https://github.com/getsentry/sentry-go/pull/1106))) + +- The changes to error handling ([#1075](https://github.com/getsentry/sentry-go/pull/1075)) will affect issue grouping. It is expected that any wrapped and complex errors will be grouped under a new issue group. + +### Features + +- Add support for improved issue grouping with enhanced error chain handling ([#1075](https://github.com/getsentry/sentry-go/pull/1075)) + + The SDK now provides better handling of complex error scenarios, particularly when dealing with multiple related errors or error chains. This feature automatically detects and properly structures errors created with Go's `errors.Join()` function and other multi-error patterns. + + ```go + // Multiple errors are now properly grouped and displayed in Sentry + err1 := errors.New("err1") + err2 := errors.New("err2") + combinedErr := errors.Join(err1, err2) + + // When captured, these will be shown as related exceptions in Sentry + sentry.CaptureException(combinedErr) + ``` + +- Add `TraceIgnoreStatusCodes` option to allow filtering of HTTP transactions based on status codes ([#1089](https://github.com/getsentry/sentry-go/pull/1089)) + - Configure which HTTP status codes should not be traced by providing single codes or ranges + - Example: `TraceIgnoreStatusCodes: [][]int{{404}, {500, 599}}` ignores 404 and server errors 500-599 + +### Bug Fixes + +- Fix logs being incorrectly filtered by `BeforeSend` callback ([#1109](https://github.com/getsentry/sentry-go/pull/1109)) + - Logs now bypass the `processEvent` method and are sent directly to the transport + - This ensures logs are only filtered by `BeforeSendLog`, not by the error/message `BeforeSend` callback + +### Misc + +- Add support for Go 1.25 and drop support for Go 1.22 ([#1103](https://github.com/getsentry/sentry-go/pull/1103)) + +## 0.35.3 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.3. + +### Bug Fixes + +- Add missing rate limit categories ([#1082](https://github.com/getsentry/sentry-go/pull/1082)) + +## 0.35.2 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.2. + +### Bug Fixes + +- Fix OpenTelemetry spans being created as transactions instead of child spans ([#1073](https://github.com/getsentry/sentry-go/pull/1073)) + +### Misc + +- Add `MockTransport` to test clients for improved testing ([#1071](https://github.com/getsentry/sentry-go/pull/1071)) + +## 0.35.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.1. + +### Bug Fixes + +- Fix race conditions when accessing the scope during logging operations ([#1050](https://github.com/getsentry/sentry-go/pull/1050)) +- Fix nil pointer dereference with malformed URLs when tracing is enabled in `fasthttp` and `fiber` integrations ([#1055](https://github.com/getsentry/sentry-go/pull/1055)) + +### Misc + +- Bump `github.com/gofiber/fiber/v2` from 2.52.5 to 2.52.9 in `/fiber` ([#1067](https://github.com/getsentry/sentry-go/pull/1067)) + +## 0.35.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.0. + +### Breaking Changes + +- Changes to the logging API ([#1046](https://github.com/getsentry/sentry-go/pull/1046)) + +The logging API now supports a fluent interface for structured logging with attributes: + +```go +// usage before +logger := sentry.NewLogger(ctx) +// attributes weren't being set permanently +logger.SetAttributes( + attribute.String("version", "1.0.0"), +) +logger.Infof(ctx, "Message with parameters %d and %d", 1, 2) + +// new behavior +ctx := context.Background() +logger := sentry.NewLogger(ctx) + +// Set permanent attributes on the logger +logger.SetAttributes( + attribute.String("version", "1.0.0"), +) + +// Chain attributes on individual log entries +logger.Info(). + String("key.string", "value"). + Int("key.int", 42). + Bool("key.bool", true). + Emitf("Message with parameters %d and %d", 1, 2) +``` + +### Bug Fixes + +- Correctly serialize `FailureIssueThreshold` and `RecoveryThreshold` onto check-in payloads ([#1060](https://github.com/getsentry/sentry-go/pull/1060)) + +## 0.34.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.34.1. + +### Bug Fixes + +- Allow flush to be used multiple times without issues, particularly for the batch logger ([#1051](https://github.com/getsentry/sentry-go/pull/1051)) +- Fix race condition in `Scope.GetSpan()` method by adding proper mutex locking ([#1044](https://github.com/getsentry/sentry-go/pull/1044)) +- Guard transport on `Close()` to prevent panic when called multiple times ([#1044](https://github.com/getsentry/sentry-go/pull/1044)) + +## 0.34.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.34.0. + +### Breaking Changes + +- Logrus structured logging support replaces the `sentrylogrus.Hook` signature from a `*Hook` to an interface. + +```go +var hook *sentrylogrus.Hook +hook = sentrylogrus.New( + // ... your setup +) + +// should change the definition to +var hook sentrylogrus.Hook +hook = sentrylogrus.New( + // ... your setup +) +``` + +### Features + +- Structured logging support for [slog](https://pkg.go.dev/log/slog). ([#1033](https://github.com/getsentry/sentry-go/pull/1033)) + +```go +ctx := context.Background() +handler := sentryslog.Option{ + EventLevel: []slog.Level{slog.LevelError, sentryslog.LevelFatal}, // Only Error and Fatal as events + LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Only Warn and Info as logs +}.NewSentryHandler(ctx) +logger := slog.New(handler) +logger.Info("hello")) +``` + +- Structured logging support for [logrus](https://github.com/sirupsen/logrus). ([#1036](https://github.com/getsentry/sentry-go/pull/1036)) +```go +logHook, _ := sentrylogrus.NewLogHook( + []logrus.Level{logrus.InfoLevel, logrus.WarnLevel}, + sentry.ClientOptions{ + Dsn: "your-dsn", + EnableLogs: true, // Required for log entries + }) +defer logHook.Flush(5 * time.Secod) +logrus.RegisterExitHandler(func() { + logHook.Flush(5 * time.Second) +}) + +logger := logrus.New() +logger.AddHook(logHook) +logger.Infof("hello") +``` + +- Add support for flushing events with context using `FlushWithContext()`. ([#935](https://github.com/getsentry/sentry-go/pull/935)) + +```go +ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) +defer cancel() + +if !sentry.FlushWithContext(ctx) { + // Handle timeout or cancellation +} +``` + +- Add support for custom fingerprints in slog integration. ([#1039](https://github.com/getsentry/sentry-go/pull/1039)) + +### Deprecations + +- Slog structured logging support replaces `Level` option with `EventLevel` and `LogLevel` options, for specifying fine-grained levels for capturing events and logs. + +```go +handler := sentryslog.Option{ + EventLevel: []slog.Level{slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal}, + LogLevel: []slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal}, +}.NewSentryHandler(ctx) +``` + +- Logrus structured logging support replaces `New` and `NewFromClient` functions to `NewEventHook`, `NewEventHookFromClient`, to match the newly added `NewLogHook` functions, and specify the hook type being created each time. + +```go +logHook, err := sentrylogrus.NewLogHook( + []logrus.Level{logrus.InfoLevel}, + sentry.ClientOptions{}) +eventHook, err := sentrylogrus.NewEventHook([]logrus.Level{ + logrus.ErrorLevel, + logrus.FatalLevel, + logrus.PanicLevel, +}, sentry.ClientOptions{}) +``` + +### Bug Fixes + +- Fix issue where `ContinueTrace()` would panic when `sentry-trace` header does not exist. ([#1026](https://github.com/getsentry/sentry-go/pull/1026)) +- Fix incorrect log level signature in structured logging. ([#1034](https://github.com/getsentry/sentry-go/pull/1034)) +- Remove `sentry.origin` attribute from Sentry logger to prevent confusion in spans. ([#1038](https://github.com/getsentry/sentry-go/pull/1038)) +- Don't gate user information behind `SendDefaultPII` flag for logs. ([#1032](https://github.com/getsentry/sentry-go/pull/1032)) + +### Misc + +- Add more sensitive HTTP headers to the default list of headers that are scrubbed by default. ([#1008](https://github.com/getsentry/sentry-go/pull/1008)) + +## 0.33.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.33.0. + + +### Breaking Changes + +- Rename the internal `Logger` to `DebugLogger`. This feature was only used when you set `Debug: True` in your `sentry.Init()` call. If you haven't used the Logger directly, no changes are necessary. ([#1012](https://github.com/getsentry/sentry-go/issues/1012)) + +### Features + +- Add support for [Structured Logging](https://docs.sentry.io/product/explore/logs/). ([#1010](https://github.com/getsentry/sentry-go/issues/1010)) + + ```go + logger := sentry.NewLogger(ctx) + logger.Info(ctx, "Hello, Logs!") + ``` + + You can learn more about Sentry Logs on our [docs](https://docs.sentry.io/product/explore/logs/) and the [examples](https://github.com/getsentry/sentry-go/blob/master/_examples/logs/main.go). + +- Add new attributes APIs, which are currently only exposed on logs. ([#1007](https://github.com/getsentry/sentry-go/issues/1007)) + +### Bug Fixes + +- Do not push a new scope on `StartSpan`. ([#1013](https://github.com/getsentry/sentry-go/issues/1013)) +- Fix an issue where the propagated smapling decision wasn't used. ([#995](https://github.com/getsentry/sentry-go/issues/995)) +- [Otel] Prefer `httpRoute` over `httpTarget` for span descriptions. ([#1002](https://github.com/getsentry/sentry-go/issues/1002)) + +### Misc + +- Update `github.com/stretchr/testify` to v1.8.4. ([#988](https://github.com/getsentry/sentry-go/issues/988)) + +## 0.32.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.32.0. + +### Breaking Changes + +- Bump the minimum Go version to 1.22. The supported versions are 1.22, 1.23 and 1.24. ([#967](https://github.com/getsentry/sentry-go/issues/967)) +- Setting any values on `span.Extra` has no effect anymore. Use `SetData(name string, value interface{})` instead. ([#864](https://github.com/getsentry/sentry-go/pull/864)) + +### Features + +- Add a `MockTransport` and `MockScope`. ([#972](https://github.com/getsentry/sentry-go/pull/972)) + +### Bug Fixes + +- Fix writing `*http.Request` in the Logrus JSONFormatter. ([#955](https://github.com/getsentry/sentry-go/issues/955)) + +### Misc + +- Transaction `data` attributes are now seralized as trace context data attributes, allowing you to query these attributes in the [Trace Explorer](https://docs.sentry.io/product/explore/traces/). + +## 0.31.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.1. + +### Bug Fixes + +- Correct wrong module name for `sentry-go/logrus` ([#950](https://github.com/getsentry/sentry-go/pull/950)) + +## 0.31.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.0. + +### Breaking Changes + +- Remove support for metrics. Read more about the end of the Metrics beta [here](https://sentry.zendesk.com/hc/en-us/articles/26369339769883-Metrics-Beta-Ended-on-October-7th). ([#914](https://github.com/getsentry/sentry-go/pull/914)) + +- Remove support for profiling. ([#915](https://github.com/getsentry/sentry-go/pull/915)) + +- Remove `Segment` field from the `User` struct. This field is no longer used in the Sentry product. ([#928](https://github.com/getsentry/sentry-go/pull/928)) + +- Every integration is now a separate module, reducing the binary size and number of dependencies. Once you update `sentry-go` to latest version, you'll need to `go get` the integration you want to use. For example, if you want to use the `echo` integration, you'll need to run `go get github.com/getsentry/sentry-go/echo` ([#919](github.com/getsentry/sentry-go/pull/919)). + +### Features + +Add the ability to override `hub` in `context` for integrations that use custom context. ([#931](https://github.com/getsentry/sentry-go/pull/931)) + +- Add `HubProvider` Hook for `sentrylogrus`, enabling dynamic Sentry hub allocation for each log entry or goroutine. ([#936](https://github.com/getsentry/sentry-go/pull/936)) + +This change enhances compatibility with Sentry's recommendation of using separate hubs per goroutine. To ensure a separate Sentry hub for each goroutine, configure the `HubProvider` like this: + +```go +hook, err := sentrylogrus.New(nil, sentry.ClientOptions{}) +if err != nil { + log.Fatalf("Failed to initialize Sentry hook: %v", err) +} + +// Set a custom HubProvider to generate a new hub for each goroutine or log entry +hook.SetHubProvider(func() *sentry.Hub { + client, _ := sentry.NewClient(sentry.ClientOptions{}) + return sentry.NewHub(client, sentry.NewScope()) +}) + +logrus.AddHook(hook) +``` + +### Bug Fixes + +- Add support for closing worker goroutines started by the `HTTPTranport` to prevent goroutine leaks. ([#894](https://github.com/getsentry/sentry-go/pull/894)) + +```go +client, _ := sentry.NewClient() +defer client.Close() +``` + +Worker can be also closed by calling `Close()` method on the `HTTPTransport` instance. `Close` should be called after `Flush` and before terminating the program otherwise some events may be lost. + +```go +transport := sentry.NewHTTPTransport() +defer transport.Close() +``` + +### Misc + +- Bump [gin-gonic/gin](https://github.com/gin-gonic/gin) to v1.9.1. ([#946](https://github.com/getsentry/sentry-go/pull/946)) + +## 0.30.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.30.0. + +### Features + +- Add `sentryzerolog` integration ([#857](https://github.com/getsentry/sentry-go/pull/857)) +- Add `sentryslog` integration ([#865](https://github.com/getsentry/sentry-go/pull/865)) +- Always set Mechanism Type to generic ([#896](https://github.com/getsentry/sentry-go/pull/897)) + +### Bug Fixes + +- Prevent panic in `fasthttp` and `fiber` integration in case a malformed URL has to be parsed ([#912](https://github.com/getsentry/sentry-go/pull/912)) + +### Misc + +Drop support for Go 1.18, 1.19 and 1.20. The currently supported Go versions are the last 3 stable releases: 1.23, 1.22 and 1.21. + +## 0.29.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.1. + +### Bug Fixes + +- Correlate errors to the current trace ([#886](https://github.com/getsentry/sentry-go/pull/886)) +- Set the trace context when the transaction finishes ([#888](https://github.com/getsentry/sentry-go/pull/888)) + +### Misc + +- Update the `sentrynegroni` integration to use the latest (v3.1.1) version of Negroni ([#885](https://github.com/getsentry/sentry-go/pull/885)) + +## 0.29.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.0. + +### Breaking Changes + +- Remove the `sentrymartini` integration ([#861](https://github.com/getsentry/sentry-go/pull/861)) +- The `WrapResponseWriter` has been moved from the `sentryhttp` package to the `internal/httputils` package. If you've imported it previosuly, you'll need to copy the implementation in your project. ([#871](https://github.com/getsentry/sentry-go/pull/871)) + +### Features + +- Add new convenience methods to continue a trace and propagate tracing headers for error-only use cases. ([#862](https://github.com/getsentry/sentry-go/pull/862)) + + If you are not using one of our integrations, you can manually continue an incoming trace by using `sentry.ContinueTrace()` by providing the `sentry-trace` and `baggage` header received from a downstream SDK. + + ```go + hub := sentry.CurrentHub() + sentry.ContinueTrace(hub, r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)), + ``` + + You can use `hub.GetTraceparent()` and `hub.GetBaggage()` to fetch the necessary header values for outgoing HTTP requests. + + ```go + hub := sentry.GetHubFromContext(ctx) + req, _ := http.NewRequest("GET", "http://localhost:3000", nil) + req.Header.Add(sentry.SentryTraceHeader, hub.GetTraceparent()) + req.Header.Add(sentry.SentryBaggageHeader, hub.GetBaggage()) + ``` + +### Bug Fixes + +- Initialize `HTTPTransport.limit` if `nil` ([#844](https://github.com/getsentry/sentry-go/pull/844)) +- Fix `sentry.StartTransaction()` returning a transaction with an outdated context on existing transactions ([#854](https://github.com/getsentry/sentry-go/pull/854)) +- Treat `Proxy-Authorization` as a sensitive header ([#859](https://github.com/getsentry/sentry-go/pull/859)) +- Add support for the `http.Hijacker` interface to the `sentrynegroni` package ([#871](https://github.com/getsentry/sentry-go/pull/871)) +- Go version >= 1.23: Use value from `http.Request.Pattern` for HTTP transaction names when using `sentryhttp` & `sentrynegroni` ([#875](https://github.com/getsentry/sentry-go/pull/875)) +- Go version >= 1.21: Fix closure functions name grouping ([#877](https://github.com/getsentry/sentry-go/pull/877)) + +### Misc + +- Collect `span` origins ([#849](https://github.com/getsentry/sentry-go/pull/849)) + +## 0.28.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.1. + +### Bug Fixes + +- Implement `http.ResponseWriter` to hook into various parts of the response process ([#837](https://github.com/getsentry/sentry-go/pull/837)) + +## 0.28.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.0. + +### Features + +- Add a `Fiber` performance tracing & error reporting integration ([#795](https://github.com/getsentry/sentry-go/pull/795)) +- Add performance tracing to the `Echo` integration ([#722](https://github.com/getsentry/sentry-go/pull/722)) +- Add performance tracing to the `FastHTTP` integration ([#732](https://github.com/getsentry/sentry-go/pull/723)) +- Add performance tracing to the `Iris` integration ([#809](https://github.com/getsentry/sentry-go/pull/809)) +- Add performance tracing to the `Negroni` integration ([#808](https://github.com/getsentry/sentry-go/pull/808)) +- Add `FailureIssueThreshold` & `RecoveryThreshold` to `MonitorConfig` ([#775](https://github.com/getsentry/sentry-go/pull/775)) +- Use `errors.Unwrap()` to create exception groups ([#792](https://github.com/getsentry/sentry-go/pull/792)) +- Add support for matching on strings for `ClientOptions.IgnoreErrors` & `ClientOptions.IgnoreTransactions` ([#819](https://github.com/getsentry/sentry-go/pull/819)) +- Add `http.request.method` attribute for performance span data ([#786](https://github.com/getsentry/sentry-go/pull/786)) +- Accept `interface{}` for span data values ([#784](https://github.com/getsentry/sentry-go/pull/784)) + +### Bug Fixes + +- Fix missing stack trace for parsing error in `logrusentry` ([#689](https://github.com/getsentry/sentry-go/pull/689)) + +## 0.27.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.27.0. + +### Breaking Changes + +- `Exception.ThreadId` is now typed as `uint64`. It was wrongly typed as `string` before. ([#770](https://github.com/getsentry/sentry-go/pull/770)) + +### Misc + +- Export `Event.Attachments` ([#771](https://github.com/getsentry/sentry-go/pull/771)) + +## 0.26.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.26.0. + +### Breaking Changes + +As previously announced, this release removes some methods from the SDK. + +- `sentry.TransactionName()` use `sentry.WithTransactionName()` instead. +- `sentry.OpName()` use `sentry.WithOpName()` instead. +- `sentry.TransctionSource()` use `sentry.WithTransactionSource()` instead. +- `sentry.SpanSampled()` use `sentry.WithSpanSampled()` instead. + +### Features + +- Add `WithDescription` span option ([#751](https://github.com/getsentry/sentry-go/pull/751)) + + ```go + span := sentry.StartSpan(ctx, "http.client", WithDescription("GET /api/users")) + ``` +- Add support for package name parsing in Go 1.20 and higher ([#730](https://github.com/getsentry/sentry-go/pull/730)) + +### Bug Fixes + +- Apply `ClientOptions.SampleRate` only to errors & messages ([#754](https://github.com/getsentry/sentry-go/pull/754)) +- Check if git is available before executing any git commands ([#737](https://github.com/getsentry/sentry-go/pull/737)) + +## 0.25.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.25.0. + +### Breaking Changes + +As previously announced, this release removes two global constants from the SDK. + +- `sentry.Version` was removed. Use `sentry.SDKVersion` instead ([#727](https://github.com/getsentry/sentry-go/pull/727)) +- `sentry.SDKIdentifier` was removed. Use `Client.GetSDKIdentifier()` instead ([#727](https://github.com/getsentry/sentry-go/pull/727)) + +### Features + +- Add `ClientOptions.IgnoreTransactions`, which allows you to ignore specific transactions based on their name ([#717](https://github.com/getsentry/sentry-go/pull/717)) +- Add `ClientOptions.Tags`, which allows you to set global tags that are applied to all events. You can also define tags by setting `SENTRY_TAGS_` environment variables ([#718](https://github.com/getsentry/sentry-go/pull/718)) + +### Bug fixes + +- Fix an issue in the profiler that would cause an infinite loop if the duration of a transaction is longer than 30 seconds ([#724](https://github.com/getsentry/sentry-go/issues/724)) + +### Misc + +- `dsn.RequestHeaders()` is not to be removed, though it is still considered deprecated and should only be used when using a custom transport that sends events to the `/store` endpoint ([#720](https://github.com/getsentry/sentry-go/pull/720)) + +## 0.24.1 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.24.1. + +### Bug fixes + +- Prevent a panic in `sentryotel.flushSpanProcessor()` ([(#711)](https://github.com/getsentry/sentry-go/pull/711)) +- Prevent a panic when setting the SDK identifier ([#715](https://github.com/getsentry/sentry-go/pull/715)) + +## 0.24.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.24.0. + +### Deprecations + +- `sentry.Version` to be removed in 0.25.0. Use `sentry.SDKVersion` instead. +- `sentry.SDKIdentifier` to be removed in 0.25.0. Use `Client.GetSDKIdentifier()` instead. +- `dsn.RequestHeaders()` to be removed after 0.25.0, but no earlier than December 1, 2023. Requests to the `/envelope` endpoint are authenticated using the DSN in the envelope header. + +### Features + +- Run a single instance of the profiler instead of multiple ones for each Go routine ([#655](https://github.com/getsentry/sentry-go/pull/655)) +- Use the route path as the transaction names when using the Gin integration ([#675](https://github.com/getsentry/sentry-go/pull/675)) +- Set the SDK name accordingly when a framework integration is used ([#694](https://github.com/getsentry/sentry-go/pull/694)) +- Read release information (VCS revision) from `debug.ReadBuildInfo` ([#704](https://github.com/getsentry/sentry-go/pull/704)) + +### Bug fixes + +- [otel] Fix incorrect usage of `attributes.Value.AsString` ([#684](https://github.com/getsentry/sentry-go/pull/684)) +- Fix trace function name parsing in profiler on go1.21+ ([#695](https://github.com/getsentry/sentry-go/pull/695)) + +### Misc + +- Test against Go 1.21 ([#695](https://github.com/getsentry/sentry-go/pull/695)) +- Make tests more robust ([#698](https://github.com/getsentry/sentry-go/pull/698), [#699](https://github.com/getsentry/sentry-go/pull/699), [#700](https://github.com/getsentry/sentry-go/pull/700), [#702](https://github.com/getsentry/sentry-go/pull/702)) + +## 0.23.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.23.0. + +### Features + +- Initial support for [Cron Monitoring](https://docs.sentry.io/product/crons/) ([#661](https://github.com/getsentry/sentry-go/pull/661)) + + This is how the basic usage of the feature looks like: + + ```go + // 🟡 Notify Sentry your job is running: + checkinId := sentry.CaptureCheckIn( + &sentry.CheckIn{ + MonitorSlug: "", + Status: sentry.CheckInStatusInProgress, + }, + nil, + ) + + // Execute your scheduled task here... + + // 🟢 Notify Sentry your job has completed successfully: + sentry.CaptureCheckIn( + &sentry.CheckIn{ + ID: *checkinId, + MonitorSlug: "", + Status: sentry.CheckInStatusOK, + }, + nil, + ) + ``` + + A full example of using Crons Monitoring is available [here](https://github.com/getsentry/sentry-go/blob/dde4d360660838f3c2e0ced8205bc8f7a8d312d9/_examples/crons/main.go). + + More documentation on configuring and using Crons [can be found here](https://docs.sentry.io/platforms/go/crons/). + +- Add support for [Event Attachments](https://docs.sentry.io/platforms/go/enriching-events/attachments/) ([#670](https://github.com/getsentry/sentry-go/pull/670)) + + It's now possible to add file/binary payloads to Sentry events: + + ```go + sentry.ConfigureScope(func(scope *sentry.Scope) { + scope.AddAttachment(&Attachment{ + Filename: "report.html", + ContentType: "text/html", + Payload: []byte("

Look, HTML

"), + }) + }) + ``` + + The attachment will then be accessible on the Issue Details page. + +- Add sampling decision to trace envelope header ([#666](https://github.com/getsentry/sentry-go/pull/666)) +- Expose SpanFromContext function ([#672](https://github.com/getsentry/sentry-go/pull/672)) + +### Bug fixes + +- Make `Span.Finish` a no-op when the span is already finished ([#660](https://github.com/getsentry/sentry-go/pull/660)) + +## 0.22.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.22.0. + +This release contains initial [profiling](https://docs.sentry.io/product/profiling/) support, as well as a few bug fixes and improvements. + +### Features + +- Initial (alpha) support for [profiling](https://docs.sentry.io/product/profiling/) ([#626](https://github.com/getsentry/sentry-go/pull/626)) + + Profiling is disabled by default. To enable it, configure both `TracesSampleRate` and `ProfilesSampleRate` when initializing the SDK: + + ```go + err := sentry.Init(sentry.ClientOptions{ + Dsn: "__DSN__", + EnableTracing: true, + TracesSampleRate: 1.0, + // The sampling rate for profiling is relative to TracesSampleRate. In this case, we'll capture profiles for 100% of transactions. + ProfilesSampleRate: 1.0, + }) + ``` + + More documentation on profiling and current limitations [can be found here](https://docs.sentry.io/platforms/go/profiling/). + +- Add transactions/tracing support go the Gin integration ([#644](https://github.com/getsentry/sentry-go/pull/644)) + +### Bug fixes + +- Always set a valid source on transactions ([#637](https://github.com/getsentry/sentry-go/pull/637)) +- Clone scope.Context in more places to avoid panics on concurrent reads and writes ([#638](https://github.com/getsentry/sentry-go/pull/638)) + - Fixes [#570](https://github.com/getsentry/sentry-go/issues/570) +- Fix frames recognized as not being in-app still showing as in-app ([#647](https://github.com/getsentry/sentry-go/pull/647)) + +## 0.21.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.21.0. + +Note: this release includes one **breaking change** and some **deprecations**, which are listed below. + +### Breaking Changes + +**This change does not apply if you use [https://sentry.io](https://sentry.io)** + +- Remove support for the `/store` endpoint ([#631](https://github.com/getsentry/sentry-go/pull/631)) + - This change requires a self-hosted version of Sentry 20.6.0 or higher. If you are using a version of [self-hosted Sentry](https://develop.sentry.dev/self-hosted/) (aka *on-premise*) older than 20.6.0, then you will need to [upgrade](https://develop.sentry.dev/self-hosted/releases/) your instance. + +### Features + +- Rename four span option functions ([#611](https://github.com/getsentry/sentry-go/pull/611), [#624](https://github.com/getsentry/sentry-go/pull/624)) + - `TransctionSource` -> `WithTransactionSource` + - `SpanSampled` -> `WithSpanSampled` + - `OpName` -> `WithOpName` + - `TransactionName` -> `WithTransactionName` + - Old functions `TransctionSource`, `SpanSampled`, `OpName`, and `TransactionName` are still available but are now **deprecated** and will be removed in a future release. +- Make `client.EventFromMessage` and `client.EventFromException` methods public ([#607](https://github.com/getsentry/sentry-go/pull/607)) +- Add `client.SetException` method ([#607](https://github.com/getsentry/sentry-go/pull/607)) + - This allows to set or add errors to an existing `Event`. + +### Bug Fixes + +- Protect from panics while doing concurrent reads/writes to Span data fields ([#609](https://github.com/getsentry/sentry-go/pull/609)) +- [otel] Improve detection of Sentry-related spans ([#632](https://github.com/getsentry/sentry-go/pull/632), [#636](https://github.com/getsentry/sentry-go/pull/636)) + - Fixes cases when HTTP spans containing requests to Sentry were captured by Sentry ([#627](https://github.com/getsentry/sentry-go/issues/627)) + +### Misc + +- Drop testing in (legacy) GOPATH mode ([#618](https://github.com/getsentry/sentry-go/pull/618)) +- Remove outdated documentation from https://pkg.go.dev/github.com/getsentry/sentry-go ([#623](https://github.com/getsentry/sentry-go/pull/623)) + +## 0.20.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.20.0. + +Note: this release has some **breaking changes**, which are listed below. + +### Breaking Changes + +- Remove the following methods: `Scope.SetTransaction()`, `Scope.Transaction()` ([#605](https://github.com/getsentry/sentry-go/pull/605)) + + Span.Name should be used instead to access the transaction's name. + + For example, the following [`TracesSampler`](https://docs.sentry.io/platforms/go/configuration/sampling/#setting-a-sampling-function) function should be now written as follows: + + **Before:** + ```go + TracesSampler: func(ctx sentry.SamplingContext) float64 { + hub := sentry.GetHubFromContext(ctx.Span.Context()) + if hub.Scope().Transaction() == "GET /health" { + return 0 + } + return 1 + }, + ``` + + **After:** + ```go + TracesSampler: func(ctx sentry.SamplingContext) float64 { + if ctx.Span.Name == "GET /health" { + return 0 + } + return 1 + }, + ``` + +### Features + +- Add `Span.SetContext()` method ([#599](https://github.com/getsentry/sentry-go/pull/599/)) + - It is recommended to use it instead of `hub.Scope().SetContext` when setting or updating context on transactions. +- Add `DebugMeta` interface to `Event` and extend `Frame` structure with more fields ([#606](https://github.com/getsentry/sentry-go/pull/606)) + - More about DebugMeta interface [here](https://develop.sentry.dev/sdk/event-payloads/debugmeta/). + +### Bug Fixes + +- [otel] Fix missing OpenTelemetry context on some events ([#599](https://github.com/getsentry/sentry-go/pull/599), [#605](https://github.com/getsentry/sentry-go/pull/605)) + - Fixes ([#596](https://github.com/getsentry/sentry-go/issues/596)). +- [otel] Better handling for HTTP span attributes ([#610](https://github.com/getsentry/sentry-go/pull/610)) + +### Misc + +- Bump minimum versions: `github.com/kataras/iris/v12` to 12.2.0, `github.com/labstack/echo/v4` to v4.10.0 ([#595](https://github.com/getsentry/sentry-go/pull/595)) + - Resolves [GO-2022-1144 / CVE-2022-41717](https://deps.dev/advisory/osv/GO-2022-1144), [GO-2023-1495 / CVE-2022-41721](https://deps.dev/advisory/osv/GO-2023-1495), [GO-2022-1059 / CVE-2022-32149](https://deps.dev/advisory/osv/GO-2022-1059). +- Bump `google.golang.org/protobuf` minimum required version to 1.29.1 ([#604](https://github.com/getsentry/sentry-go/pull/604)) + - This fixes a potential denial of service issue ([CVE-2023-24535](https://github.com/advisories/GHSA-hw7c-3rfg-p46j)). +- Exclude the `otel` module when building in GOPATH mode ([#615](https://github.com/getsentry/sentry-go/pull/615)) + +## 0.19.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.19.0. + +### Features + +- Add support for exception mechanism metadata ([#564](https://github.com/getsentry/sentry-go/pull/564/)) + - More about exception mechanisms [here](https://develop.sentry.dev/sdk/event-payloads/exception/#exception-mechanism). + +### Bug Fixes +- [otel] Use the correct "trace" context when sending a Sentry error ([#580](https://github.com/getsentry/sentry-go/pull/580/)) + + +### Misc +- Drop support for Go 1.17, add support for Go 1.20 ([#563](https://github.com/getsentry/sentry-go/pull/563/)) + - According to our policy, we're officially supporting the last three minor releases of Go. +- Switch repository license to MIT ([#583](https://github.com/getsentry/sentry-go/pull/583/)) + - More about Sentry licensing [here](https://open.sentry.io/licensing/). +- Bump `golang.org/x/text` minimum required version to 0.3.8 ([#586](https://github.com/getsentry/sentry-go/pull/586)) + - This fixes [CVE-2022-32149](https://github.com/advisories/GHSA-69ch-w2m2-3vjp) vulnerability. + +## 0.18.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.18.0. +This release contains initial support for [OpenTelemetry](https://opentelemetry.io/) and various other bug fixes and improvements. + +**Note**: This is the last release supporting Go 1.17. + +### Features + +- Initial support for [OpenTelemetry](https://opentelemetry.io/). + You can now send all your OpenTelemetry spans to Sentry. + + Install the `otel` module + + ```bash + go get github.com/getsentry/sentry-go \ + github.com/getsentry/sentry-go/otel + ``` + + Configure the Sentry and OpenTelemetry SDKs + + ```go + import ( + "go.opentelemetry.io/otel" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "github.com/getsentry/sentry-go" + "github.com/getsentry/sentry-go/otel" + // ... + ) + + // Initlaize the Sentry SDK + sentry.Init(sentry.ClientOptions{ + Dsn: "__DSN__", + EnableTracing: true, + TracesSampleRate: 1.0, + }) + + // Set up the Sentry span processor + tp := sdktrace.NewTracerProvider( + sdktrace.WithSpanProcessor(sentryotel.NewSentrySpanProcessor()), + // ... + ) + otel.SetTracerProvider(tp) + + // Set up the Sentry propagator + otel.SetTextMapPropagator(sentryotel.NewSentryPropagator()) + ``` + + You can read more about using OpenTelemetry with Sentry in our [docs](https://docs.sentry.io/platforms/go/performance/instrumentation/opentelemetry/). + +### Bug Fixes + +- Do not freeze the Dynamic Sampling Context when no Sentry values are present in the baggage header ([#532](https://github.com/getsentry/sentry-go/pull/532)) +- Create a frozen Dynamic Sampling Context when calling `span.ToBaggage()` ([#566](https://github.com/getsentry/sentry-go/pull/566)) +- Fix baggage parsing and encoding in vendored otel package ([#568](https://github.com/getsentry/sentry-go/pull/568)) + +### Misc + +- Add `Span.SetDynamicSamplingContext()` ([#539](https://github.com/getsentry/sentry-go/pull/539/)) +- Add various getters for `Dsn` ([#540](https://github.com/getsentry/sentry-go/pull/540)) +- Add `SpanOption::SpanSampled` ([#546](https://github.com/getsentry/sentry-go/pull/546)) +- Add `Span.SetData()` ([#542](https://github.com/getsentry/sentry-go/pull/542)) +- Add `Span.IsTransaction()` ([#543](https://github.com/getsentry/sentry-go/pull/543)) +- Add `Span.GetTransaction()` method ([#558](https://github.com/getsentry/sentry-go/pull/558)) + +## 0.17.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.17.0. +This release contains a new `BeforeSendTransaction` hook option and corrects two regressions introduced in `0.16.0`. + +### Features + +- Add `BeforeSendTransaction` hook to `ClientOptions` ([#517](https://github.com/getsentry/sentry-go/pull/517)) + - Here's [an example](https://github.com/getsentry/sentry-go/blob/master/_examples/http/main.go#L56-L66) of how BeforeSendTransaction can be used to modify or drop transaction events. + +### Bug Fixes + +- Do not crash in Span.Finish() when the Client is empty [#520](https://github.com/getsentry/sentry-go/pull/520) + - Fixes [#518](https://github.com/getsentry/sentry-go/issues/518) +- Attach non-PII/non-sensitive request headers to events when `ClientOptions.SendDefaultPii` is set to `false` ([#524](https://github.com/getsentry/sentry-go/pull/524)) + - Fixes [#523](https://github.com/getsentry/sentry-go/issues/523) + +### Misc + +- Clarify how to handle logrus.Fatalf events ([#501](https://github.com/getsentry/sentry-go/pull/501/)) +- Rename the `examples` directory to `_examples` ([#521](https://github.com/getsentry/sentry-go/pull/521)) + - This removes an indirect dependency to `github.com/golang-jwt/jwt` + +## 0.16.0 + +The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.16.0. +Due to ongoing work towards a stable API for `v1.0.0`, we sadly had to include **two breaking changes** in this release. + +### Breaking Changes + +- Add `EnableTracing`, a boolean option flag to enable performance monitoring (`false` by default). + - If you're using `TracesSampleRate` or `TracesSampler`, this option is **required** to enable performance monitoring. + + ```go + sentry.Init(sentry.ClientOptions{ + EnableTracing: true, + TracesSampleRate: 1.0, + }) + ``` +- Unify TracesSampler [#498](https://github.com/getsentry/sentry-go/pull/498) + - `TracesSampler` was changed to a callback that must return a `float64` between `0.0` and `1.0`. + + For example, you can apply a sample rate of `1.0` (100%) to all `/api` transactions, and a sample rate of `0.5` (50%) to all other transactions. + You can read more about this in our [SDK docs](https://docs.sentry.io/platforms/go/configuration/filtering/#using-sampling-to-filter-transaction-events). + + ```go + sentry.Init(sentry.ClientOptions{ + TracesSampler: sentry.TracesSampler(func(ctx sentry.SamplingContext) float64 { + hub := sentry.GetHubFromContext(ctx.Span.Context()) + name := hub.Scope().Transaction() + + if strings.HasPrefix(name, "GET /api") { + return 1.0 + } + + return 0.5 + }), + } + ``` + +### Features + +- Send errors logged with [Logrus](https://github.com/sirupsen/logrus) to Sentry. + - Have a look at our [logrus examples](https://github.com/getsentry/sentry-go/blob/master/_examples/logrus/main.go) on how to use the integration. +- Add support for Dynamic Sampling [#491](https://github.com/getsentry/sentry-go/pull/491) + - You can read more about Dynamic Sampling in our [product docs](https://docs.sentry.io/product/data-management-settings/dynamic-sampling/). +- Add detailed logging about the reason transactions are being dropped. + - You can enable SDK logging via `sentry.ClientOptions.Debug: true`. + +### Bug Fixes + +- Do not clone the hub when calling `StartTransaction` [#505](https://github.com/getsentry/sentry-go/pull/505) + - Fixes [#502](https://github.com/getsentry/sentry-go/issues/502) + +## 0.15.0 + +- fix: Scope values should not override Event values (#446) +- feat: Make maximum amount of spans configurable (#460) +- feat: Add a method to start a transaction (#482) +- feat: Extend User interface by adding Data, Name and Segment (#483) +- feat: Add ClientOptions.SendDefaultPII (#485) + +## 0.14.0 + +- feat: Add function to continue from trace string (#434) +- feat: Add `max-depth` options (#428) +- *[breaking]* ref: Use a `Context` type mapping to a `map[string]interface{}` for all event contexts (#444) +- *[breaking]* ref: Replace deprecated `ioutil` pkg with `os` & `io` (#454) +- ref: Optimize `stacktrace.go` from size and speed (#467) +- ci: Test against `go1.19` and `go1.18`, drop `go1.16` and `go1.15` support (#432, #477) +- deps: Dependency update to fix CVEs (#462, #464, #477) + +_NOTE:_ This version drops support for Go 1.16 and Go 1.15. The currently supported Go versions are the last 3 stable releases: 1.19, 1.18 and 1.17. + +## v0.13.0 + +- ref: Change DSN ProjectID to be a string (#420) +- fix: When extracting PCs from stack frames, try the `PC` field (#393) +- build: Bump gin-gonic/gin from v1.4.0 to v1.7.7 (#412) +- build: Bump Go version in go.mod (#410) +- ci: Bump golangci-lint version in GH workflow (#419) +- ci: Update GraphQL config with appropriate permissions (#417) +- ci: ci: Add craft release automation (#422) + +## v0.12.0 + +- feat: Automatic Release detection (#363, #369, #386, #400) +- fix: Do not change Hub.lastEventID for transactions (#379) +- fix: Do not clear LastEventID when events are dropped (#382) +- Updates to documentation (#366, #385) + +_NOTE:_ +This version drops support for Go 1.14, however no changes have been made that would make the SDK not work with Go 1.14. The currently supported Go versions are the last 3 stable releases: 1.15, 1.16 and 1.17. +There are two behavior changes related to `LastEventID`, both of which were intended to align the behavior of the Sentry Go SDK with other Sentry SDKs. +The new [automatic release detection feature](https://github.com/getsentry/sentry-go/issues/335) makes it easier to use Sentry and separate events per release without requiring extra work from users. We intend to improve this functionality in a future release by utilizing information that will be available in runtime starting with Go 1.18. The tracking issue is [#401](https://github.com/getsentry/sentry-go/issues/401). + +## v0.11.0 + +- feat(transports): Category-based Rate Limiting ([#354](https://github.com/getsentry/sentry-go/pull/354)) +- feat(transports): Report User-Agent identifying SDK ([#357](https://github.com/getsentry/sentry-go/pull/357)) +- fix(scope): Include event processors in clone ([#349](https://github.com/getsentry/sentry-go/pull/349)) +- Improvements to `go doc` documentation ([#344](https://github.com/getsentry/sentry-go/pull/344), [#350](https://github.com/getsentry/sentry-go/pull/350), [#351](https://github.com/getsentry/sentry-go/pull/351)) +- Miscellaneous changes to our testing infrastructure with GitHub Actions + ([57123a40](https://github.com/getsentry/sentry-go/commit/57123a409be55f61b1d5a6da93c176c55a399ad0), [#128](https://github.com/getsentry/sentry-go/pull/128), [#338](https://github.com/getsentry/sentry-go/pull/338), [#345](https://github.com/getsentry/sentry-go/pull/345), [#346](https://github.com/getsentry/sentry-go/pull/346), [#352](https://github.com/getsentry/sentry-go/pull/352), [#353](https://github.com/getsentry/sentry-go/pull/353), [#355](https://github.com/getsentry/sentry-go/pull/355)) + +_NOTE:_ +This version drops support for Go 1.13. The currently supported Go versions are the last 3 stable releases: 1.14, 1.15 and 1.16. +Users of the tracing functionality (`StartSpan`, etc) should upgrade to this version to benefit from separate rate limits for errors and transactions. +There are no breaking changes and upgrading should be a smooth experience for all users. + +## v0.10.0 + +- feat: Debug connection reuse (#323) +- fix: Send root span data as `Event.Extra` (#329) +- fix: Do not double sample transactions (#328) +- fix: Do not override trace context of transactions (#327) +- fix: Drain and close API response bodies (#322) +- ci: Run tests against Go tip (#319) +- ci: Move away from Travis in favor of GitHub Actions (#314) (#321) + +## v0.9.0 + +- feat: Initial tracing and performance monitoring support (#285) +- doc: Revamp sentryhttp documentation (#304) +- fix: Hub.PopScope never empties the scope stack (#300) +- ref: Report Event.Timestamp in local time (#299) +- ref: Report Breadcrumb.Timestamp in local time (#299) + +_NOTE:_ +This version introduces support for [Sentry's Performance Monitoring](https://docs.sentry.io/platforms/go/performance/). +The new tracing capabilities are beta, and we plan to expand them on future versions. Feedback is welcome, please open new issues on GitHub. +The `sentryhttp` package got better API docs, an [updated usage example](https://github.com/getsentry/sentry-go/tree/master/_examples/http) and support for creating automatic transactions as part of Performance Monitoring. + +## v0.8.0 + +- build: Bump required version of Iris (#296) +- fix: avoid unnecessary allocation in Client.processEvent (#293) +- doc: Remove deprecation of sentryhttp.HandleFunc (#284) +- ref: Update sentryhttp example (#283) +- doc: Improve documentation of sentryhttp package (#282) +- doc: Clarify SampleRate documentation (#279) +- fix: Remove RawStacktrace (#278) +- docs: Add example of custom HTTP transport +- ci: Test against go1.15, drop go1.12 support (#271) + +_NOTE:_ +This version comes with a few updates. Some examples and documentation have been +improved. We've bumped the supported version of the Iris framework to avoid +LGPL-licensed modules in the module dependency graph. +The `Exception.RawStacktrace` and `Thread.RawStacktrace` fields have been +removed to conform to Sentry's ingestion protocol, only `Exception.Stacktrace` +and `Thread.Stacktrace` should appear in user code. + +## v0.7.0 + +- feat: Include original error when event cannot be encoded as JSON (#258) +- feat: Use Hub from request context when available (#217, #259) +- feat: Extract stack frames from golang.org/x/xerrors (#262) +- feat: Make Environment Integration preserve existing context data (#261) +- feat: Recover and RecoverWithContext with arbitrary types (#268) +- feat: Report bad usage of CaptureMessage and CaptureEvent (#269) +- feat: Send debug logging to stderr by default (#266) +- feat: Several improvements to documentation (#223, #245, #250, #265) +- feat: Example of Recover followed by panic (#241, #247) +- feat: Add Transactions and Spans (to support OpenTelemetry Sentry Exporter) (#235, #243, #254) +- fix: Set either Frame.Filename or Frame.AbsPath (#233) +- fix: Clone requestBody to new Scope (#244) +- fix: Synchronize access and mutation of Hub.lastEventID (#264) +- fix: Avoid repeated syscalls in prepareEvent (#256) +- fix: Do not allocate new RNG for every event (#256) +- fix: Remove stale replace directive in go.mod (#255) +- fix(http): Deprecate HandleFunc, remove duplication (#260) + +_NOTE:_ +This version comes packed with several fixes and improvements and no breaking +changes. +Notably, there is a change in how the SDK reports file names in stack traces +that should resolve any ambiguity when looking at stack traces and using the +Suspect Commits feature. +We recommend all users to upgrade. + +## v0.6.1 + +- fix: Use NewEvent to init Event struct (#220) + +_NOTE:_ +A change introduced in v0.6.0 with the intent of avoiding allocations made a +pattern used in official examples break in certain circumstances (attempting +to write to a nil map). +This release reverts the change such that maps in the Event struct are always +allocated. + +## v0.6.0 + +- feat: Read module dependencies from runtime/debug (#199) +- feat: Support chained errors using Unwrap (#206) +- feat: Report chain of errors when available (#185) +- **[breaking]** fix: Accept http.RoundTripper to customize transport (#205) + Before the SDK accepted a concrete value of type `*http.Transport` in + `ClientOptions`, now it accepts any value implementing the `http.RoundTripper` + interface. Note that `*http.Transport` implements `http.RoundTripper`, so most + code bases will continue to work unchanged. + Users of custom transport gain the ability to pass in other implementations of + `http.RoundTripper` and may be able to simplify their code bases. +- fix: Do not panic when scope event processor drops event (#192) +- **[breaking]** fix: Use time.Time for timestamps (#191) + Users of sentry-go typically do not need to manipulate timestamps manually. + For those who do, the field type changed from `int64` to `time.Time`, which + should be more convenient to use. The recommended way to get the current time + is `time.Now().UTC()`. +- fix: Report usage error including stack trace (#189) +- feat: Add Exception.ThreadID field (#183) +- ci: Test against Go 1.14, drop 1.11 (#170) +- feat: Limit reading bytes from request bodies (#168) +- **[breaking]** fix: Rename fasthttp integration package sentryhttp => sentryfasthttp + The current recommendation is to use a named import, in which case existing + code should not require any change: + ```go + package main + + import ( + "fmt" + + "github.com/getsentry/sentry-go" + sentryfasthttp "github.com/getsentry/sentry-go/fasthttp" + "github.com/valyala/fasthttp" + ) + ``` + +_NOTE:_ +This version includes some new features and a few breaking changes, none of +which should pose troubles with upgrading. Most code bases should be able to +upgrade without any changes. + +## v0.5.1 + +- fix: Ignore err.Cause() when it is nil (#160) + +## v0.5.0 + +- fix: Synchronize access to HTTPTransport.disabledUntil (#158) +- docs: Update Flush documentation (#153) +- fix: HTTPTransport.Flush panic and data race (#140) + +_NOTE:_ +This version changes the implementation of the default transport, modifying the +behavior of `sentry.Flush`. The previous behavior was to wait until there were +no buffered events; new concurrent events kept `Flush` from returning. The new +behavior is to wait until the last event prior to the call to `Flush` has been +sent or the timeout; new concurrent events have no effect. The new behavior is +inline with the [Unified API +Guidelines](https://docs.sentry.io/development/sdk-dev/unified-api/). + +We have updated the documentation and examples to clarify that `Flush` is meant +to be called typically only once before program termination, to wait for +in-flight events to be sent to Sentry. Calling `Flush` after every event is not +recommended, as it introduces unnecessary latency to the surrounding function. +Please verify the usage of `sentry.Flush` in your code base. + +## v0.4.0 + +- fix(stacktrace): Correctly report package names (#127) +- fix(stacktrace): Do not rely on AbsPath of files (#123) +- build: Require github.com/ugorji/go@v1.1.7 (#110) +- fix: Correctly store last event id (#99) +- fix: Include request body in event payload (#94) +- build: Reset go.mod version to 1.11 (#109) +- fix: Eliminate data race in modules integration (#105) +- feat: Add support for path prefixes in the DSN (#102) +- feat: Add HTTPClient option (#86) +- feat: Extract correct type and value from top-most error (#85) +- feat: Check for broken pipe errors in Gin integration (#82) +- fix: Client.CaptureMessage accept nil EventModifier (#72) + +## v0.3.1 + +- feat: Send extra information exposed by the Go runtime (#76) +- fix: Handle new lines in module integration (#65) +- fix: Make sure that cache is locked when updating for contextifyFramesIntegration +- ref: Update Iris integration and example to version 12 +- misc: Remove indirect dependencies in order to move them to separate go.mod files + +## v0.3.0 + +- feat: Retry event marshaling without contextual data if the first pass fails +- fix: Include `url.Parse` error in `DsnParseError` +- fix: Make more `Scope` methods safe for concurrency +- fix: Synchronize concurrent access to `Hub.client` +- ref: Remove mutex from `Scope` exported API +- ref: Remove mutex from `Hub` exported API +- ref: Compile regexps for `filterFrames` only once +- ref: Change `SampleRate` type to `float64` +- doc: `Scope.Clear` not safe for concurrent use +- ci: Test sentry-go with `go1.13`, drop `go1.10` + +_NOTE:_ +This version removes some of the internal APIs that landed publicly (namely `Hub/Scope` mutex structs) and may require (but shouldn't) some changes to your code. +It's not done through major version update, as we are still in `0.x` stage. + +## v0.2.1 + +- fix: Run `Contextify` integration on `Threads` as well + +## v0.2.0 + +- feat: Add `SetTransaction()` method on the `Scope` +- feat: `fasthttp` framework support with `sentryfasthttp` package +- fix: Add `RWMutex` locks to internal `Hub` and `Scope` changes + +## v0.1.3 + +- feat: Move frames context reading into `contextifyFramesIntegration` (#28) + +_NOTE:_ +In case of any performance issues due to source contexts IO, you can let us know and turn off the integration in the meantime with: + +```go +sentry.Init(sentry.ClientOptions{ + Integrations: func(integrations []sentry.Integration) []sentry.Integration { + var filteredIntegrations []sentry.Integration + for _, integration := range integrations { + if integration.Name() == "ContextifyFrames" { + continue + } + filteredIntegrations = append(filteredIntegrations, integration) + } + return filteredIntegrations + }, +}) +``` + +## v0.1.2 + +- feat: Better source code location resolution and more useful inapp frames (#26) +- feat: Use `noopTransport` when no `Dsn` provided (#27) +- ref: Allow empty `Dsn` instead of returning an error (#22) +- fix: Use `NewScope` instead of literal struct inside a `scope.Clear` call (#24) +- fix: Add to `WaitGroup` before the request is put inside a buffer (#25) + +## v0.1.1 + +- fix: Check for initialized `Client` in `AddBreadcrumbs` (#20) +- build: Bump version when releasing with Craft (#19) + +## v0.1.0 + +- First stable release! \o/ + +## v0.0.1-beta.5 + +- feat: **[breaking]** Add `NewHTTPTransport` and `NewHTTPSyncTransport` which accepts all transport options +- feat: New `HTTPSyncTransport` that blocks after each call +- feat: New `Echo` integration +- ref: **[breaking]** Remove `BufferSize` option from `ClientOptions` and move it to `HTTPTransport` instead +- ref: Export default `HTTPTransport` +- ref: Export `net/http` integration handler +- ref: Set `Request` instantly in the package handlers, not in `recoverWithSentry` so it can be accessed later on +- ci: Add craft config + +## v0.0.1-beta.4 + +- feat: `IgnoreErrors` client option and corresponding integration +- ref: Reworked `net/http` integration, wrote better example and complete readme +- ref: Reworked `Gin` integration, wrote better example and complete readme +- ref: Reworked `Iris` integration, wrote better example and complete readme +- ref: Reworked `Negroni` integration, wrote better example and complete readme +- ref: Reworked `Martini` integration, wrote better example and complete readme +- ref: Remove `Handle()` from frameworks handlers and return it directly from New + +## v0.0.1-beta.3 + +- feat: `Iris` framework support with `sentryiris` package +- feat: `Gin` framework support with `sentrygin` package +- feat: `Martini` framework support with `sentrymartini` package +- feat: `Negroni` framework support with `sentrynegroni` package +- feat: Add `Hub.Clone()` for easier frameworks integration +- feat: Return `EventID` from `Recovery` methods +- feat: Add `NewScope` and `NewEvent` functions and use them in the whole codebase +- feat: Add `AddEventProcessor` to the `Client` +- fix: Operate on requests body copy instead of the original +- ref: Try to read source files from the root directory, based on the filename as well, to make it work on AWS Lambda +- ref: Remove `gocertifi` dependence and document how to provide your own certificates +- ref: **[breaking]** Remove `Decorate` and `DecorateFunc` methods in favor of `sentryhttp` package +- ref: **[breaking]** Allow for integrations to live on the client, by passing client instance in `SetupOnce` method +- ref: **[breaking]** Remove `GetIntegration` from the `Hub` +- ref: **[breaking]** Remove `GlobalEventProcessors` getter from the public API + +## v0.0.1-beta.2 + +- feat: Add `AttachStacktrace` client option to include stacktrace for messages +- feat: Add `BufferSize` client option to configure transport buffer size +- feat: Add `SetRequest` method on a `Scope` to control `Request` context data +- feat: Add `FromHTTPRequest` for `Request` type for easier extraction +- ref: Extract `Request` information more accurately +- fix: Attach `ServerName`, `Release`, `Dist`, `Environment` options to the event +- fix: Don't log events dropped due to full transport buffer as sent +- fix: Don't panic and create an appropriate event when called `CaptureException` or `Recover` with `nil` value + +## v0.0.1-beta + +- Initial release diff --git a/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md b/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md new file mode 100644 index 0000000..9808f18 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/CONTRIBUTING.md @@ -0,0 +1,98 @@ +# Contributing to sentry-go + +Hey, thank you if you're reading this, we welcome your contribution! + +## Sending a Pull Request + +Please help us save time when reviewing your PR by following this simple +process: + +1. Is your PR a simple typo fix? Read no further, **click that green "Create + pull request" button**! + +2. For more complex PRs that involve behavior changes or new APIs, please + consider [opening an **issue**][new-issue] describing the problem you're + trying to solve if there's not one already. + + A PR is often one specific solution to a problem and sometimes talking about + the problem unfolds new possible solutions. Remember we will be responsible + for maintaining the changes later. + +3. Fixing a bug and changing a behavior? Please add automated tests to prevent + future regression. + +4. Practice writing good commit messages. We have [commit + guidelines][commit-guide]. + +5. We have [guidelines for PR submitters][pr-guide]. A short summary: + + - Good PR descriptions are very helpful and most of the time they include + **why** something is done and why done in this particular way. Also list + other possible solutions that were considered and discarded. + - Be your own first reviewer. Make sure your code compiles and passes the + existing tests. + +[new-issue]: https://github.com/getsentry/sentry-go/issues/new/choose +[commit-guide]: https://develop.sentry.dev/code-review/#commit-guidelines +[pr-guide]: https://develop.sentry.dev/code-review/#guidelines-for-submitters + +Please also read through our [SDK Development docs](https://develop.sentry.dev/sdk/). +It contains information about SDK features, expected payloads and best practices for +contributing to Sentry SDKs. + +## Community + +The public-facing channels for support and development of Sentry SDKs can be found on [Discord](https://discord.gg/Ww9hbqr). + +## Testing + +```console +$ go test +``` + +### Watch mode + +Use: https://github.com/cespare/reflex + +```console +$ reflex -g '*.go' -d "none" -- sh -c 'printf "\n"; go test' +``` + +### With data race detection + +```console +$ go test -race +``` + +### Coverage + +```console +$ go test -race -coverprofile=coverage.txt -covermode=atomic && go tool cover -html coverage.txt +``` + +## Linting + +Lint with [`golangci-lint`](https://github.com/golangci/golangci-lint): + +```console +$ golangci-lint run +``` + +## Release + +1. Update `CHANGELOG.md` with new version in `vX.X.X` format title and list of changes. + + The command below can be used to get a list of changes since the last tag, with the format used in `CHANGELOG.md`: + + ```console + $ git log --no-merges --format=%s $(git describe --abbrev=0).. | sed 's/^/- /' + ``` + +2. Commit with `misc: vX.X.X changelog` commit message and push to `master`. + +3. Let [`craft`](https://github.com/getsentry/craft) do the rest: + + ```console + $ craft prepare X.X.X + $ craft publish X.X.X + ``` diff --git a/vendor/github.com/getsentry/sentry-go/LICENSE b/vendor/github.com/getsentry/sentry-go/LICENSE new file mode 100644 index 0000000..b1b358e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Functional Software, Inc. dba Sentry + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/getsentry/sentry-go/MIGRATION.md b/vendor/github.com/getsentry/sentry-go/MIGRATION.md new file mode 100644 index 0000000..2c30d62 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/MIGRATION.md @@ -0,0 +1,3 @@ +# `raven-go` to `sentry-go` Migration Guide + +A [`raven-go` to `sentry-go` migration guide](https://docs.sentry.io/platforms/go/migration/) is available at the official Sentry documentation site. diff --git a/vendor/github.com/getsentry/sentry-go/Makefile b/vendor/github.com/getsentry/sentry-go/Makefile new file mode 100644 index 0000000..edd1777 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/Makefile @@ -0,0 +1,67 @@ +.DEFAULT_GOAL := help + +GO = go +ALL_GO_MOD_DIRS := $(shell $(GO) work edit -json | jq -r '.Use[].DiskPath') +WORK_LINT_TARGETS := $(patsubst %, %/..., $(ALL_GO_MOD_DIRS)) +TIMEOUT = 300 + +help: ## Show help + @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' +.PHONY: help + +build: ## Build all workspace modules + $(GO) build work +.PHONY: build + +test: ## Run tests across all workspace modules + $(GO) test -count=1 -timeout $(TIMEOUT)s work +.PHONY: test + +test-race: ## Run tests with race detection + $(GO) test -count=1 -timeout $(TIMEOUT)s -race work +.PHONY: test-race + +COVERAGE_MODE = atomic +COVERAGE_DIR = .coverage +COVERAGE_PROFILE = $(COVERAGE_DIR)/coverage.out + +$(COVERAGE_DIR): + mkdir -p $(COVERAGE_DIR) + +test-coverage: $(COVERAGE_DIR) ## Test with coverage enabled + rm -f $(COVERAGE_DIR)/* + $(GO) test -count=1 -timeout $(TIMEOUT)s -covermode=$(COVERAGE_MODE) -coverprofile=$(COVERAGE_PROFILE) work +.PHONY: test-coverage + +test-race-coverage: $(COVERAGE_DIR) ## Run tests with race detection and coverage + rm -f $(COVERAGE_DIR)/* + $(GO) test -count=1 -timeout $(TIMEOUT)s -race -covermode=$(COVERAGE_MODE) -coverprofile=$(COVERAGE_PROFILE) work +.PHONY: test-race-coverage + +vet: ## Run "go vet" across all workspace modules + $(GO) vet work +.PHONY: vet + +mod-tidy: ## Check go.mod tidiness + @set -e ; \ + for dir in $(ALL_GO_MOD_DIRS); do \ + MOD_GO=$$(sed -n 's/^go \([0-9.]*\)/\1/p' "$${dir}/go.mod"); \ + echo ">>> Running 'go mod tidy' for module: $${dir} (go $${MOD_GO})"; \ + (cd "$${dir}" && GOTOOLCHAIN=local $(GO) mod tidy -go=$${MOD_GO} -compat=$${MOD_GO}); \ + done; \ + git diff --exit-code +.PHONY: mod-tidy + +gotidy: $(ALL_GO_MOD_DIRS:%=gotidy/%) ## Run go mod tidy across all modules +gotidy/%: DIR=$* +gotidy/%: + @echo "==> $(DIR)" && (cd "$(DIR)" && $(GO) mod tidy) +.PHONY: gotidy + +lint: ## Lint (using "golangci-lint") + golangci-lint run $(WORK_LINT_TARGETS) +.PHONY: lint + +fmt: ## Format all Go files + gofmt -l -w -s . +.PHONY: fmt diff --git a/vendor/github.com/getsentry/sentry-go/README.md b/vendor/github.com/getsentry/sentry-go/README.md new file mode 100644 index 0000000..a44b969 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/README.md @@ -0,0 +1,108 @@ +

+ + + + + Sentry + + +

+ +# Official Sentry SDK for Go + +[![Build Status](https://github.com/getsentry/sentry-go/actions/workflows/test.yml/badge.svg)](https://github.com/getsentry/sentry-go/actions/workflows/test.yml) +[![Go Report Card](https://goreportcard.com/badge/github.com/getsentry/sentry-go)](https://goreportcard.com/report/github.com/getsentry/sentry-go) +[![Discord](https://img.shields.io/discord/621778831602221064)](https://discord.gg/Ww9hbqr) +[![X Follow](https://img.shields.io/twitter/follow/sentry?label=sentry&style=social)](https://x.com/intent/follow?screen_name=sentry) +[![go.dev](https://img.shields.io/badge/go.dev-pkg-007d9c.svg?style=flat)](https://pkg.go.dev/github.com/getsentry/sentry-go) + +`sentry-go` provides a Sentry client implementation for the Go programming +language. This is the next generation of the Go SDK for [Sentry](https://sentry.io/), +intended to replace the `raven-go` package. + +> Looking for the old `raven-go` SDK documentation? See the Legacy client section [here](https://docs.sentry.io/clients/go/). +> If you want to start using `sentry-go` instead, check out the [migration guide](https://docs.sentry.io/platforms/go/migration/). + +## Requirements + +The only requirement is a Go compiler. + +We follow Go's [official release policy](https://go.dev/doc/devel/release#policy), +supporting the two most recent Go releases. Each major Go release is supported +until there are two newer major releases. The exact versions are defined in +[`GitHub workflow`](.github/workflows/test.yml). + +In addition, we run tests against the current master branch of the Go toolchain, +though support for this configuration is best-effort. + +## Installation + +`sentry-go` can be installed like any other Go library through `go get`: + +```console +$ go get github.com/getsentry/sentry-go@latest +``` + +Check out the [list of released versions](https://github.com/getsentry/sentry-go/releases). + +## Configuration + +To use `sentry-go`, you’ll need to import the `sentry-go` package and initialize +it with your DSN and other [options](https://pkg.go.dev/github.com/getsentry/sentry-go#ClientOptions). + +If not specified in the SDK initialization, the +[DSN](https://docs.sentry.io/product/sentry-basics/dsn-explainer/), +[Release](https://docs.sentry.io/product/releases/) and +[Environment](https://docs.sentry.io/product/sentry-basics/environments/) +are read from the environment variables `SENTRY_DSN`, `SENTRY_RELEASE` and +`SENTRY_ENVIRONMENT`, respectively. + +More on this in the [Configuration section of the official Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/configuration/). + +## Usage + +The SDK supports reporting errors and tracking application performance. + +To get started, have a look at one of our [examples](_examples/): +- [Basic error instrumentation](_examples/basic/main.go) +- [Error and tracing for HTTP servers](_examples/http/main.go) + +We also provide a [complete API reference](https://pkg.go.dev/github.com/getsentry/sentry-go). + +For more detailed information about how to get the most out of `sentry-go`, +check out the official documentation: + +- [Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/) +- Guides: + - [net/http](https://docs.sentry.io/platforms/go/guides/http/) + - [echo](https://docs.sentry.io/platforms/go/guides/echo/) + - [fasthttp](https://docs.sentry.io/platforms/go/guides/fasthttp/) + - [fiber](https://docs.sentry.io/platforms/go/guides/fiber/) + - [gin](https://docs.sentry.io/platforms/go/guides/gin/) + - [iris](https://docs.sentry.io/platforms/go/guides/iris/) + - [logrus](https://docs.sentry.io/platforms/go/guides/logrus/) + - [negroni](https://docs.sentry.io/platforms/go/guides/negroni/) + - [slog](https://docs.sentry.io/platforms/go/guides/slog/) + - [zerolog](https://docs.sentry.io/platforms/go/guides/zerolog/) + +## Resources + +- [Bug Tracker](https://github.com/getsentry/sentry-go/issues) +- [GitHub Project](https://github.com/getsentry/sentry-go) +- [![go.dev](https://img.shields.io/badge/go.dev-pkg-007d9c.svg?style=flat)](https://pkg.go.dev/github.com/getsentry/sentry-go) +- [![Documentation](https://img.shields.io/badge/documentation-sentry.io-green.svg)](https://docs.sentry.io/platforms/go/) +- [![Discussions](https://img.shields.io/github/discussions/getsentry/sentry-go.svg)](https://github.com/getsentry/sentry-go/discussions) +- [![Discord](https://img.shields.io/discord/621778831602221064)](https://discord.gg/Ww9hbqr) +- [![Stack Overflow](https://img.shields.io/badge/stack%20overflow-sentry-green.svg)](http://stackoverflow.com/questions/tagged/sentry) +- [![Twitter Follow](https://img.shields.io/twitter/follow/getsentry?label=getsentry&style=social)](https://twitter.com/intent/follow?screen_name=getsentry) + +## License + +Licensed under +[The MIT License](https://opensource.org/licenses/mit/), see +[`LICENSE`](LICENSE). + +## Community + +Join Sentry's [`#go` channel on Discord](https://discord.gg/Ww9hbqr) to get +involved and help us improve the SDK! diff --git a/vendor/github.com/getsentry/sentry-go/agents.toml b/vendor/github.com/getsentry/sentry-go/agents.toml new file mode 100644 index 0000000..db47be2 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/agents.toml @@ -0,0 +1,38 @@ +version = 1 +agents = ["claude", "codex"] + +[trust] +github_orgs = [ "getsentry" ] + + +[[skills]] +name = "dotagents" +source = "getsentry/dotagents" + +[[skills]] +name = "find-bugs" +source = "getsentry/skills" + +[[skills]] +name = "code-review" +source = "getsentry/skills" + +[[skills]] +name = "commit" +source = "getsentry/skills" + +[[skills]] +name = "create-pr" +source = "getsentry/skills" + +[[skills]] +name = "code-simplifier" +source = "getsentry/skills" + +[[skills]] +name = "iterate-pr" +source = "getsentry/skills" + +[[skills]] +name = "security-review" +source = "getsentry/skills" diff --git a/vendor/github.com/getsentry/sentry-go/attribute/builder.go b/vendor/github.com/getsentry/sentry-go/attribute/builder.go new file mode 100644 index 0000000..314802b --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/attribute/builder.go @@ -0,0 +1,61 @@ +package attribute + +type Builder struct { + Key string + Value Value +} + +// String returns a Builder for a string value. +func String(key, value string) Builder { + return Builder{key, StringValue(value)} +} + +// Int64 returns a Builder for an int64. +func Int64(key string, value int64) Builder { + return Builder{key, Int64Value(value)} +} + +// Int returns a Builder for an int64. +func Int(key string, value int) Builder { + return Builder{key, IntValue(value)} +} + +// Float64 returns a Builder for a float64. +func Float64(key string, v float64) Builder { + return Builder{key, Float64Value(v)} +} + +// Bool returns a Builder for a boolean. +func Bool(key string, v bool) Builder { + return Builder{key, BoolValue(v)} +} + +// BoolSlice returns a Builder for a bool slice. +func BoolSlice(key string, v []bool) Builder { + return Builder{key, BoolSliceValue(v)} +} + +// IntSlice returns a Builder for an int slice. +func IntSlice(key string, v []int) Builder { + return Builder{key, IntSliceValue(v)} +} + +// Int64Slice returns a Builder for an int64 slice. +func Int64Slice(key string, v []int64) Builder { + return Builder{key, Int64SliceValue(v)} +} + +// Float64Slice returns a Builder for a float64 slice. +func Float64Slice(key string, v []float64) Builder { + return Builder{key, Float64SliceValue(v)} +} + +// StringSlice returns a Builder for a string slice. +func StringSlice(key string, v []string) Builder { + return Builder{key, StringSliceValue(v)} +} + +// Valid checks for valid key and type. +func (b *Builder) Valid() bool { + return len(b.Key) > 0 && b.Value.Type() != INVALID +} diff --git a/vendor/github.com/getsentry/sentry-go/attribute/rawhelpers.go b/vendor/github.com/getsentry/sentry-go/attribute/rawhelpers.go new file mode 100644 index 0000000..8ba7a88 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/attribute/rawhelpers.go @@ -0,0 +1,49 @@ +// Copied from https://github.com/open-telemetry/opentelemetry-go/blob/cc43e01c27892252aac9a8f20da28cdde957a289/attribute/rawhelpers.go +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package attribute + +import ( + "math" +) + +func boolToRaw(b bool) uint64 { // b is not a control flag. + if b { + return 1 + } + return 0 +} + +func rawToBool(r uint64) bool { + return r != 0 +} + +func int64ToRaw(i int64) uint64 { + // Assumes original was a valid int64 (overflow not checked). + return uint64(i) // nolint: gosec +} + +func rawToInt64(r uint64) int64 { + // Assumes original was a valid int64 (overflow not checked). + return int64(r) // nolint: gosec +} + +func float64ToRaw(f float64) uint64 { + return math.Float64bits(f) +} + +func rawToFloat64(r uint64) float64 { + return math.Float64frombits(r) +} diff --git a/vendor/github.com/getsentry/sentry-go/attribute/slicehelpers.go b/vendor/github.com/getsentry/sentry-go/attribute/slicehelpers.go new file mode 100644 index 0000000..4d53fa0 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/attribute/slicehelpers.go @@ -0,0 +1,15 @@ +package attribute + +import "reflect" + +func asSlice[T any](v any) []T { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Array { + return nil + } + cpy := make([]T, rv.Len()) + if len(cpy) > 0 { + _ = reflect.Copy(reflect.ValueOf(cpy), rv) + } + return cpy +} diff --git a/vendor/github.com/getsentry/sentry-go/attribute/value.go b/vendor/github.com/getsentry/sentry-go/attribute/value.go new file mode 100644 index 0000000..872a04a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/attribute/value.go @@ -0,0 +1,321 @@ +// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/cc43e01c27892252aac9a8f20da28cdde957a289/attribute/value.go +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package attribute + +import ( + "encoding/json" + "fmt" + "reflect" + "strconv" +) + +// Type describes the type of the data Value holds. +type Type int // redefines builtin Type. + +// Value represents the value part in key-value pairs. +type Value struct { + vtype Type + numeric uint64 + stringly string + slice any +} + +const ( + // INVALID is used for a Value with no value set. + INVALID Type = iota + // BOOL is a boolean Type Value. + BOOL + // INT64 is a 64-bit signed integral Type Value. + INT64 + // FLOAT64 is a 64-bit floating point Type Value. + FLOAT64 + // STRING is a string Type Value. + STRING + // BOOLSLICE is a slice of booleans Type Value. + BOOLSLICE + // INT64SLICE is a slice of 64-bit signed integral numbers Type Value. + INT64SLICE + // FLOAT64SLICE is a slice of 64-bit floating point numbers Type Value. + FLOAT64SLICE + // STRINGSLICE is a slice of strings Type Value. + STRINGSLICE + // UINT64 is a 64-bit unsigned integral Type Value. + // + // This type is intentionally not exposed through the Builder API. + UINT64 +) + +// BoolValue creates a BOOL Value. +func BoolValue(v bool) Value { + return Value{ + vtype: BOOL, + numeric: boolToRaw(v), + } +} + +// BoolSliceValue creates a BOOLSLICE Value. +func BoolSliceValue(v []bool) Value { + cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[bool]())).Elem() + reflect.Copy(cp, reflect.ValueOf(v)) + return Value{vtype: BOOLSLICE, slice: cp.Interface()} +} + +// IntValue creates an INT64 Value. +func IntValue(v int) Value { + return Int64Value(int64(v)) +} + +// IntSliceValue creates an INTSLICE Value. +func IntSliceValue(v []int) Value { + cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[int64]())) + for i, val := range v { + cp.Elem().Index(i).SetInt(int64(val)) + } + return Value{ + vtype: INT64SLICE, + slice: cp.Elem().Interface(), + } +} + +// Int64Value creates an INT64 Value. +func Int64Value(v int64) Value { + return Value{ + vtype: INT64, + numeric: int64ToRaw(v), + } +} + +// Int64SliceValue creates an INT64SLICE Value. +func Int64SliceValue(v []int64) Value { + cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[int64]())).Elem() + reflect.Copy(cp, reflect.ValueOf(v)) + return Value{vtype: INT64SLICE, slice: cp.Interface()} +} + +// Float64Value creates a FLOAT64 Value. +func Float64Value(v float64) Value { + return Value{ + vtype: FLOAT64, + numeric: float64ToRaw(v), + } +} + +// Float64SliceValue creates a FLOAT64SLICE Value. +func Float64SliceValue(v []float64) Value { + cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[float64]())).Elem() + reflect.Copy(cp, reflect.ValueOf(v)) + return Value{vtype: FLOAT64SLICE, slice: cp.Interface()} +} + +// StringValue creates a STRING Value. +func StringValue(v string) Value { + return Value{ + vtype: STRING, + stringly: v, + } +} + +// StringSliceValue creates a STRINGSLICE Value. +func StringSliceValue(v []string) Value { + cp := reflect.New(reflect.ArrayOf(len(v), reflect.TypeFor[string]())).Elem() + reflect.Copy(cp, reflect.ValueOf(v)) + return Value{vtype: STRINGSLICE, slice: cp.Interface()} +} + +// Uint64Value creates a UINT64 Value. +// +// This constructor is intentionally not exposed through the Builder API. +func Uint64Value(v uint64) Value { + return Value{ + vtype: UINT64, + numeric: v, + } +} + +// Type returns a type of the Value. +func (v Value) Type() Type { + return v.vtype +} + +// AsBool returns the bool value. Make sure that the Value's type is +// BOOL. +func (v Value) AsBool() bool { + return rawToBool(v.numeric) +} + +// AsBoolSlice returns the []bool value. Make sure that the Value's type is +// BOOLSLICE. +func (v Value) AsBoolSlice() []bool { + if v.vtype != BOOLSLICE { + return nil + } + return asSlice[bool](v.slice) +} + +// AsInt64 returns the int64 value. Make sure that the Value's type is +// INT64. +func (v Value) AsInt64() int64 { + return rawToInt64(v.numeric) +} + +// AsInt64Slice returns the []int64 value. Make sure that the Value's type is +// INT64SLICE. +func (v Value) AsInt64Slice() []int64 { + if v.vtype != INT64SLICE { + return nil + } + return asSlice[int64](v.slice) +} + +// AsFloat64 returns the float64 value. Make sure that the Value's +// type is FLOAT64. +func (v Value) AsFloat64() float64 { + return rawToFloat64(v.numeric) +} + +// AsFloat64Slice returns the []float64 value. Make sure that the Value's type is +// FLOAT64SLICE. +func (v Value) AsFloat64Slice() []float64 { + if v.vtype != FLOAT64SLICE { + return nil + } + return asSlice[float64](v.slice) +} + +// AsString returns the string value. Make sure that the Value's type +// is STRING. +func (v Value) AsString() string { + return v.stringly +} + +// AsStringSlice returns the []string value. Make sure that the Value's type is +// STRINGSLICE. +func (v Value) AsStringSlice() []string { + if v.vtype != STRINGSLICE { + return nil + } + return asSlice[string](v.slice) +} + +// AsUint64 returns the uint64 value. Make sure that the Value's type is +// UINT64. +func (v Value) AsUint64() uint64 { + return v.numeric +} + +type unknownValueType struct{} + +// AsInterface returns Value's data as interface{}. +func (v Value) AsInterface() interface{} { + switch v.Type() { + case BOOL: + return v.AsBool() + case BOOLSLICE: + return v.AsBoolSlice() + case INT64: + return v.AsInt64() + case INT64SLICE: + return v.AsInt64Slice() + case FLOAT64: + return v.AsFloat64() + case FLOAT64SLICE: + return v.AsFloat64Slice() + case STRING: + return v.stringly + case STRINGSLICE: + return v.AsStringSlice() + case UINT64: + return v.numeric + } + return unknownValueType{} +} + +// String returns a string representation of Value's data. +func (v Value) String() string { + switch v.Type() { + case BOOLSLICE: + return fmt.Sprint(v.AsBoolSlice()) + case BOOL: + return strconv.FormatBool(v.AsBool()) + case INT64SLICE: + return fmt.Sprint(v.AsInt64Slice()) + case INT64: + return strconv.FormatInt(v.AsInt64(), 10) + case FLOAT64SLICE: + return fmt.Sprint(v.AsFloat64Slice()) + case FLOAT64: + return fmt.Sprint(v.AsFloat64()) + case STRINGSLICE: + return fmt.Sprint(v.AsStringSlice()) + case STRING: + return v.stringly + case UINT64: + return strconv.FormatUint(v.numeric, 10) + default: + return "unknown" + } +} + +// MarshalJSON returns the JSON encoding of the Value. +func (v Value) MarshalJSON() ([]byte, error) { + var jsonVal struct { + Value any `json:"value"` + Type string `json:"type"` + } + jsonVal.Type = mapTypesToStr[v.Type()] + jsonVal.Value = v.AsInterface() + return json.Marshal(jsonVal) +} + +func (t Type) String() string { + switch t { + case BOOL: + return "bool" + case BOOLSLICE: + return "boolslice" + case INT64: + return "int64" + case INT64SLICE: + return "int64slice" + case FLOAT64: + return "float64" + case FLOAT64SLICE: + return "float64slice" + case STRING: + return "string" + case STRINGSLICE: + return "stringslice" + case UINT64: + return "uint64" + } + return "invalid" +} + +// mapTypesToStr is a map from attribute.Type to the primitive types the server understands. +// https://develop.sentry.dev/sdk/foundations/data-model/attributes/#primitive-types +var mapTypesToStr = map[Type]string{ + INVALID: "", + BOOL: "boolean", + INT64: "integer", + FLOAT64: "double", + STRING: "string", + BOOLSLICE: "array", + INT64SLICE: "array", + FLOAT64SLICE: "array", + STRINGSLICE: "array", + UINT64: "integer", // wire format: same "integer" type +} diff --git a/vendor/github.com/getsentry/sentry-go/baggage.go b/vendor/github.com/getsentry/sentry-go/baggage.go new file mode 100644 index 0000000..b039fd0 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/baggage.go @@ -0,0 +1,52 @@ +package sentry + +import ( + "fmt" + "strings" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/otel/baggage" +) + +// MergeBaggage merges an existing baggage header with a Sentry-generated one. +// +// Existing third-party members are preserved. If both baggage strings contain +// the same member key, the Sentry-generated member wins. The helper is best-effort +// and only keeps the sentry baggage in case the existing one is malformed. +func MergeBaggage(existingHeader, sentryHeader string) (string, error) { + // TODO: we are reparsing the headers here, because we currently don't + // expose a method to get only DSC or its baggage members. + sentryBaggage, err := baggage.Parse(sentryHeader) + if err != nil { + return "", fmt.Errorf("cannot parse sentryHeader: %w", err) + } + + existingBaggage, err := baggage.Parse(existingHeader) + if err != nil { + if sentryBaggage.Len() == 0 { + return "", fmt.Errorf("cannot parse existingHeader: %w", err) + } + // in case that the incoming header is malformed we should only + // care about merging sentry related baggage information for distributed tracing. + debuglog.Printf("malformed incoming header: %v", err) + return sentryBaggage.String(), nil + } + + sentryKeys := make(map[string]struct{}, sentryBaggage.Len()) + for _, member := range sentryBaggage.Members() { + sentryKeys[member.Key()] = struct{}{} + } + + parts := make([]string, 0, sentryBaggage.Len()+existingBaggage.Len()) + if s := sentryBaggage.String(); s != "" { + parts = append(parts, s) + } + for _, member := range existingBaggage.Members() { + if _, collides := sentryKeys[member.Key()]; collides { + continue + } + parts = append(parts, member.String()) + } + + return strings.Join(parts, ","), nil +} diff --git a/vendor/github.com/getsentry/sentry-go/batch_processor.go b/vendor/github.com/getsentry/sentry-go/batch_processor.go new file mode 100644 index 0000000..4b938ac --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/batch_processor.go @@ -0,0 +1,136 @@ +package sentry + +import ( + "context" + "sync" + "time" +) + +const ( + batchSize = 100 + defaultBatchTimeout = 5 * time.Second +) + +type batchProcessor[T any] struct { + sendBatch func([]T) + itemCh chan T + flushCh chan chan struct{} + cancel context.CancelFunc + wg sync.WaitGroup + startOnce sync.Once + shutdownOnce sync.Once + batchTimeout time.Duration +} + +func newBatchProcessor[T any](sendBatch func([]T)) *batchProcessor[T] { + return &batchProcessor[T]{ + itemCh: make(chan T, batchSize), + flushCh: make(chan chan struct{}), + sendBatch: sendBatch, + batchTimeout: defaultBatchTimeout, + } +} + +// WithBatchTimeout sets a custom batch timeout for the processor. +// This is useful for testing or when different timing behavior is needed. +func (p *batchProcessor[T]) WithBatchTimeout(timeout time.Duration) *batchProcessor[T] { + p.batchTimeout = timeout + return p +} + +func (p *batchProcessor[T]) Send(item T) bool { + select { + case p.itemCh <- item: + return true + default: + return false + } +} + +func (p *batchProcessor[T]) Start() { + p.startOnce.Do(func() { + ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // G118: cancel is stored in p.cancel and called in Shutdown() + p.cancel = cancel + p.wg.Add(1) + go p.run(ctx) + }) +} + +func (p *batchProcessor[T]) Flush(timeout <-chan struct{}) { + done := make(chan struct{}) + select { + case p.flushCh <- done: + select { + case <-done: + case <-timeout: + } + case <-timeout: + } +} + +func (p *batchProcessor[T]) Shutdown() { + p.shutdownOnce.Do(func() { + if p.cancel != nil { + p.cancel() + p.wg.Wait() + } + }) +} + +func (p *batchProcessor[T]) run(ctx context.Context) { + defer p.wg.Done() + var items []T + timer := time.NewTimer(0) + timer.Stop() + defer timer.Stop() + + for { + select { + case item := <-p.itemCh: + if len(items) == 0 { + timer.Reset(p.batchTimeout) + } + items = append(items, item) + if len(items) >= batchSize { + p.sendBatch(items) + items = nil + } + case <-timer.C: + if len(items) > 0 { + p.sendBatch(items) + items = nil + } + case done := <-p.flushCh: + flushDrain: + for { + select { + case item := <-p.itemCh: + items = append(items, item) + default: + break flushDrain + } + } + + if len(items) > 0 { + p.sendBatch(items) + items = nil + } + close(done) + case <-ctx.Done(): + drain: + for { + select { + case item := <-p.itemCh: + items = append(items, item) + default: + break drain + } + } + + if len(items) > 0 { + p.sendBatch(items) + } + return + } + } +} diff --git a/vendor/github.com/getsentry/sentry-go/check_in.go b/vendor/github.com/getsentry/sentry-go/check_in.go new file mode 100644 index 0000000..de6d0ad --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/check_in.go @@ -0,0 +1,121 @@ +package sentry + +import "time" + +type CheckInStatus string + +const ( + CheckInStatusInProgress CheckInStatus = "in_progress" + CheckInStatusOK CheckInStatus = "ok" + CheckInStatusError CheckInStatus = "error" +) + +type checkInScheduleType string + +const ( + checkInScheduleTypeCrontab checkInScheduleType = "crontab" + checkInScheduleTypeInterval checkInScheduleType = "interval" +) + +type MonitorSchedule interface { + // scheduleType is a private method that must be implemented for monitor schedule + // implementation. It should never be called. This method is made for having + // specific private implementation of MonitorSchedule interface. + scheduleType() checkInScheduleType +} + +type crontabSchedule struct { + Type string `json:"type"` + Value string `json:"value"` +} + +func (c crontabSchedule) scheduleType() checkInScheduleType { + return checkInScheduleTypeCrontab +} + +// CrontabSchedule defines the MonitorSchedule with a cron format. +// Example: "8 * * * *". +func CrontabSchedule(scheduleString string) MonitorSchedule { + return crontabSchedule{ + Type: string(checkInScheduleTypeCrontab), + Value: scheduleString, + } +} + +type intervalSchedule struct { + Type string `json:"type"` + Value int64 `json:"value"` + Unit string `json:"unit"` +} + +func (i intervalSchedule) scheduleType() checkInScheduleType { + return checkInScheduleTypeInterval +} + +type MonitorScheduleUnit string + +const ( + MonitorScheduleUnitMinute MonitorScheduleUnit = "minute" + MonitorScheduleUnitHour MonitorScheduleUnit = "hour" + MonitorScheduleUnitDay MonitorScheduleUnit = "day" + MonitorScheduleUnitWeek MonitorScheduleUnit = "week" + MonitorScheduleUnitMonth MonitorScheduleUnit = "month" + MonitorScheduleUnitYear MonitorScheduleUnit = "year" +) + +// IntervalSchedule defines the MonitorSchedule with an interval format. +// +// Example: +// +// IntervalSchedule(1, sentry.MonitorScheduleUnitDay) +func IntervalSchedule(value int64, unit MonitorScheduleUnit) MonitorSchedule { + return intervalSchedule{ + Type: string(checkInScheduleTypeInterval), + Value: value, + Unit: string(unit), + } +} + +type MonitorConfig struct { //nolint: maligned // prefer readability over optimal memory layout + Schedule MonitorSchedule `json:"schedule,omitempty"` + // The allowed margin of minutes after the expected check-in time that + // the monitor will not be considered missed for. + CheckInMargin int64 `json:"checkin_margin,omitempty"` + // The allowed duration in minutes that the monitor may be `in_progress` + // for before being considered failed due to timeout. + MaxRuntime int64 `json:"max_runtime,omitempty"` + // A tz database string representing the timezone which the monitor's execution schedule is in. + // See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones + Timezone string `json:"timezone,omitempty"` + // The number of consecutive failed check-ins it takes before an issue is created. + FailureIssueThreshold int64 `json:"failure_issue_threshold,omitempty"` + // The number of consecutive OK check-ins it takes before an issue is resolved. + RecoveryThreshold int64 `json:"recovery_threshold,omitempty"` +} + +type CheckIn struct { //nolint: maligned // prefer readability over optimal memory layout + // Check-In ID (unique and client generated) + ID EventID `json:"check_in_id"` + // The distinct slug of the monitor. + MonitorSlug string `json:"monitor_slug"` + // The status of the check-in. + Status CheckInStatus `json:"status"` + // The duration of the check-in. Will only take effect if the status is ok or error. + Duration time.Duration `json:"duration,omitempty"` +} + +// serializedCheckIn is used by checkInMarshalJSON method on Event struct. +// See https://develop.sentry.dev/sdk/check-ins/ +type serializedCheckIn struct { //nolint: maligned + // Check-In ID (unique and client generated). + CheckInID string `json:"check_in_id"` + // The distinct slug of the monitor. + MonitorSlug string `json:"monitor_slug"` + // The status of the check-in. + Status CheckInStatus `json:"status"` + // The duration of the check-in in seconds. Will only take effect if the status is ok or error. + Duration float64 `json:"duration,omitempty"` + Release string `json:"release,omitempty"` + Environment string `json:"environment,omitempty"` + MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"` +} diff --git a/vendor/github.com/getsentry/sentry-go/client.go b/vendor/github.com/getsentry/sentry-go/client.go new file mode 100644 index 0000000..dd6f13b --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/client.go @@ -0,0 +1,1070 @@ +package sentry + +import ( + "context" + "crypto/x509" + "fmt" + "io" + "math/rand" + "net/http" + "os" + "sort" + "strings" + "sync" + "time" + + "github.com/getsentry/sentry-go/internal/debug" + "github.com/getsentry/sentry-go/internal/debuglog" + httpInternal "github.com/getsentry/sentry-go/internal/http" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/internal/telemetry" + "github.com/getsentry/sentry-go/report" +) + +// The identifier of the SDK. +const sdkIdentifier = "sentry.go" + +const ( + // maxErrorDepth is the maximum number of errors reported in a chain of errors. + // This protects the SDK from an arbitrarily long chain of wrapped errors. + // + // An additional consideration is that arguably reporting a long chain of errors + // is of little use when debugging production errors with Sentry. The Sentry UI + // is not optimized for long chains either. The top-level error together with a + // stack trace is often the most useful information. + maxErrorDepth = 100 + + // defaultMaxSpans limits the default number of recorded spans per transaction. The limit is + // meant to bound memory usage and prevent too large transaction events that + // would be rejected by Sentry. + defaultMaxSpans = 1000 + + // defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to + // an event. Can be overwritten with the MaxBreadcrumbs option. + defaultMaxBreadcrumbs = 100 +) + +// hostname is the host name reported by the kernel. It is precomputed once to +// avoid syscalls when capturing events. +// +// The error is ignored because retrieving the host name is best-effort. If the +// error is non-nil, there is nothing to do other than retrying. We choose not +// to retry for now. +var hostname, _ = os.Hostname() + +// lockedRand is a random number generator safe for concurrent use. Its API is +// intentionally limited and it is not meant as a full replacement for a +// rand.Rand. +type lockedRand struct { + mu sync.Mutex + r *rand.Rand +} + +// Float64 returns a pseudo-random number in [0.0,1.0). +func (r *lockedRand) Float64() float64 { + r.mu.Lock() + defer r.mu.Unlock() + return r.r.Float64() +} + +// rng is the internal random number generator. +// +// We do not use the global functions from math/rand because, while they are +// safe for concurrent use, any package in a build could change the seed and +// affect the generated numbers, for instance making them deterministic. On the +// other hand, the source returned from rand.NewSource is not safe for +// concurrent use, so we need to couple its use with a sync.Mutex. +var rng = &lockedRand{ + // #nosec G404 -- We are fine using transparent, non-secure value here. + r: rand.New(rand.NewSource(time.Now().UnixNano())), +} + +// usageError is used to report to Sentry an SDK usage error. +// +// It is not exported because it is never returned by any function or method in +// the exported API. +type usageError struct { + error +} + +// DebugLogger is an instance of log.Logger that is used to provide debug information about running Sentry Client +// can be enabled by either using debuglog.SetOutput directly or with Debug client option. +var DebugLogger = debuglog.GetLogger() + +// EventProcessor is a function that processes an event. +// Event processors are used to change an event before it is sent to Sentry. +type EventProcessor func(event *Event, hint *EventHint) *Event + +// externalContextTraceResolver extracts trace and span IDs from an external context source. +// +// This is currently a workaround for extractring trace information from OTel SpanContext without +// needing the otel dependency on the root package. +type externalContextTraceResolver func(ctx context.Context) (traceID TraceID, spanID SpanID, ok bool) + +// EventModifier is the interface that wraps the ApplyToEvent method. +// +// ApplyToEvent changes an event based on external data and/or +// an event hint. +type EventModifier interface { + ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event +} + +var globalEventProcessors []EventProcessor + +// AddGlobalEventProcessor adds processor to the global list of event +// processors. Global event processors apply to all events. +// +// AddGlobalEventProcessor is deprecated. Most users will prefer to initialize +// the SDK with Init and provide a ClientOptions.BeforeSend function or use +// Scope.AddEventProcessor instead. +func AddGlobalEventProcessor(processor EventProcessor) { + globalEventProcessors = append(globalEventProcessors, processor) +} + +// Integration allows for registering a functions that modify or discard captured events. +type Integration interface { + Name() string + SetupOnce(client *Client) +} + +// ClientOptions that configures a SDK Client. +type ClientOptions struct { + // The DSN to use. If the DSN is not set, the client is effectively + // disabled. + Dsn string + // In debug mode, the debug information is printed to stdout to help you + // understand what sentry is doing. + Debug bool + // Configures whether SDK should generate and attach stacktraces to pure + // capture message calls. + AttachStacktrace bool + // The sample rate for event submission in the range [0.0, 1.0]. By default, + // all events are sent. Thus, as a historical special case, the sample rate + // 0.0 is treated as if it was 1.0. To drop all events, set the DSN to the + // empty string. + SampleRate float64 + // Enable performance tracing. + EnableTracing bool + // The sample rate for sampling traces in the range [0.0, 1.0]. + TracesSampleRate float64 + // Used to customize the sampling of traces, overrides TracesSampleRate. + TracesSampler TracesSampler + // Control with URLs trace propagation should be enabled. Does not support regex patterns. + TracePropagationTargets []string + // PropagateTraceparent is used to control whether the W3C Trace Context HTTP traceparent header + // is propagated on outgoing http requests. + PropagateTraceparent bool + // StrictTraceContinuation is used to control trace continuation from 3rd party services that happen to be + // instrumented by Sentry. + // + // Enabling the option means that the SDK will require the org ids from baggage to match for continuing the trace. + StrictTraceContinuation bool + // OrgID configures the orgID used for trace propagation and features like StrictTraceContinuation. + // + // In most cases the orgID is already parsed from the DSN. This option should be used when non-standard Sentry DSNs + // are used, such as self-hosted or when using a local Relay. + OrgID uint64 + // List of regexp strings that will be used to match against event's message + // and if applicable, caught errors type and value. + // If the match is found, then a whole event will be dropped. + IgnoreErrors []string + // List of regexp strings that will be used to match against a transaction's + // name. If a match is found, then the transaction will be dropped. + IgnoreTransactions []string + // Deprecated: Use DataCollection for granular control over what data the + // SDK collects. When DataCollection is configured, SendDefaultPII is + // ignored. + // + // If this flag is enabled, certain personally identifiable information (PII) is added by active integrations. + // By default, no such data is sent. + SendDefaultPII bool + // DataCollection configures what data the SDK collects automatically. All fields are optional. By default + // the SDK collects rich context for debugging while scrubbing sensitive values. + // + // See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection + DataCollection *DataCollection + // BeforeSend is called before error events are sent to Sentry. + // You can use it to mutate the event or return nil to discard it. + BeforeSend func(event *Event, hint *EventHint) *Event + // BeforeSendLong is called before log events are sent to Sentry. + // You can use it to mutate the log event or return nil to discard it. + BeforeSendLog func(event *Log) *Log + // BeforeSendTransaction is called before transaction events are sent to Sentry. + // Use it to mutate the transaction or return nil to discard the transaction. + BeforeSendTransaction func(event *Event, hint *EventHint) *Event + // Before breadcrumb add callback. + BeforeBreadcrumb func(breadcrumb *Breadcrumb, hint *BreadcrumbHint) *Breadcrumb + // BeforeSendMetric is called before metric events are sent to Sentry. + // You can use it to mutate the metric or return nil to discard it. + BeforeSendMetric func(metric *Metric) *Metric + // Integrations to be installed on the current Client, receives default + // integrations. + Integrations func([]Integration) []Integration + // io.Writer implementation that should be used with the Debug mode. + DebugWriter io.Writer + // The transport to use. Defaults to HTTPTransport. + Transport Transport + // The server name to be reported. + ServerName string + // The release to be sent with events. + // + // Some Sentry features are built around releases, and, thus, reporting + // events with a non-empty release improves the product experience. See + // https://docs.sentry.io/product/releases/. + // + // If Release is not set, the SDK will try to derive a default value + // from environment variables or the Git repository in the working + // directory. + // + // If you distribute a compiled binary, it is recommended to set the + // Release value explicitly at build time. As an example, you can use: + // + // go build -ldflags='-X main.release=VALUE' + // + // That will set the value of a predeclared variable 'release' in the + // 'main' package to 'VALUE'. Then, use that variable when initializing + // the SDK: + // + // sentry.Init(ClientOptions{Release: release}) + // + // See https://golang.org/cmd/go/ and https://golang.org/cmd/link/ for + // the official documentation of -ldflags and -X, respectively. + Release string + // The dist to be sent with events. + Dist string + // The environment to be sent with events. + Environment string + // Maximum number of breadcrumbs + // when MaxBreadcrumbs is negative then ignore breadcrumbs. + MaxBreadcrumbs int + // Maximum number of spans. + // + // See https://develop.sentry.dev/sdk/envelopes/#size-limits for size limits + // applied during event ingestion. Events that exceed these limits might get dropped. + MaxSpans int + // An optional pointer to http.Client that will be used with a default + // HTTPTransport. Using your own client will make HTTPTransport, HTTPProxy, + // HTTPSProxy and CaCerts options ignored. + HTTPClient *http.Client + // An optional pointer to http.Transport that will be used with a default + // HTTPTransport. Using your own transport will make HTTPProxy, HTTPSProxy + // and CaCerts options ignored. + HTTPTransport http.RoundTripper + // An optional HTTP proxy to use. + // This will default to the HTTP_PROXY environment variable. + HTTPProxy string + // An optional HTTPS proxy to use. + // This will default to the HTTPS_PROXY environment variable. + // HTTPS_PROXY takes precedence over HTTP_PROXY for https requests. + HTTPSProxy string + // An optional set of SSL certificates to use. + CaCerts *x509.CertPool + // MaxErrorDepth is the maximum number of errors reported in a chain of errors. + // This protects the SDK from an arbitrarily long chain of wrapped errors. + // + // An additional consideration is that arguably reporting a long chain of errors + // is of little use when debugging production errors with Sentry. The Sentry UI + // is not optimized for long chains either. The top-level error together with a + // stack trace is often the most useful information. + MaxErrorDepth int + // Default event tags. These are overridden by tags set on a scope. + Tags map[string]string + // DisableClientReports controls when client reports should be emitted. + DisableClientReports bool + // TraceIgnoreStatusCodes is a list of HTTP status codes that should not be traced. + // Each element can be either: + // - A single-element slice [code] for a specific status code + // - A two-element slice [min, max] for a range of status codes (inclusive) + // When an HTTP request results in a status code that matches any of these codes or ranges, + // the transaction will not be sent to Sentry. + // + // Examples: + // [][]int{{404}} // ignore only status code 404 + // [][]int{{400, 405}} // ignore status codes 400-405 + // [][]int{{404}, {500}} // ignore status codes 404 and 500 + // [][]int{{404}, {400, 405}, {500, 599}} // ignore 404, range 400-405, and range 500-599 + // + // By default, this ignores 404 status codes. + // + // IMPORTANT: to not ignore any status codes, the option should be an empty slice and not nil. The nil option is + // used for defaulting to 404 ignores. + TraceIgnoreStatusCodes [][]int + // DisableTelemetryBuffer disables the telemetry buffer layer for prioritizing events and uses the old transport layer. + DisableTelemetryBuffer bool +} + +// Client is the underlying processor that is used by the main API and Hub +// instances. It must be created with NewClient. +type Client struct { + mu sync.RWMutex + options ClientOptions + dsn *protocol.Dsn + eventProcessors []EventProcessor + integrations []Integration + externalTraceResolver externalContextTraceResolver + sdkIdentifier string + sdkVersion string + // Transport is read-only. Replacing the transport of an existing client is + // not supported, create a new client instead. + Transport Transport + batchLogger *logBatchProcessor + batchMeter *metricBatchProcessor + telemetryProcessor *telemetry.Processor + reportRecorder report.ClientReportRecorder + reportProvider report.ClientReportProvider +} + +// NewClient creates and returns an instance of Client configured using +// ClientOptions. +// +// Most users will not create clients directly. Instead, initialize the SDK with +// Init and use the package-level functions (for simple programs that run on a +// single goroutine) or hub methods (for concurrent programs, for example web +// servers). +func NewClient(options ClientOptions) (*Client, error) { + // The default error event sample rate for all SDKs is 1.0 (send all). + // + // In Go, the zero value (default) for float64 is 0.0, which means that + // constructing a client with NewClient(ClientOptions{}), or, equivalently, + // initializing the SDK with Init(ClientOptions{}) without an explicit + // SampleRate would drop all events. + // + // To retain the desired default behavior, we exceptionally flip SampleRate + // from 0.0 to 1.0 here. Setting the sample rate to 0.0 is not very useful + // anyway, and the same end result can be achieved in many other ways like + // not initializing the SDK, setting the DSN to the empty string or using an + // event processor that always returns nil. + // + // An alternative API could be such that default options don't need to be + // the same as Go's zero values, for example using the Functional Options + // pattern. That would either require a breaking change if we want to reuse + // the obvious NewClient name, or a new function as an alternative + // constructor. + if options.SampleRate == 0.0 { + options.SampleRate = 1.0 + } + + if options.Debug { + debugWriter := options.DebugWriter + if debugWriter == nil { + debugWriter = os.Stderr + } + debuglog.SetOutput(debugWriter) + } + + if options.Dsn == "" { + options.Dsn = os.Getenv("SENTRY_DSN") + } + + if options.Release == "" { + options.Release = defaultRelease() + } + + if options.Environment == "" { + options.Environment = os.Getenv("SENTRY_ENVIRONMENT") + } + + if options.MaxErrorDepth == 0 { + options.MaxErrorDepth = maxErrorDepth + } + + if options.MaxSpans == 0 { + options.MaxSpans = defaultMaxSpans + } + + if options.TraceIgnoreStatusCodes == nil { + options.TraceIgnoreStatusCodes = [][]int{{404}} + } + + resolvedDataCollection := snapshotDataCollection(options.DataCollection, options.SendDefaultPII) + options.DataCollection = cloneDataCollection(&resolvedDataCollection) + + // SENTRYGODEBUG is a comma-separated list of key=value pairs (similar + // to GODEBUG). It is not a supported feature: recognized debug options + // may change any time. + // + // The intended public is SDK developers. It is orthogonal to + // options.Debug, which is also available for SDK users. + dbg := strings.Split(os.Getenv("SENTRYGODEBUG"), ",") + sort.Strings(dbg) + // dbgOpt returns true when the given debug option is enabled, for + // example SENTRYGODEBUG=someopt=1. + dbgOpt := func(opt string) bool { + s := opt + "=1" + return dbg[sort.SearchStrings(dbg, s)%len(dbg)] == s + } + if dbgOpt("httpdump") || dbgOpt("httptrace") { + options.HTTPTransport = &debug.Transport{ + RoundTripper: http.DefaultTransport, + Output: os.Stderr, + Dump: dbgOpt("httpdump"), + Trace: dbgOpt("httptrace"), + } + } + + var dsn *protocol.Dsn + if options.Dsn != "" { + var err error + dsn, err = protocol.NewDsn(options.Dsn) + if err != nil { + return nil, err + } + } + + client := Client{ + options: options, + dsn: dsn, + sdkIdentifier: sdkIdentifier, + sdkVersion: SDKVersion, + reportRecorder: report.NoopRecorder(), + reportProvider: report.NoopProvider(), + } + + if !options.DisableClientReports { + a := report.NewAggregator() + client.reportRecorder = a + client.reportProvider = a + } + + // We currently disallow using custom Transport with the new Telemetry Processor, due to the difference in transport signatures. + // The option should be enabled when the new Transport interface signature changes. + if !options.DisableTelemetryBuffer && client.options.Transport == nil { + client.setupTelemetryProcessor() + } else { + if client.options.Transport != nil { + debuglog.Println("Cannot enable Telemetry Processor with custom Transport: fallback to old transport") + } + client.setupTransport() + + client.batchLogger = newLogBatchProcessor(&client) + client.batchLogger.Start() + client.batchMeter = newMetricBatchProcessor(&client) + client.batchMeter.Start() + } + client.setupIntegrations() + if options.OrgID != 0 && client.dsn != nil { + client.dsn.SetOrgID(options.OrgID) + } + + return &client, nil +} + +func (client *Client) setupTransport() { + opts := client.options + transport := opts.Transport + + if transport == nil { + if opts.Dsn == "" { + transport = new(noopTransport) + } else { + httpTransport := NewHTTPTransport() + httpTransport.recorder = client.reportRecorder + httpTransport.provider = client.reportProvider + transport = httpTransport + } + } else { + // For known transport types, inject the client report interfaces. + switch tr := transport.(type) { + case *HTTPTransport: + tr.recorder = client.reportRecorder + tr.provider = client.reportProvider + case *HTTPSyncTransport: + tr.recorder = client.reportRecorder + tr.provider = client.reportProvider + case *internalAsyncTransportAdapter: + tr.recorder = client.reportRecorder + tr.provider = client.reportProvider + } + } + + transport.Configure(opts) + client.Transport = transport +} + +func (client *Client) sdkInfo() *protocol.SdkInfo { + return &protocol.SdkInfo{ + Name: client.GetSDKIdentifier(), + Version: SDKVersion, + Integrations: client.listIntegrations(), + Packages: []SdkPackage{{ + Name: "sentry-go", + Version: SDKVersion, + }}, + } +} + +func (client *Client) setupTelemetryProcessor() { + transport := httpInternal.NewAsyncTransport(httpInternal.TransportOptions{ + Dsn: client.options.Dsn, + HTTPClient: client.options.HTTPClient, + HTTPTransport: client.options.HTTPTransport, + HTTPProxy: client.options.HTTPProxy, + HTTPSProxy: client.options.HTTPSProxy, + CaCerts: client.options.CaCerts, + Recorder: client.reportRecorder, + Provider: client.reportProvider, + SdkInfo: client.sdkInfo, + }) + client.Transport = &internalAsyncTransportAdapter{transport: transport} + + buffers := map[ratelimit.Category]telemetry.Buffer[protocol.TelemetryItem]{ + ratelimit.CategoryError: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryError, 100, telemetry.OverflowPolicyDropOldest, 1, 0, client.reportRecorder), + ratelimit.CategoryTransaction: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryTransaction, 1000, telemetry.OverflowPolicyDropOldest, 1, 0, client.reportRecorder), + ratelimit.CategoryLog: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryLog, 10*100, telemetry.OverflowPolicyDropOldest, 100, 5*time.Second, client.reportRecorder), + ratelimit.CategoryMonitor: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryMonitor, 100, telemetry.OverflowPolicyDropOldest, 1, 0, client.reportRecorder), + ratelimit.CategoryTraceMetric: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryTraceMetric, 10*100, telemetry.OverflowPolicyDropOldest, 100, 5*time.Second, client.reportRecorder), + } + + client.telemetryProcessor = telemetry.NewProcessor(buffers, transport, client.dsn, client.sdkInfo, client.reportRecorder) +} + +func (client *Client) setupIntegrations() { + integrations := []Integration{ + new(environmentIntegration), + new(modulesIntegration), + new(ignoreErrorsIntegration), + new(ignoreTransactionsIntegration), + new(globalTagsIntegration), + } + + if client.options.Integrations != nil { + integrations = client.options.Integrations(integrations) + } + + for _, integration := range integrations { + if client.integrationAlreadyInstalled(integration.Name()) { + debuglog.Printf("Integration %s is already installed\n", integration.Name()) + continue + } + client.integrations = append(client.integrations, integration) + integration.SetupOnce(client) + debuglog.Printf("Integration installed: %s\n", integration.Name()) + } + + sort.Slice(client.integrations, func(i, j int) bool { + return client.integrations[i].Name() < client.integrations[j].Name() + }) +} + +// AddEventProcessor adds an event processor to the client. It must not be +// called from concurrent goroutines. Most users will prefer to use +// ClientOptions.BeforeSend or Scope.AddEventProcessor instead. +// +// Note that typical programs have only a single client created by Init and the +// client is shared among multiple hubs, one per goroutine, such that adding an +// event processor to the client affects all hubs that share the client. +func (client *Client) AddEventProcessor(processor EventProcessor) { + client.eventProcessors = append(client.eventProcessors, processor) +} + +// SetExternalContextTraceResolver installs a resolver used to extract trace/span IDs +// from external context implementations. +// +// This is intended for integrations such as OpenTelemetry. +func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) { + client.mu.Lock() + defer client.mu.Unlock() + + client.externalTraceResolver = resolver +} + +func (client *Client) externalTraceContextFromContext(ctx context.Context) (TraceID, SpanID, bool) { + if ctx == nil { + return TraceID{}, SpanID{}, false + } + + client.mu.RLock() + resolver := client.externalTraceResolver + client.mu.RUnlock() + + if resolver == nil { + return TraceID{}, SpanID{}, false + } + + return resolver(ctx) +} + +// Options return ClientOptions for the current Client. +func (client *Client) Options() ClientOptions { + // Note: internally, consider using `client.options` instead of `client.Options()` to avoid copying the object each time. + opts := client.options + opts.DataCollection = cloneDataCollection(client.options.DataCollection) + return opts +} + +// GetDataCollection returns a copy of the resolved data collection +// configuration used by the client. +func (client *Client) GetDataCollection() DataCollection { + if client == nil || client.options.DataCollection == nil { + return DataCollection{} + } + return *cloneDataCollection(client.options.DataCollection) +} + +// CaptureMessage captures an arbitrary message. +func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID { + event := client.EventFromMessage(message, LevelInfo) + return client.CaptureEvent(event, hint, scope) +} + +// CaptureException captures an error. +func (client *Client) CaptureException(exception error, hint *EventHint, scope EventModifier) *EventID { + event := client.EventFromException(exception, LevelError) + return client.CaptureEvent(event, hint, scope) +} + +// CaptureCheckIn captures a check in. +func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig, scope EventModifier) *EventID { + event := client.EventFromCheckIn(checkIn, monitorConfig) + if event != nil && event.CheckIn != nil { + client.CaptureEvent(event, nil, scope) + return &event.CheckIn.ID + } + return nil +} + +// CaptureEvent captures an event on the currently active client if any. +// +// The event must already be assembled. Typically, code would instead use +// the utility methods like CaptureException. The return value is the +// event ID. In case Sentry is disabled or event was dropped, the return value will be nil. +func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID { + return client.processEvent(event, hint, scope) +} + +func (client *Client) captureLog(log *Log, _ *Scope) bool { + if log == nil { + return false + } + + if client.options.BeforeSendLog != nil { + approxSize := log.ApproximateSize() + log = client.options.BeforeSendLog(log) + if log == nil { + debuglog.Println("Log dropped due to BeforeSendLog callback.") + client.reportRecorder.RecordOne(report.ReasonBeforeSend, ratelimit.CategoryLog) + client.reportRecorder.Record(report.ReasonBeforeSend, ratelimit.CategoryLogByte, int64(approxSize)) + return false + } + } + + if client.telemetryProcessor != nil { + if !client.telemetryProcessor.Add(log) { + debuglog.Print("Dropping log: telemetry buffer full or category missing") + // Note: processor tracks client report + return false + } + } else if client.batchLogger != nil { + if !client.batchLogger.Send(log) { + debuglog.Printf("Dropping log [%s]: buffer full", log.Level) + client.reportRecorder.RecordOne(report.ReasonBufferOverflow, ratelimit.CategoryLog) + client.reportRecorder.Record(report.ReasonBufferOverflow, ratelimit.CategoryLogByte, int64(log.ApproximateSize())) + return false + } + } + + return true +} + +func (client *Client) captureMetric(metric *Metric, _ *Scope) bool { + if metric == nil { + return false + } + + if client.options.BeforeSendMetric != nil { + metric = client.options.BeforeSendMetric(metric) + if metric == nil { + debuglog.Println("Metric dropped due to BeforeSendMetric callback.") + client.reportRecorder.RecordOne(report.ReasonBeforeSend, ratelimit.CategoryTraceMetric) + return false + } + } + + if client.telemetryProcessor != nil { + if !client.telemetryProcessor.Add(metric) { + debuglog.Printf("Dropping metric: telemetry buffer full or category missing") + // Note: processor tracks client report + return false + } + } else if client.batchMeter != nil { + if !client.batchMeter.Send(metric) { + debuglog.Printf("Dropping metric %q: buffer full", metric.Name) + client.reportRecorder.RecordOne(report.ReasonBufferOverflow, ratelimit.CategoryTraceMetric) + return false + } + } + + return true +} + +// Recover captures a panic. +// Returns EventID if successfully, or nil if there's no error to recover from. +func (client *Client) Recover(err any, hint *EventHint, scope EventModifier) *EventID { + if err == nil { + err = recover() + } + + // Normally we would not pass a nil Context, but RecoverWithContext doesn't + // use the Context for communicating deadline nor cancelation. All it does + // is store the Context in the EventHint and there nil means the Context is + // not available. + // nolint: staticcheck + return client.RecoverWithContext(nil, err, hint, scope) +} + +// RecoverWithContext captures a panic and passes relevant context object. +// Returns EventID if successfully, or nil if there's no error to recover from. +func (client *Client) RecoverWithContext( + ctx context.Context, + err any, + hint *EventHint, + scope EventModifier, +) *EventID { + if err == nil { + err = recover() + } + if err == nil { + return nil + } + + if ctx != nil { + if hint == nil { + hint = &EventHint{} + } + if hint.Context == nil { + hint.Context = ctx + } + } + + var event *Event + switch err := err.(type) { + case error: + event = client.EventFromException(err, LevelFatal) + case string: + event = client.EventFromMessage(err, LevelFatal) + default: + event = client.EventFromMessage(fmt.Sprintf("%#v", err), LevelFatal) + } + return client.CaptureEvent(event, hint, scope) +} + +// Flush waits until the underlying Transport sends any buffered events to the +// Sentry server, blocking for at most the given timeout. It returns false if +// the timeout was reached. In that case, some events may not have been sent. +// +// Flush should be called before terminating the program to avoid +// unintentionally dropping events. +// +// Do not call Flush indiscriminately after every call to CaptureEvent, +// CaptureException or CaptureMessage. Instead, to have the SDK send events over +// the network synchronously, configure it to use the HTTPSyncTransport in the +// call to Init. +func (client *Client) Flush(timeout time.Duration) bool { + if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return client.FlushWithContext(ctx) + } + return client.Transport.Flush(timeout) +} + +// FlushWithContext waits until the underlying Transport sends any buffered events +// to the Sentry server, blocking for at most the duration specified by the context. +// It returns false if the context is canceled before the events are sent. In such a case, +// some events may not be delivered. +// +// FlushWithContext should be called before terminating the program to ensure no +// events are unintentionally dropped. +// +// Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent, +// CaptureException, or CaptureMessage. To send events synchronously over the network, +// configure the SDK to use HTTPSyncTransport during initialization with Init. + +func (client *Client) FlushWithContext(ctx context.Context) bool { + if client.batchLogger != nil { + client.batchLogger.Flush(ctx.Done()) + } + if client.batchMeter != nil { + client.batchMeter.Flush(ctx.Done()) + } + if client.telemetryProcessor != nil { + return client.telemetryProcessor.FlushWithContext(ctx) + } + return client.Transport.FlushWithContext(ctx) +} + +// Close clean up underlying Transport resources. +// +// Close should be called after Flush and before terminating the program +// otherwise some events may be lost. +func (client *Client) Close() { + if client.telemetryProcessor != nil { + client.telemetryProcessor.Close(5 * time.Second) + } + if client.batchLogger != nil { + client.batchLogger.Shutdown() + } + if client.batchMeter != nil { + client.batchMeter.Shutdown() + } + client.Transport.Close() +} + +// EventFromMessage creates an event from the given message string. +func (client *Client) EventFromMessage(message string, level Level) *Event { + if message == "" { + err := usageError{fmt.Errorf("%s called with empty message", callerFunctionName())} + return client.EventFromException(err, level) + } + event := NewEvent() + event.Level = level + event.Message = message + + if client.options.AttachStacktrace { + event.Threads = []Thread{{ + Stacktrace: NewStacktrace(), + Crashed: false, + Current: true, + }} + } + + return event +} + +// EventFromException creates a new Sentry event from the given `error` instance. +func (client *Client) EventFromException(exception error, level Level) *Event { + event := NewEvent() + event.Level = level + + err := exception + if err == nil { + err = usageError{fmt.Errorf("%s called with nil error", callerFunctionName())} + } + + event.SetException(err, client.options.MaxErrorDepth) + + return event +} + +// EventFromCheckIn creates a new Sentry event from the given `check_in` instance. +func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *Event { + if checkIn == nil { + return nil + } + + event := NewEvent() + event.Type = checkInType + + var checkInID EventID + if checkIn.ID == "" { + checkInID = EventID(uuid()) + } else { + checkInID = checkIn.ID + } + + event.CheckIn = &CheckIn{ + ID: checkInID, + MonitorSlug: checkIn.MonitorSlug, + Status: checkIn.Status, + Duration: checkIn.Duration, + } + event.MonitorConfig = monitorConfig + + return event +} + +func (client *Client) SetSDKIdentifier(identifier string) { + client.mu.Lock() + defer client.mu.Unlock() + + client.sdkIdentifier = identifier +} + +func (client *Client) GetSDKIdentifier() string { + client.mu.RLock() + defer client.mu.RUnlock() + + return client.sdkIdentifier +} + +func (client *Client) processEvent(event *Event, hint *EventHint, scope EventModifier) *EventID { + if event == nil { + err := usageError{fmt.Errorf("%s called with nil event", callerFunctionName())} + return client.CaptureException(err, hint, scope) + } + + // Transactions are sampled by options.TracesSampleRate or + // options.TracesSampler when they are started. Other events + // (errors, messages) are sampled here. Does not apply to check-ins. + if event.Type != transactionType && event.Type != checkInType && !sample(client.options.SampleRate) { + debuglog.Println("Event dropped due to SampleRate hit.") + client.reportRecorder.RecordOne(report.ReasonSampleRate, event.toCategory()) + return nil + } + + if event = client.prepareEvent(event, hint, scope); event == nil { + return nil + } + + // Apply beforeSend* processors + if hint == nil { + hint = &EventHint{} + } + switch event.Type { + case transactionType: + if client.options.BeforeSendTransaction != nil { + spanCountBefore := event.GetSpanCount() + event = client.options.BeforeSendTransaction(event, hint) + if event == nil { + debuglog.Println("Transaction dropped due to BeforeSendTransaction callback.") + client.reportRecorder.RecordOne(report.ReasonBeforeSend, ratelimit.CategoryTransaction) + client.reportRecorder.Record(report.ReasonBeforeSend, ratelimit.CategorySpan, int64(spanCountBefore)) + return nil + } + // Track spans removed by the callback + if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 { + client.reportRecorder.Record(report.ReasonBeforeSend, ratelimit.CategorySpan, int64(droppedSpans)) + } + } + case checkInType: // not a default case, since we shouldn't apply BeforeSend on check-in events + default: + if client.options.BeforeSend != nil { + if event = client.options.BeforeSend(event, hint); event == nil { + debuglog.Println("Event dropped due to BeforeSend callback.") + client.reportRecorder.RecordOne(report.ReasonBeforeSend, ratelimit.CategoryError) + return nil + } + } + } + + if client.telemetryProcessor != nil { + if !client.telemetryProcessor.Add(event) { + debuglog.Println("Event dropped: telemetry buffer full or unavailable") + } + } else { + client.Transport.SendEvent(event) + } + + return &event.EventID +} + +func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventModifier) *Event { + if event.EventID == "" { + // TODO set EventID when the event is created, same as in other SDKs. It's necessary for profileTransaction.ID. + event.EventID = EventID(uuid()) + } + + if event.Timestamp.IsZero() { + event.Timestamp = time.Now() + } + + if event.Level == "" { + event.Level = LevelInfo + } + + if event.ServerName == "" { + event.ServerName = client.options.ServerName + + if event.ServerName == "" { + event.ServerName = hostname + } + } + + if event.Release == "" { + event.Release = client.options.Release + } + + if event.Dist == "" { + event.Dist = client.options.Dist + } + + if event.Environment == "" { + event.Environment = client.options.Environment + } + + event.Platform = "go" + event.Sdk = SdkInfo{ + Name: client.GetSDKIdentifier(), + Version: SDKVersion, + Integrations: client.listIntegrations(), + Packages: []SdkPackage{{ + Name: "sentry-go", + Version: SDKVersion, + }}, + } + + if scope != nil { + event = scope.ApplyToEvent(event, hint, client) + if event == nil { + return nil + } + } + + for _, processor := range client.eventProcessors { + id := event.EventID + category := event.toCategory() + spanCountBefore := event.GetSpanCount() + event = processor(event, hint) + if event == nil { + debuglog.Printf("Event dropped by one of the Client EventProcessors: %s\n", id) + client.reportRecorder.RecordOne(report.ReasonEventProcessor, category) + if category == ratelimit.CategoryTransaction { + client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore)) + } + return nil + } + // Track spans removed by the processor + if category == ratelimit.CategoryTransaction { + if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 { + client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans)) + } + } + } + + for _, processor := range globalEventProcessors { + id := event.EventID + category := event.toCategory() + spanCountBefore := event.GetSpanCount() + event = processor(event, hint) + if event == nil { + debuglog.Printf("Event dropped by one of the Global EventProcessors: %s\n", id) + client.reportRecorder.RecordOne(report.ReasonEventProcessor, category) + if category == ratelimit.CategoryTransaction { + client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore)) + } + return nil + } + // Track spans removed by the processor + if category == ratelimit.CategoryTransaction { + if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 { + client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans)) + } + } + } + + return event +} + +func (client *Client) listIntegrations() []string { + integrations := make([]string, len(client.integrations)) + for i, integration := range client.integrations { + integrations[i] = integration.Name() + } + return integrations +} + +func (client *Client) integrationAlreadyInstalled(name string) bool { + for _, integration := range client.integrations { + if integration.Name() == name { + return true + } + } + return false +} + +// sample returns true with the given probability, which must be in the range +// [0.0, 1.0]. +func sample(probability float64) bool { + return rng.Float64() < probability +} diff --git a/vendor/github.com/getsentry/sentry-go/data_collection.go b/vendor/github.com/getsentry/sentry-go/data_collection.go new file mode 100644 index 0000000..713aba5 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/data_collection.go @@ -0,0 +1,217 @@ +package sentry + +import "slices" + +// CollectionMode controls how key-value data (headers, cookies, query params) is collected. +// +// Defaults to CollectionDenyList. +type CollectionMode int + +const ( + // CollectionDenyList keeps all keys and filters denied values. + CollectionDenyList CollectionMode = iota + + // CollectionOff disables collection of the category entirely. + CollectionOff + + // CollectionAllowList keeps all keys and sends real values only for allowed keys. + CollectionAllowList +) + +// KeyValueCollectionBehavior configures how key-value data is collected and filtered. +type KeyValueCollectionBehavior struct { + // Mode controls the collection strategy. + Mode CollectionMode + // Terms is a list of additional terms used by the active mode. + Terms []string +} + +// HeaderCollectionConfig configures how HTTP headers are collected for +// requests and responses independently. +type HeaderCollectionConfig struct { + // Request configures collection of HTTP request headers. + Request *KeyValueCollectionBehavior + // Response configures collection of HTTP response headers. + Response *KeyValueCollectionBehavior +} + +// BodyType identifies a category of HTTP body to collect. +type BodyType string + +const ( + // BodyIncomingRequest collects bodies from incoming HTTP requests + // (server-side). + BodyIncomingRequest BodyType = "incomingRequest" + + // BodyOutgoingRequest collects bodies from outgoing HTTP requests + // (client-side). + BodyOutgoingRequest BodyType = "outgoingRequest" + + // BodyIncomingResponse collects bodies from incoming HTTP responses + // (client-side). + BodyIncomingResponse BodyType = "incomingResponse" +) + +// DataCollection configures what data the SDK collects automatically. +// All fields are optional. nil or zero-value fields use the documented +// defaults, which collect rich context for debugging while scrubbing sensitive +// values via a built-in denylist. +// +// See https://docs.sentry.io/platforms/go/configuration/options/#DataCollection +type DataCollection struct { + // UserInfo controls automatic population of user.* fields from auto-instrumentation. + // + // This does NOT gate data explicitly set via Scope.SetUser(); that is + // always attached. Defaults to true. + UserInfo Option[bool] + + // Cookies configures collection of HTTP cookies. + // + // Defaults to using the built-in DenyList. + Cookies *KeyValueCollectionBehavior + + // HTTPHeaders configures collection of HTTP request and response headers + // independently. + // + // Defaults to both request and response using the built-in DenyList. + HTTPHeaders *HeaderCollectionConfig + + // HTTPBodies controls which HTTP body types are collected. + // + // Defaults to collecting all valid body types. + HTTPBodies []BodyType + + // QueryParams configures collection of URL query parameters. + // + // Defaults to using the built-in DenyList. + QueryParams *KeyValueCollectionBehavior + + // sensitiveTerms is the deny-list used for built-in sensitive-key + // scrubbing. + sensitiveTerms []string +} + +// cloneKeyValueCollectionBehavior returns a deep copy of b. +func cloneKeyValueCollectionBehavior(b *KeyValueCollectionBehavior) *KeyValueCollectionBehavior { + if b == nil { + return nil + } + cloned := &KeyValueCollectionBehavior{Mode: b.Mode} + if b.Terms != nil { + cloned.Terms = slices.Clone(b.Terms) + } + return cloned +} + +// cloneHeaderCollectionConfig returns a deep copy of c. +func cloneHeaderCollectionConfig(c *HeaderCollectionConfig) *HeaderCollectionConfig { + if c == nil { + return nil + } + return &HeaderCollectionConfig{ + Request: cloneKeyValueCollectionBehavior(c.Request), + Response: cloneKeyValueCollectionBehavior(c.Response), + } +} + +// cloneDataCollection returns a deep copy of dc. +func cloneDataCollection(dc *DataCollection) *DataCollection { + if dc == nil { + return nil + } + cloned := &DataCollection{ + UserInfo: dc.UserInfo, + Cookies: cloneKeyValueCollectionBehavior(dc.Cookies), + HTTPHeaders: cloneHeaderCollectionConfig(dc.HTTPHeaders), + QueryParams: cloneKeyValueCollectionBehavior(dc.QueryParams), + sensitiveTerms: dc.sensitiveTerms, + } + if dc.HTTPBodies != nil { + cloned.HTTPBodies = slices.Clone(dc.HTTPBodies) + } + return cloned +} + +// allBodyTypes returns all valid body types. +func allBodyTypes() []BodyType { + return []BodyType{ + BodyIncomingRequest, + BodyOutgoingRequest, + BodyIncomingResponse, + } +} + +// snapshotDataCollection builds a fully-populated DataCollection based on given options. +// It handles any unspecified values by applying the defaults. If the given opts are nil, this +// provides a best-effort snapshot to align with sendDefaultPII for backwards compatibility. +func snapshotDataCollection(opts *DataCollection, sendDefaultPII bool) DataCollection { + if opts == nil { + return legacyDataCollection(sendDefaultPII) + } + return resolveDataCollection(opts) +} + +func resolveDataCollection(dc *DataCollection) DataCollection { + var resolved DataCollection + if cloned := cloneDataCollection(dc); cloned != nil { + resolved = *cloned + } + + if !resolved.UserInfo.IsSet { + resolved.UserInfo = Set(true) + } + if resolved.Cookies == nil { + resolved.Cookies = &KeyValueCollectionBehavior{} + } + if resolved.HTTPHeaders == nil { + resolved.HTTPHeaders = &HeaderCollectionConfig{} + } + if resolved.HTTPHeaders.Request == nil { + resolved.HTTPHeaders.Request = &KeyValueCollectionBehavior{} + } + if resolved.HTTPHeaders.Response == nil { + resolved.HTTPHeaders.Response = &KeyValueCollectionBehavior{} + } + if resolved.HTTPBodies == nil { + resolved.HTTPBodies = allBodyTypes() + } + if resolved.QueryParams == nil { + resolved.QueryParams = &KeyValueCollectionBehavior{} + } + return resolved +} + +func legacyDataCollection(sendDefaultPII bool) DataCollection { + if sendDefaultPII { + return resolveDataCollection(&DataCollection{ + UserInfo: Set(true), + Cookies: &KeyValueCollectionBehavior{}, + HTTPHeaders: &HeaderCollectionConfig{Request: &KeyValueCollectionBehavior{}, Response: &KeyValueCollectionBehavior{}}, + HTTPBodies: allBodyTypes(), + QueryParams: &KeyValueCollectionBehavior{}, + }) + } + + return resolveDataCollection(&DataCollection{ + UserInfo: Set(false), + HTTPBodies: []BodyType{}, + Cookies: &KeyValueCollectionBehavior{Mode: CollectionOff}, + HTTPHeaders: &HeaderCollectionConfig{ + Request: &KeyValueCollectionBehavior{Mode: CollectionDenyList}, + Response: &KeyValueCollectionBehavior{Mode: CollectionDenyList}, + }, + QueryParams: &KeyValueCollectionBehavior{Mode: CollectionDenyList}, + sensitiveTerms: extendedSensitiveTerms, + }) +} + +// extendedSensitiveTerms are additional privacy terms that cover +// user-identifying data such as IP forwarding headers and user IDs. Used for +// backwards compatibility with SendDefaultPII=false. +var extendedSensitiveTerms = []string{ + "forwarded", + "-ip", + "remote-", + "via", + "-user", +} diff --git a/vendor/github.com/getsentry/sentry-go/data_collection_filter.go b/vendor/github.com/getsentry/sentry-go/data_collection_filter.go new file mode 100644 index 0000000..438093a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/data_collection_filter.go @@ -0,0 +1,308 @@ +package sentry + +import ( + "encoding/json" + "net/url" + "strings" +) + +// defaultSensitiveTerms is the canonical list of case-insensitive, +// partial-match terms used for scrubbing. +// +// See https://develop.sentry.dev/sdk/foundations/client/data-collection/#sensitive-denylist +var defaultSensitiveTerms = []string{ + "auth", + "bearer", + "credentials", + "csrf", + "identity", + "jwt", + "key", + "passwd", + "password", + "pwd", + "saml", + "secret", + "session", + "sid", + "sso", + "token", + "xsrf", +} + +// filteredValue is the replacement for sensitive values. +const filteredValue = "[Filtered]" + +// filterKeyValues applies a KeyValueCollectionBehavior to a map of key-value +// pairs. Keys are always preserved and values are replaced with "[Filtered]". +// +// Returns nil when the mode is CollectionOff. +func (dc DataCollection) filterKeyValues(data map[string]string, behavior *KeyValueCollectionBehavior) map[string]string { + if behavior == nil { + behavior = &KeyValueCollectionBehavior{} + } + if behavior.Mode == CollectionOff { + return nil + } + result := make(map[string]string, len(data)) + for k, v := range data { + if dc.shouldFilterKey(k, behavior) { + result[k] = filteredValue + } else { + result[k] = v + } + } + return result +} + +// FilterRequestHeaders applies the configured request-header collection behavior. +func (dc DataCollection) FilterRequestHeaders(headers map[string]string) map[string]string { + var behavior *KeyValueCollectionBehavior + if dc.HTTPHeaders != nil { + behavior = dc.HTTPHeaders.Request + } + return dc.filterKeyValues(headers, behavior) +} + +// FilterResponseHeaders applies the configured response-header collection behavior. +func (dc DataCollection) FilterResponseHeaders(headers map[string]string) map[string]string { + var behavior *KeyValueCollectionBehavior + if dc.HTTPHeaders != nil { + behavior = dc.HTTPHeaders.Response + } + return dc.filterKeyValues(headers, behavior) +} + +// CollectHTTPBody reports whether the given body type should be collected. +func (dc *DataCollection) CollectHTTPBody(bt BodyType) bool { + if dc == nil || dc.HTTPBodies == nil { + return true + } + for _, t := range dc.HTTPBodies { + if t == bt { + return true + } + } + return false +} + +// CollectCookies reports whether cookies should be collected. +func (dc *DataCollection) CollectCookies() bool { + return dc == nil || dc.Cookies == nil || dc.Cookies.Mode != CollectionOff +} + +// CollectQueryParams reports whether query parameters should be collected. +func (dc DataCollection) CollectQueryParams() bool { + return dc.QueryParams == nil || dc.QueryParams.Mode != CollectionOff +} + +// FilterQueryString applies the configured query-parameter collection behavior. +func (dc DataCollection) FilterQueryString(rawQuery string) string { + if rawQuery == "" { + return "" + } + values, _ := url.ParseQuery(rawQuery) + return dc.filterURLValues(values, dc.QueryParams) +} + +// FilterURL applies query-parameter filtering to u and returns its redacted string form. +func (dc DataCollection) FilterURL(u *url.URL) string { + if u == nil { + return "" + } + filtered := *u + filtered.RawQuery = dc.FilterQueryString(u.RawQuery) + return filtered.Redacted() +} + +// FilterCookies applies the configured cookie collection behavior. +func (dc DataCollection) FilterCookies(values []string) string { + parsed := parseKeyValueStrings(values, ';') + if len(parsed) == 0 { + return "" + } + filtered := dc.filterKeyValues(parsed, dc.Cookies) + if len(filtered) == 0 { + return "" + } + + parts := make([]string, 0, len(filtered)) + for key, value := range filtered { + parts = append(parts, key+"="+value) + } + return strings.Join(parts, "; ") +} + +// FilterSetCookies applies the configured cookie collection behavior to +// Set-Cookie header values. +func (dc DataCollection) FilterSetCookies(values []string) string { + filtered := make([]string, 0, len(values)) + for _, value := range values { + if cookie := dc.filterSetCookie(value); cookie != "" { + filtered = append(filtered, cookie) + } + } + return strings.Join(filtered, ", ") +} + +func (dc DataCollection) filterSetCookie(setCookie string) string { + if !dc.CollectCookies() { + return "" + } + parts := strings.Split(setCookie, ";") + name, value, ok := strings.Cut(parts[0], "=") + name = strings.TrimSpace(name) + if !ok || name == "" { + return "" + } + if dc.shouldFilterKey(name, dc.Cookies) { + value = filteredValue + } + parts[0] = name + "=" + value + + for i := 1; i < len(parts); i++ { + attribute, _, ok := strings.Cut(parts[i], "=") + if !ok { + continue + } + if name := strings.TrimSpace(attribute); name != "" && dc.shouldFilterKey(name, dc.Cookies) { + parts[i] = attribute + "=" + filteredValue + } + } + + return strings.Join(parts, ";") +} + +// FilterHTTPBody applies sensitive-key filtering to parseable HTTP body data. +// Opaque raw bodies are replaced entirely. +func (dc DataCollection) FilterHTTPBody(body []byte, contentType string) string { + if len(body) == 0 { + return "" + } + + if strings.Contains(strings.ToLower(contentType), "application/json") || looksLikeJSON(body) { + var value any + if err := json.Unmarshal(body, &value); err == nil { + filteredJSON := dc.filterJSONValue(value, nil) + filtered, err := json.Marshal(filteredJSON) + if err == nil { + return string(filtered) + } + } + } + + if strings.Contains(strings.ToLower(contentType), "application/x-www-form-urlencoded") { + if values, err := url.ParseQuery(string(body)); err == nil { + return dc.filterURLValues(values, nil) + } + } + + return filteredValue +} + +func looksLikeJSON(body []byte) bool { + trimmed := strings.TrimSpace(string(body)) + return strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") +} + +func (dc DataCollection) filterURLValues(values url.Values, behavior *KeyValueCollectionBehavior) string { + if behavior == nil { + behavior = &KeyValueCollectionBehavior{} + } + if behavior.Mode == CollectionOff { + return "" + } + for key := range values { + if dc.shouldFilterKey(key, behavior) { + values.Set(key, filteredValue) + } + } + return strings.ReplaceAll(values.Encode(), url.QueryEscape(filteredValue), filteredValue) +} + +func (dc DataCollection) filterJSONValue(value any, behavior *KeyValueCollectionBehavior) any { + return dc.filterJSONNode(value, behavior, false) +} + +// filterJSONNode recursively filters a decoded JSON value. +func (dc DataCollection) filterJSONNode(value any, behavior *KeyValueCollectionBehavior, keyed bool) any { + if behavior != nil && behavior.Mode == CollectionOff { + return nil + } + + switch value := value.(type) { + case map[string]any: + filtered := make(map[string]any, len(value)) + for key, child := range value { + if dc.shouldFilterKey(key, behavior) { + filtered[key] = filteredValue + } else { + filtered[key] = dc.filterJSONNode(child, behavior, true) + } + } + return filtered + case []any: + filtered := make([]any, len(value)) + for i, child := range value { + filtered[i] = dc.filterJSONNode(child, behavior, keyed) + } + return filtered + default: + if !keyed { + return filteredValue + } + return value + } +} + +// shouldFilterKey reports whether a key's value should be redacted under the +// given behavior. It combines the built-in sensitive terms with the behavior's +// user-provided terms. +func (dc DataCollection) shouldFilterKey(key string, behavior *KeyValueCollectionBehavior) bool { + if behavior == nil { + behavior = &KeyValueCollectionBehavior{} + } + + sensitive := matchesDenyTerms(key, defaultSensitiveTerms) || matchesDenyTerms(key, dc.sensitiveTerms) + + switch behavior.Mode { + case CollectionOff: + return true + case CollectionAllowList: + return sensitive || !matchesDenyTerms(key, behavior.Terms) + default: + return sensitive || matchesDenyTerms(key, behavior.Terms) + } +} + +// matchesDenyTerms reports whether the key (case-insensitive) contains any of +// the given terms as a substring. +func matchesDenyTerms(key string, terms []string) bool { + lower := strings.ToLower(key) + for _, term := range terms { + if strings.Contains(lower, strings.ToLower(term)) { + return true + } + } + return false +} + +// parseKeyValueStrings splits strings like "a=1; b=2" into a map. +// Malformed parts without '=' and parts with empty keys are skipped. +func parseKeyValueStrings(values []string, separator rune) map[string]string { + result := make(map[string]string) + for _, value := range values { + for _, part := range strings.Split(value, string(separator)) { + part = strings.TrimSpace(part) + if part == "" { + continue + } + key, value, ok := strings.Cut(part, "=") + if !ok || strings.TrimSpace(key) == "" { + continue + } + result[key] = value + } + } + return result +} diff --git a/vendor/github.com/getsentry/sentry-go/doc.go b/vendor/github.com/getsentry/sentry-go/doc.go new file mode 100644 index 0000000..973020a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/doc.go @@ -0,0 +1,6 @@ +/* +Package repository: https://github.com/getsentry/sentry-go/ + +For more information about Sentry and SDK features, please have a look at the official documentation site: https://docs.sentry.io/platforms/go/ +*/ +package sentry diff --git a/vendor/github.com/getsentry/sentry-go/dsn.go b/vendor/github.com/getsentry/sentry-go/dsn.go new file mode 100644 index 0000000..64b6f05 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/dsn.go @@ -0,0 +1,37 @@ +package sentry + +import ( + "github.com/getsentry/sentry-go/internal/protocol" +) + +// Re-export protocol types to maintain public API compatibility + +// Dsn is used as the remote address source to client transport. +type Dsn struct { + protocol.Dsn +} + +// DsnParseError represents an error that occurs if a Sentry +// DSN cannot be parsed. +type DsnParseError = protocol.DsnParseError + +// NewDsn creates a Dsn by parsing rawURL. Most users will never call this +// function directly. It is provided for use in custom Transport +// implementations. +func NewDsn(rawURL string) (*Dsn, error) { + protocolDsn, err := protocol.NewDsn(rawURL) + if err != nil { + return nil, err + } + return &Dsn{Dsn: *protocolDsn}, nil +} + +// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events +// to the /store endpoint. +// +// Deprecated: This method shall only be used if you want to implement your own transport that sends events to +// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate +// against the /envelope endpoint are added automatically. +func (dsn Dsn) RequestHeaders() map[string]string { + return dsn.Dsn.RequestHeaders(SDKVersion) +} diff --git a/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go new file mode 100644 index 0000000..a257f6f --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/dynamic_sampling_context.go @@ -0,0 +1,160 @@ +package sentry + +import ( + "strconv" + "strings" + + "github.com/getsentry/sentry-go/internal/otel/baggage" +) + +const ( + sentryPrefix = "sentry-" +) + +// DynamicSamplingContext holds information about the current event that can be used to make dynamic sampling decisions. +type DynamicSamplingContext struct { + Entries map[string]string + Frozen bool +} + +func DynamicSamplingContextFromHeader(header []byte) (DynamicSamplingContext, error) { + bag, err := baggage.Parse(string(header)) + if err != nil { + return DynamicSamplingContext{}, err + } + + entries := map[string]string{} + for _, member := range bag.Members() { + // We only store baggage members if their key starts with "sentry-". + if k, v := member.Key(), member.Value(); strings.HasPrefix(k, sentryPrefix) { + entries[strings.TrimPrefix(k, sentryPrefix)] = v + } + } + + return DynamicSamplingContext{ + Entries: entries, + // If there's at least one Sentry value, we consider the DSC frozen + Frozen: len(entries) > 0, + }, nil +} + +func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext { + hub := hubFromContext(span.Context()) + scope := hub.Scope() + client := hub.Client() + + if client == nil || scope == nil { + return DynamicSamplingContext{ + Entries: map[string]string{}, + Frozen: false, + } + } + + entries := make(map[string]string) + + if traceID := span.TraceID.String(); traceID != "" { + entries["trace_id"] = traceID + } + if sampleRate := span.sampleRate; sampleRate != 0 { + entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) + } + + if dsn := client.dsn; dsn != nil { + if publicKey := dsn.GetPublicKey(); publicKey != "" { + entries["public_key"] = publicKey + } + if orgID := dsn.GetOrgID(); orgID != 0 { + entries["org_id"] = strconv.FormatUint(orgID, 10) + } + } + if release := client.options.Release; release != "" { + entries["release"] = release + } + if environment := client.options.Environment; environment != "" { + entries["environment"] = environment + } + + // Only include the transaction name if it's of good quality (not empty and not SourceURL) + if span.Source != "" && span.Source != SourceURL { + if span.IsTransaction() { + entries["transaction"] = span.Name + } + } + + entries["sampled"] = strconv.FormatBool(span.Sampled.Bool()) + + return DynamicSamplingContext{Entries: entries, Frozen: true} +} + +func (d DynamicSamplingContext) HasEntries() bool { + return len(d.Entries) > 0 +} + +func (d DynamicSamplingContext) IsFrozen() bool { + return d.Frozen +} + +func (d DynamicSamplingContext) String() string { + members := []baggage.Member{} + for k, entry := range d.Entries { + member, err := baggage.NewMember(sentryPrefix+k, entry) + if err != nil { + continue + } + members = append(members, member) + } + + if len(members) == 0 { + return "" + } + + baggage, err := baggage.New(members...) + if err != nil { + return "" + } + + return baggage.String() +} + +// DynamicSamplingContextFromScope Constructs a new DynamicSamplingContext using a scope and client. Accessing +// fields on the scope are not thread safe, and this function should only be +// called within scope methods. +func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext { + entries := map[string]string{} + + if client == nil || scope == nil { + return DynamicSamplingContext{ + Entries: entries, + Frozen: false, + } + } + + propagationContext := scope.propagationContext + + if traceID := propagationContext.TraceID.String(); traceID != "" { + entries["trace_id"] = traceID + } + if sampleRate := client.options.TracesSampleRate; sampleRate != 0 { + entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) + } + + if dsn := client.dsn; dsn != nil { + if publicKey := dsn.GetPublicKey(); publicKey != "" { + entries["public_key"] = publicKey + } + if orgID := dsn.GetOrgID(); orgID != 0 { + entries["org_id"] = strconv.FormatUint(orgID, 10) + } + } + if release := client.options.Release; release != "" { + entries["release"] = release + } + if environment := client.options.Environment; environment != "" { + entries["environment"] = environment + } + + return DynamicSamplingContext{ + Entries: entries, + Frozen: true, + } +} diff --git a/vendor/github.com/getsentry/sentry-go/exception.go b/vendor/github.com/getsentry/sentry-go/exception.go new file mode 100644 index 0000000..f7ef4a0 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/exception.go @@ -0,0 +1,129 @@ +package sentry + +import ( + "fmt" + "reflect" + "slices" +) + +const ( + MechanismTypeGeneric string = "generic" + MechanismTypeChained string = "chained" + MechanismTypeUnwrap string = "unwrap" + MechanismSourceCause string = "cause" +) + +type visited struct { + ptrs map[uintptr]struct{} + msgs map[string]struct{} +} + +func (v *visited) seenError(err error) bool { + t := reflect.ValueOf(err) + if t.Kind() == reflect.Ptr && !t.IsNil() { + ptr := t.Pointer() + if _, ok := v.ptrs[ptr]; ok { + return true + } + v.ptrs[ptr] = struct{}{} + return false + } + + key := t.String() + err.Error() + if _, ok := v.msgs[key]; ok { + return true + } + v.msgs[key] = struct{}{} + return false +} + +func convertErrorToExceptions(err error, maxErrorDepth int) []Exception { + var exceptions []Exception + vis := &visited{ + ptrs: make(map[uintptr]struct{}), + msgs: make(map[string]struct{}), + } + convertErrorDFS(err, &exceptions, nil, "", vis, maxErrorDepth, 0) + + // mechanism type is used for debugging purposes, but since we can't really distinguish the origin of who invoked + // captureException, we set it to nil if the error is not chained. + if len(exceptions) == 1 { + exceptions[0].Mechanism = nil + } + + slices.Reverse(exceptions) + + // Add a trace of the current stack to the top level(outermost) error in a chain if + // it doesn't have a stack trace yet. + // We only add to the most recent error to avoid duplication and because the + // current stack is most likely unrelated to errors deeper in the chain. + if len(exceptions) > 0 && exceptions[len(exceptions)-1].Stacktrace == nil { + exceptions[len(exceptions)-1].Stacktrace = NewStacktrace() + } + + return exceptions +} + +func convertErrorDFS(err error, exceptions *[]Exception, parentID *int, source string, visited *visited, maxErrorDepth int, currentDepth int) { + if err == nil { + return + } + + if visited.seenError(err) { + return + } + + _, isExceptionGroup := err.(interface{ Unwrap() []error }) + + exception := Exception{ + Value: err.Error(), + Type: reflect.TypeOf(err).String(), + Stacktrace: ExtractStacktrace(err), + } + + currentID := len(*exceptions) + + var mechanismType string + + if parentID == nil { + mechanismType = MechanismTypeGeneric + source = "" + } else { + mechanismType = MechanismTypeChained + } + + exception.Mechanism = &Mechanism{ + Type: mechanismType, + ExceptionID: currentID, + ParentID: parentID, + Source: source, + IsExceptionGroup: isExceptionGroup, + } + + *exceptions = append(*exceptions, exception) + + if maxErrorDepth >= 0 && currentDepth >= maxErrorDepth { + return + } + + switch v := err.(type) { + case interface{ Unwrap() []error }: + unwrapped := v.Unwrap() + for i := range unwrapped { + if unwrapped[i] != nil { + childSource := fmt.Sprintf("errors[%d]", i) + convertErrorDFS(unwrapped[i], exceptions, ¤tID, childSource, visited, maxErrorDepth, currentDepth+1) + } + } + case interface{ Unwrap() error }: + unwrapped := v.Unwrap() + if unwrapped != nil { + convertErrorDFS(unwrapped, exceptions, ¤tID, MechanismTypeUnwrap, visited, maxErrorDepth, currentDepth+1) + } + case interface{ Cause() error }: + cause := v.Cause() + if cause != nil { + convertErrorDFS(cause, exceptions, ¤tID, MechanismSourceCause, visited, maxErrorDepth, currentDepth+1) + } + } +} diff --git a/vendor/github.com/getsentry/sentry-go/go.work b/vendor/github.com/getsentry/sentry-go/go.work new file mode 100644 index 0000000..a1a4f91 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/go.work @@ -0,0 +1,21 @@ +go 1.25.0 + +use ( + . + ./crosstest + ./echo + ./fasthttp + ./fiber + ./fiberv3 + ./gin + ./grpc + ./iris + ./logrus + ./negroni + ./otel + ./otel/otlp + ./slog + ./sql + ./zap + ./zerolog +) diff --git a/vendor/github.com/getsentry/sentry-go/go.work.sum b/vendor/github.com/getsentry/sentry-go/go.work.sum new file mode 100644 index 0000000..f27f5dd --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/go.work.sum @@ -0,0 +1,229 @@ +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +codeberg.org/go-fonts/liberation v0.5.0 h1:SsKoMO1v1OZmzkG2DY+7ZkCL9U+rrWI09niOLfQ5Bo0= +codeberg.org/go-fonts/liberation v0.5.0/go.mod h1:zS/2e1354/mJ4pGzIIaEtm/59VFCFnYC7YV6YdGl5GU= +codeberg.org/go-latex/latex v0.1.0 h1:hoGO86rIbWVyjtlDLzCqZPjNykpWQ9YuTZqAzPcfL3c= +codeberg.org/go-latex/latex v0.1.0/go.mod h1:LA0q/AyWIYrqVd+A9Upkgsb+IqPcmSTKc9Dny04MHMw= +codeberg.org/go-pdf/fpdf v0.10.0 h1:u+w669foDDx5Ds43mpiiayp40Ov6sZalgcPMDBcZRd4= +codeberg.org/go-pdf/fpdf v0.10.0/go.mod h1:Y0DGRAdZ0OmnZPvjbMp/1bYxmIPxm0ws4tfoPOc4LjU= +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= +github.com/PuerkitoBio/goquery v1.8.1/go.mod h1:Q8ICL1kNUJ2sXGoAhPGUdYDJvgQgHzJsnnd3H7Ho5jQ= +github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b h1:slYM766cy2nI3BwyRiyQj/Ud48djTMtMebDqepE95rw= +github.com/ajstarks/svgo v0.0.0-20211024235047-1546f124cd8b/go.mod h1:1KcenG0jGWcpt8ov532z81sp/kMMUG485J2InIOyADM= +github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss= +github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU= +github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= +github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= +github.com/campoy/embedmd v1.0.0 h1:V4kI2qTJJLf4J29RzI/MAt2c3Bl4dQSYPuflzwFH2hY= +github.com/campoy/embedmd v1.0.0/go.mod h1:oxyr9RCiSXg0M3VJ3ks0UGfp98BpSSGr0kpiX3MzVl8= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cheekybits/is v0.0.0-20150225183255-68e9c0620927 h1:SKI1/fuSdodxmNNyVBR8d7X/HuLnRpvvFO0AgyQk764= +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= +github.com/dgraph-io/badger/v2 v2.2007.4/go.mod h1:vSw/ax2qojzbN6eXHIx6KPKtCSHJN/Uz0X0VPruTIhk= +github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de h1:t0UHb5vdojIDUqktM6+xJAfScFBsVpXZmqC9dsgJmeA= +github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2 h1:tdlZCpZ/P9DhczCTSixgIKmwPv6+wP5DGjqLYw5SUiA= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/djherbis/atime v1.1.0 h1:rgwVbP/5by8BvvjBNrbh64Qz33idKT3pSnMSJsxhi0g= +github.com/djherbis/atime v1.1.0/go.mod h1:28OF6Y8s3NQWwacXc5eZTsEsiMzp7LF8MbXE+XJPdBE= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= +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= +github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo= +github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= +github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= +github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= +github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.1.0 h1:7RFti/xnNkMJnrK7D1yQ/iCIB5OrrY/54/H930kIbHA= +github.com/gobwas/ws v1.1.0/go.mod h1:nzvNcVha5eUziGrbxFCo6qFIojQHjJV5cLYIbezhfL0= +github.com/goccmack/gocc v1.0.2 h1:PHv20lcM1Erz+kovS+c07DnDFp6X5cvghndtTXuEyfE= +github.com/goccmack/gocc v1.0.2/go.mod h1:LXX2tFVUggS/Zgx/ICPOr3MLyusuM7EcbfkPvNsjdO8= +github.com/godbus/dbus/v5 v5.0.4 h1:9349emZab16e7zQvpmsbtjc18ykshndd8y2PG3sgJbA= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/golang/glog v1.2.5 h1:DrW6hGnjIhtvhOIiAKT6Psh/Kd/ldepEa81DKeiRJ5I= +github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI= +github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho= +github.com/iris-contrib/go.uuid v2.0.0+incompatible h1:XZubAYg61/JwnJNbZilGjf3b3pB80+OQg2qf6c8BfWE= +github.com/iris-contrib/go.uuid v2.0.0+incompatible/go.mod h1:iz2lgM/1UnEf1kP0L/+fafWORmlnuysV2EMP8MW+qe0= +github.com/kataras/jwt v0.1.8 h1:u71baOsYD22HWeSOg32tCHbczPjdCk7V4MMeJqTtmGk= +github.com/kataras/jwt v0.1.8/go.mod h1:Q5j2IkcIHnfwy+oNY3TVWuEBJNw0ADgCcXK9CaZwV4o= +github.com/kataras/neffos v0.0.21 h1:UwN/F44jlqdtgFI29y3VhA7IlJ4JbK3UjCbTDg1pYoo= +github.com/kataras/neffos v0.0.21/go.mod h1:FeGka8lu8cjD2H+0OpBvW8c6xXawy3fj5VX6xcIJ1Fg= +github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= +github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= +github.com/lyft/protoc-gen-star/v2 v2.0.4-0.20230330145011-496ad1ac90a4 h1:sIXJOMrYnQZJu7OB7ANSF4MYri2fTEGIsRLz6LwI4xE= +github.com/lyft/protoc-gen-star/v2 v2.0.4-0.20230330145011-496ad1ac90a4/go.mod h1:amey7yeodaJhXSbf/TlLvWiqQfLOSpEk//mLlc+axEk= +github.com/matryer/try v0.0.0-20161228173917-9ac251b645a2 h1:JAEbJn3j/FrhdWA9jW8B5ajsLIjeuEHLi8xE4fk997o= +github.com/matryer/try v0.0.0-20161228173917-9ac251b645a2/go.mod h1:0KeJpeMD6o+O4hW7qJOT7vyQPKrWmj26uf5wMc/IiIs= +github.com/mediocregopher/radix/v3 v3.8.1 h1:rOkHflVuulFKlwsLY01/M2cM2tWCjDoETcMqKbAWu1M= +github.com/mediocregopher/radix/v3 v3.8.1/go.mod h1:8FL3F6UQRXHXIBSPUs5h0RybMF8i4n7wVopoX3x7Bv8= +github.com/minio/highwayhash v1.0.2 h1:Aak5U0nElisjDCfPSG79Tgzkn2gl66NxOMspRrKnA/g= +github.com/minio/highwayhash v1.0.2/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= +github.com/nats-io/jwt/v2 v2.3.0 h1:z2mA1a7tIf5ShggOFlR1oBPgd6hGqcDYsISxZByUzdI= +github.com/nats-io/jwt/v2 v2.3.0/go.mod h1:0tqz9Hlu6bCBFLWAASKhE5vUA4c24L9KPUUgvwumE/k= +github.com/nats-io/nats.go v1.23.0 h1:lR28r7IX44WjYgdiKz9GmUeW0uh/m33uD3yEjLZ2cOE= +github.com/nats-io/nats.go v1.23.0/go.mod h1:ki/Scsa23edbh8IRZbCuNXR9TDcbvfaSijKtaqQgw+Q= +github.com/nats-io/nkeys v0.3.0 h1:cgM5tL53EvYRU+2YLXIK0G2mJtK12Ft9oeooSZMA2G8= +github.com/nats-io/nkeys v0.3.0/go.mod h1:gvUNGjVcM2IPr5rCsRsC6Wb3Hr2CQAm08dsxtV6A5y4= +github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw= +github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c h1:dAMKvw0MlJT1GshSTtih8C2gDs04w8dReiOGXrGLNoY= +github.com/philhofer/fwd v1.1.3-0.20240916144458-20a13a1f6b7c/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e h1:aoZm08cpOy4WuID//EZDgcC4zIxODThtZNPirFr42+A= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c h1:ncq/mPwQF4JjgDlrVEn3C11VoGHZN7m8qihwgMEtzYw= +github.com/power-devops/perfstat v0.0.0-20210106213030-5aafc221ea8c/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= +github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= +github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= +github.com/rogpeppe/fastuuid v1.2.0 h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi2s= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/rs/xid v1.5.0 h1:mKX4bl4iPYJtEIxp6CYiUuLQ/8DYMoz0PUdtGgMFRVc= +github.com/shirou/gopsutil/v3 v3.23.2 h1:PAWSuiAszn7IhPMBtXsbSCafej7PqUOvY6YywlQUExU= +github.com/shirou/gopsutil/v3 v3.23.2/go.mod h1:gv0aQw33GLo3pG8SiWKiQrbDzbRY1K80RyZJ7V4Th1M= +github.com/spf13/afero v1.10.0 h1:EaGW2JJh15aKOejeuJ+wpFSHnbd7GE6Wvp3TsNhb6LY= +github.com/spf13/afero v1.10.0/go.mod h1:UBogFpq8E9Hx+xc5CNTTEpTnuHVmXDwZcZcE1eb/UhQ= +github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= +github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= +github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502 h1:34icjjmqJ2HPjrSuJYEkdZ+0ItmGQAQ75cRHIiftIyE= +github.com/tdewolff/argp v0.0.0-20240126212256-acdb2fb50090 h1:ok0U1tNDp9ICD93bMrZuFtHLwDoW+5nfSfF8e/x36Y0= +github.com/tdewolff/argp v0.0.0-20240126212256-acdb2fb50090/go.mod h1:fF+gnKbmf3iMG+ErLiF+orMU/InyZIEnKVVigUjfriw= +github.com/tinylib/msgp v1.2.5 h1:WeQg1whrXRFiZusidTQqzETkRpGjFjcIhW6uqWH09po= +github.com/tinylib/msgp v1.2.5/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= +github.com/tklauser/go-sysconf v0.3.11 h1:89WgdJhk5SNwJfu+GKyYveZ4IaJ7xAkecBo+KdJV0CM= +github.com/tklauser/go-sysconf v0.3.11/go.mod h1:GqXfhXY3kiPa0nAXPDIQIWzJbMCB7AmcWpGR8lSZfqI= +github.com/tklauser/numcpus v0.6.0 h1:kebhY2Qt+3U6RNK7UqpYNA+tJ23IBEGKkB7JQBfDYms= +github.com/tklauser/numcpus v0.6.0/go.mod h1:FEZLMke0lhOUG6w2JadTzp0a+Nl8PF/GFkQ5UVIcaL4= +github.com/valyala/fasthttp v1.58.0/go.mod h1:SYXvHHaFp7QZHGKSHmoMipInhrI5StHrhDTYVEjK/Kw= +github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= +github.com/yuin/goldmark v1.4.1 h1:/vn0k+RBvwlxEmP5E7SZMqNxPhfMVFEJiykr15/0XKM= +github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= +github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +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= +golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ= +golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs= +golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY= +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= +golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +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= +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= +gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c h1:cJWOvXtcaFSGXz2F4z2AMM0VV7edDDGrxb5GLQH7ayQ= +gonum.org/v1/tools v0.0.0-20200318103217-c168b003ce8c/go.mod h1:fy6Otjqbk477ELp8IXTpw1cObQtLbRCBVonY+bTTfcM= +google.golang.org/genproto/googleapis/api v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:p3MLuOwURrGBRoEyFHBT3GjUwaCQVKeNqqWxlcISGdw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260120221211-b8f7ae30c516/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260401001100-f93e5f3e9f0f/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6 h1:ExN12ndbJ608cboPYflpTny6mXSzPrDLh0iTaVrRrds= +google.golang.org/grpc/examples v0.0.0-20250407062114-b368379ef8f6/go.mod h1:6ytKWczdvnpnO+m+JiG9NjEDzR1FJfsnmJdG7B8QVZ8= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/errgo.v2 v2.1.0 h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +rsc.io/pdf v0.1.1 h1:k1MczvYDUvJBe93bYd7wrZLLUEcLZAuF824/I4e5Xr4= diff --git a/vendor/github.com/getsentry/sentry-go/hub.go b/vendor/github.com/getsentry/sentry-go/hub.go new file mode 100644 index 0000000..15420a6 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/hub.go @@ -0,0 +1,450 @@ +package sentry + +import ( + "context" + "fmt" + "sync" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" +) + +type contextKey int + +// Keys used to store values in a Context. Use with Context.Value to access +// values stored by the SDK. +const ( + // HubContextKey is the key used to store the current Hub. + HubContextKey = contextKey(1) + // RequestContextKey is the key used to store the current http.Request. + RequestContextKey = contextKey(2) +) + +// currentHub is the initial Hub with no Client bound and an empty Scope. +var currentHub = NewHub(nil, NewScope()) + +// Hub is the central object that manages scopes and clients. +// +// This can be used to capture events and manage the scope. +// The default hub that is available automatically. +// +// In most situations developers do not need to interface the hub. Instead +// toplevel convenience functions are exposed that will automatically dispatch +// to global (CurrentHub) hub. In some situations this might not be +// possible in which case it might become necessary to manually work with the +// hub. This is for instance the case when working with async code. +type Hub struct { + mu sync.RWMutex + stack *stack + lastEventID EventID +} + +type layer struct { + // mu protects concurrent reads and writes to client. + mu sync.RWMutex + client *Client + // scope is read-only, not protected by mu. + scope *Scope +} + +// Client returns the layer's client. Safe for concurrent use. +func (l *layer) Client() *Client { + l.mu.RLock() + defer l.mu.RUnlock() + return l.client +} + +// SetClient sets the layer's client. Safe for concurrent use. +func (l *layer) SetClient(c *Client) { + l.mu.Lock() + defer l.mu.Unlock() + l.client = c +} + +type stack []*layer + +// NewHub returns an instance of a Hub with provided Client and Scope bound. +func NewHub(client *Client, scope *Scope) *Hub { + hub := Hub{ + stack: &stack{{ + client: client, + scope: scope, + }}, + } + return &hub +} + +// CurrentHub returns an instance of previously initialized Hub stored in the global namespace. +func CurrentHub() *Hub { + return currentHub +} + +// LastEventID returns the ID of the last event (error or message) captured +// through the hub and sent to the underlying transport. +// +// Transactions and events dropped by sampling or event processors do not change +// the last event ID. +// +// LastEventID is a convenience method to cover use cases in which errors are +// captured indirectly and the ID is needed. For example, it can be used as part +// of an HTTP middleware to log the ID of the last error, if any. +// +// For more flexibility, consider instead using the ClientOptions.BeforeSend +// function or event processors. +func (hub *Hub) LastEventID() EventID { + hub.mu.RLock() + defer hub.mu.RUnlock() + + return hub.lastEventID +} + +// stackTop returns the top layer of the hub stack. Valid hubs always have at +// least one layer, therefore stackTop always return a non-nil pointer. +func (hub *Hub) stackTop() *layer { + hub.mu.RLock() + defer hub.mu.RUnlock() + + stack := hub.stack + stackLen := len(*stack) + top := (*stack)[stackLen-1] + return top +} + +// Clone returns a copy of the current Hub with top-most scope and client copied over. +func (hub *Hub) Clone() *Hub { + top := hub.stackTop() + scope := top.scope + if scope != nil { + scope = scope.Clone() + } + return NewHub(top.Client(), scope) +} + +// Scope returns top-level Scope of the current Hub or nil if no Scope is bound. +func (hub *Hub) Scope() *Scope { + top := hub.stackTop() + return top.scope +} + +// Client returns top-level Client of the current Hub or nil if no Client is bound. +func (hub *Hub) Client() *Client { + top := hub.stackTop() + return top.Client() +} + +// PushScope pushes a new scope for the current Hub and reuses previously bound Client. +func (hub *Hub) PushScope() *Scope { + top := hub.stackTop() + + var scope *Scope + if top.scope != nil { + scope = top.scope.Clone() + } else { + scope = NewScope() + } + + hub.mu.Lock() + defer hub.mu.Unlock() + + *hub.stack = append(*hub.stack, &layer{ + client: top.Client(), + scope: scope, + }) + + return scope +} + +// PopScope drops the most recent scope. +// +// Calls to PopScope must be coordinated with PushScope. For most cases, using +// WithScope should be more convenient. +// +// Calls to PopScope that do not match previous calls to PushScope are silently +// ignored. +func (hub *Hub) PopScope() { + hub.mu.Lock() + defer hub.mu.Unlock() + + stack := *hub.stack + stackLen := len(stack) + if stackLen > 1 { + // Never pop the last item off the stack, the stack should always have + // at least one item. + *hub.stack = stack[0 : stackLen-1] + } +} + +// BindClient binds a new Client for the current Hub. +func (hub *Hub) BindClient(client *Client) { + top := hub.stackTop() + top.SetClient(client) +} + +// WithScope runs f in an isolated temporary scope. +// +// It is useful when extra data should be sent with a single capture call, for +// instance a different level or tags. +// +// The scope passed to f starts as a clone of the current scope and can be +// freely modified without affecting the current scope. +// +// It is a shorthand for PushScope followed by PopScope. +func (hub *Hub) WithScope(f func(scope *Scope)) { + scope := hub.PushScope() + defer hub.PopScope() + f(scope) +} + +// ConfigureScope runs f in the current scope. +// +// It is useful to set data that applies to all events that share the current +// scope. +// +// Modifying the scope affects all references to the current scope. +// +// See also WithScope for making isolated temporary changes. +func (hub *Hub) ConfigureScope(f func(scope *Scope)) { + scope := hub.Scope() + f(scope) +} + +// CaptureEvent calls the method of a same name on currently bound Client instance +// passing it a top-level Scope. +// Returns EventID if successfully, or nil if there's no Scope or Client available. +func (hub *Hub) CaptureEvent(event *Event) *EventID { + return hub.CaptureEventWithHint(event, nil) +} + +// CaptureEventWithHint is like CaptureEvent but additionally accepts an EventHint. +func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID { + client, scope := hub.Client(), hub.Scope() + if client == nil || scope == nil { + return nil + } + eventID := client.CaptureEvent(event, hint, scope) + + if event.Type != transactionType && eventID != nil { + hub.mu.Lock() + hub.lastEventID = *eventID + hub.mu.Unlock() + } + return eventID +} + +// CaptureMessage calls the method of a same name on currently bound Client instance +// passing it a top-level Scope. +// Returns EventID if successfully, or nil if there's no Scope or Client available. +func (hub *Hub) CaptureMessage(message string) *EventID { + client, scope := hub.Client(), hub.Scope() + if client == nil || scope == nil { + return nil + } + eventID := client.CaptureMessage(message, nil, scope) + + if eventID != nil { + hub.mu.Lock() + hub.lastEventID = *eventID + hub.mu.Unlock() + } + return eventID +} + +// CaptureException calls the method of a same name on currently bound Client instance +// passing it a top-level Scope. +// Returns EventID if successfully, or nil if there's no Scope or Client available. +func (hub *Hub) CaptureException(exception error) *EventID { + client, scope := hub.Client(), hub.Scope() + if client == nil || scope == nil { + return nil + } + eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope) + + if eventID != nil { + hub.mu.Lock() + hub.lastEventID = *eventID + hub.mu.Unlock() + } + return eventID +} + +// CaptureCheckIn calls the method of the same name on currently bound Client instance +// passing it a top-level Scope. +// Returns CheckInID if the check-in was captured successfully, or nil otherwise. +func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { + client, scope := hub.Client(), hub.Scope() + if client == nil { + return nil + } + + return client.CaptureCheckIn(checkIn, monitorConfig, scope) +} + +// AddBreadcrumb records a new breadcrumb. +// +// The total number of breadcrumbs that can be recorded are limited by the +// configuration on the client. +func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) { + client := hub.Client() + + // If there's no client, just store it on the scope straight away + if client == nil { + hub.Scope().AddBreadcrumb(breadcrumb, defaultMaxBreadcrumbs) + return + } + + limit := client.options.MaxBreadcrumbs + switch { + case limit < 0: + return + case limit == 0: + limit = defaultMaxBreadcrumbs + } + + if client.options.BeforeBreadcrumb != nil { + if hint == nil { + hint = &BreadcrumbHint{} + } + if breadcrumb = client.options.BeforeBreadcrumb(breadcrumb, hint); breadcrumb == nil { + debuglog.Println("breadcrumb dropped due to BeforeBreadcrumb callback.") + return + } + } + + hub.Scope().AddBreadcrumb(breadcrumb, limit) +} + +// Recover calls the method of a same name on currently bound Client instance +// passing it a top-level Scope. +// Returns EventID if successfully, or nil if there's no Scope or Client available. +func (hub *Hub) Recover(err interface{}) *EventID { + if err == nil { + err = recover() + } + client, scope := hub.Client(), hub.Scope() + if client == nil || scope == nil { + return nil + } + return client.Recover(err, &EventHint{RecoveredException: err}, scope) +} + +// RecoverWithContext calls the method of a same name on currently bound Client instance +// passing it a top-level Scope. +// Returns EventID if successfully, or nil if there's no Scope or Client available. +func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventID { + if err == nil { + err = recover() + } + client, scope := hub.Client(), hub.Scope() + if client == nil || scope == nil { + return nil + } + return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope) +} + +// Flush waits until the underlying Transport sends any buffered events to the +// Sentry server, blocking for at most the given timeout. It returns false if +// the timeout was reached. In that case, some events may not have been sent. +// +// Flush should be called before terminating the program to avoid +// unintentionally dropping events. +// +// Do not call Flush indiscriminately after every call to CaptureEvent, +// CaptureException or CaptureMessage. Instead, to have the SDK send events over +// the network synchronously, configure it to use the HTTPSyncTransport in the +// call to Init. +func (hub *Hub) Flush(timeout time.Duration) bool { + client := hub.Client() + + if client == nil { + return false + } + + return client.Flush(timeout) +} + +// FlushWithContext waits until the underlying Transport sends any buffered events +// to the Sentry server, blocking for at most the duration specified by the context. +// It returns false if the context is canceled before the events are sent. In such a case, +// some events may not be delivered. +// +// FlushWithContext should be called before terminating the program to ensure no +// events are unintentionally dropped. +// +// Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent, +// CaptureException, or CaptureMessage. To send events synchronously over the network, +// configure the SDK to use HTTPSyncTransport during initialization with Init. + +func (hub *Hub) FlushWithContext(ctx context.Context) bool { + client := hub.Client() + + if client == nil { + return false + } + + return client.FlushWithContext(ctx) +} + +// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value +// or HTML meta tag value. +// This function is context aware, as in it either returns the traceparent based +// on the current span, or the scope's propagation context. +func (hub *Hub) GetTraceparent() string { + scope := hub.Scope() + if span := scope.GetSpan(); span != nil { + return span.ToSentryTrace() + } + propagationContext := scope.propagationContextSnapshot() + return fmt.Sprintf("%s-%s", propagationContext.TraceID, propagationContext.SpanID) +} + +// GetTraceparentW3C returns the current traceparent string in W3C format. +// This is intended for propagation to downstream services that expect the W3C header. +func (hub *Hub) GetTraceparentW3C() string { + scope := hub.Scope() + if span := scope.GetSpan(); span != nil { + return span.ToTraceparent() + } + propagationContext := scope.propagationContextSnapshot() + return fmt.Sprintf("00-%s-%s-00", propagationContext.TraceID, propagationContext.SpanID) +} + +// GetBaggage returns the current Sentry baggage string, to be used as a HTTP header value +// or HTML meta tag value. +// This function is context aware, as in it either returns the baggage based +// on the current span or the scope's propagation context. +func (hub *Hub) GetBaggage() string { + scope := hub.Scope() + if span := scope.GetSpan(); span != nil { + return span.ToBaggage() + } + return scope.propagationContextSnapshot().DynamicSamplingContext.String() +} + +// HasHubOnContext checks whether Hub instance is bound to a given Context struct. +func HasHubOnContext(ctx context.Context) bool { + _, ok := ctx.Value(HubContextKey).(*Hub) + return ok +} + +// GetHubFromContext tries to retrieve Hub instance from the given Context struct +// or return nil if one is not found. +func GetHubFromContext(ctx context.Context) *Hub { + if hub, ok := ctx.Value(HubContextKey).(*Hub); ok { + return hub + } + return nil +} + +// hubFromContext returns either a hub stored in the context or the current hub. +// The return value is guaranteed to be non-nil, unlike GetHubFromContext. +func hubFromContext(ctx context.Context) *Hub { + if hub, ok := ctx.Value(HubContextKey).(*Hub); ok { + return hub + } + return currentHub +} + +// SetHubOnContext stores given Hub instance on the Context struct and returns a new Context. +func SetHubOnContext(ctx context.Context, hub *Hub) context.Context { + return context.WithValue(ctx, HubContextKey, hub) +} diff --git a/vendor/github.com/getsentry/sentry-go/integrations.go b/vendor/github.com/getsentry/sentry-go/integrations.go new file mode 100644 index 0000000..0d92652 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/integrations.go @@ -0,0 +1,278 @@ +package sentry + +import ( + "fmt" + "os" + "regexp" + "runtime" + "runtime/debug" + "strings" + "sync" + + "github.com/getsentry/sentry-go/internal/debuglog" +) + +// ================================ +// Modules Integration +// ================================ + +type modulesIntegration struct { + once sync.Once + modules map[string]string +} + +func (mi *modulesIntegration) Name() string { + return "Modules" +} + +func (mi *modulesIntegration) SetupOnce(client *Client) { + client.AddEventProcessor(mi.processor) +} + +func (mi *modulesIntegration) processor(event *Event, _ *EventHint) *Event { + if len(event.Modules) == 0 { + mi.once.Do(func() { + info, ok := debug.ReadBuildInfo() + if !ok { + debuglog.Print("The Modules integration is not available in binaries built without module support.") + return + } + mi.modules = extractModules(info) + }) + } + event.Modules = mi.modules + return event +} + +func extractModules(info *debug.BuildInfo) map[string]string { + modules := map[string]string{ + info.Main.Path: info.Main.Version, + } + for _, dep := range info.Deps { + ver := dep.Version + if dep.Replace != nil { + ver += fmt.Sprintf(" => %s %s", dep.Replace.Path, dep.Replace.Version) + } + modules[dep.Path] = strings.TrimSuffix(ver, " ") + } + return modules +} + +// ================================ +// Environment Integration +// ================================ + +type environmentIntegration struct{} + +func (ei *environmentIntegration) Name() string { + return "Environment" +} + +func (ei *environmentIntegration) SetupOnce(client *Client) { + client.AddEventProcessor(ei.processor) +} + +func (ei *environmentIntegration) processor(event *Event, _ *EventHint) *Event { + // Initialize maps as necessary. + contextNames := []string{"device", "os", "runtime"} + if event.Contexts == nil { + event.Contexts = make(map[string]Context, len(contextNames)) + } + for _, name := range contextNames { + if event.Contexts[name] == nil { + event.Contexts[name] = make(Context) + } + } + + // Set contextual information preserving existing data. For each context, if + // the existing value is not of type map[string]interface{}, then no + // additional information is added. + if deviceContext, ok := event.Contexts["device"]; ok { + if _, ok := deviceContext["arch"]; !ok { + deviceContext["arch"] = runtime.GOARCH + } + if _, ok := deviceContext["num_cpu"]; !ok { + deviceContext["num_cpu"] = runtime.NumCPU() + } + } + if osContext, ok := event.Contexts["os"]; ok { + if _, ok := osContext["name"]; !ok { + osContext["name"] = runtime.GOOS + } + } + if runtimeContext, ok := event.Contexts["runtime"]; ok { + if _, ok := runtimeContext["name"]; !ok { + runtimeContext["name"] = "go" + } + if _, ok := runtimeContext["version"]; !ok { + runtimeContext["version"] = runtime.Version() + } + if _, ok := runtimeContext["go_numroutines"]; !ok { + runtimeContext["go_numroutines"] = runtime.NumGoroutine() + } + if _, ok := runtimeContext["go_maxprocs"]; !ok { + runtimeContext["go_maxprocs"] = runtime.GOMAXPROCS(0) + } + if _, ok := runtimeContext["go_numcgocalls"]; !ok { + runtimeContext["go_numcgocalls"] = runtime.NumCgoCall() + } + } + return event +} + +// ================================ +// Ignore Errors Integration +// ================================ + +type ignoreErrorsIntegration struct { + ignoreErrors []*regexp.Regexp +} + +func (iei *ignoreErrorsIntegration) Name() string { + return "IgnoreErrors" +} + +func (iei *ignoreErrorsIntegration) SetupOnce(client *Client) { + iei.ignoreErrors = transformStringsIntoRegexps(client.options.IgnoreErrors) + client.AddEventProcessor(iei.processor) +} + +func (iei *ignoreErrorsIntegration) processor(event *Event, _ *EventHint) *Event { + suspects := getIgnoreErrorsSuspects(event) + + for _, suspect := range suspects { + for _, pattern := range iei.ignoreErrors { + if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) { + debuglog.Printf("Event dropped due to being matched by `IgnoreErrors` option."+ + "| Value matched: %s | Filter used: %s", suspect, pattern) + return nil + } + } + } + + return event +} + +func transformStringsIntoRegexps(strings []string) []*regexp.Regexp { + var exprs []*regexp.Regexp + + for _, s := range strings { + r, err := regexp.Compile(s) + if err == nil { + exprs = append(exprs, r) + } + } + + return exprs +} + +func getIgnoreErrorsSuspects(event *Event) []string { + suspects := []string{} + + if event.Message != "" { + suspects = append(suspects, event.Message) + } + + for _, ex := range event.Exception { + suspects = append(suspects, ex.Type, ex.Value) + } + + return suspects +} + +// ================================ +// Ignore Transactions Integration +// ================================ + +type ignoreTransactionsIntegration struct { + ignoreTransactions []*regexp.Regexp +} + +func (iei *ignoreTransactionsIntegration) Name() string { + return "IgnoreTransactions" +} + +func (iei *ignoreTransactionsIntegration) SetupOnce(client *Client) { + iei.ignoreTransactions = transformStringsIntoRegexps(client.options.IgnoreTransactions) + client.AddEventProcessor(iei.processor) +} + +func (iei *ignoreTransactionsIntegration) processor(event *Event, _ *EventHint) *Event { + suspect := event.Transaction + if suspect == "" { + return event + } + + for _, pattern := range iei.ignoreTransactions { + if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) { + debuglog.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+ + "| Value matched: %s | Filter used: %s", suspect, pattern) + return nil + } + } + + return event +} + +// ================================ +// Global Tags Integration +// ================================ + +const envTagsPrefix = "SENTRY_TAGS_" + +type globalTagsIntegration struct { + tags map[string]string + envTags map[string]string +} + +func (ti *globalTagsIntegration) Name() string { + return "GlobalTags" +} + +func (ti *globalTagsIntegration) SetupOnce(client *Client) { + ti.tags = make(map[string]string, len(client.options.Tags)) + for k, v := range client.options.Tags { + ti.tags[k] = v + } + + ti.envTags = loadEnvTags() + + client.AddEventProcessor(ti.processor) +} + +func (ti *globalTagsIntegration) processor(event *Event, _ *EventHint) *Event { + if len(ti.tags) == 0 && len(ti.envTags) == 0 { + return event + } + + if event.Tags == nil { + event.Tags = make(map[string]string, len(ti.tags)+len(ti.envTags)) + } + + for k, v := range ti.tags { + if _, ok := event.Tags[k]; !ok { + event.Tags[k] = v + } + } + + for k, v := range ti.envTags { + if _, ok := event.Tags[k]; !ok { + event.Tags[k] = v + } + } + + return event +} + +func loadEnvTags() map[string]string { + tags := map[string]string{} + for _, pair := range os.Environ() { + parts := strings.Split(pair, "=") + if !strings.HasPrefix(parts[0], envTagsPrefix) { + continue + } + tag := strings.TrimPrefix(parts[0], envTagsPrefix) + tags[tag] = parts[1] + } + return tags +} diff --git a/vendor/github.com/getsentry/sentry-go/interfaces.go b/vendor/github.com/getsentry/sentry-go/interfaces.go new file mode 100644 index 0000000..4d14df6 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/interfaces.go @@ -0,0 +1,894 @@ +package sentry + +import ( + "context" + "encoding/json" + "fmt" + "net" + "net/http" + "strings" + "time" + + "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +const errorType = "" +const eventType = "event" +const transactionType = "transaction" +const checkInType = "check_in" + +var logEvent = struct { + Type string + ContentType string +}{ + "log", + "application/vnd.sentry.items.log+json", +} + +var traceMetricEvent = struct { + Type string + ContentType string +}{ + "trace_metric", + "application/vnd.sentry.items.trace-metric+json", +} + +// Level marks the severity of the event. +type Level string + +// Describes the severity of the event. +const ( + LevelDebug Level = "debug" + LevelInfo Level = "info" + LevelWarning Level = "warning" + LevelError Level = "error" + LevelFatal Level = "fatal" +) + +// SdkInfo contains all metadata about the SDK. +type SdkInfo = protocol.SdkInfo +type SdkPackage = protocol.SdkPackage + +// TODO: This type could be more useful, as map of interface{} is too generic +// and requires a lot of type assertions in beforeBreadcrumb calls +// plus it could just be map[string]interface{} then. + +// BreadcrumbHint contains information that can be associated with a Breadcrumb. +type BreadcrumbHint map[string]interface{} + +// Breadcrumb specifies an application event that occurred before a Sentry event. +// An event may contain one or more breadcrumbs. +type Breadcrumb struct { + Type string `json:"type,omitempty"` + Category string `json:"category,omitempty"` + Message string `json:"message,omitempty"` + Data map[string]interface{} `json:"data,omitempty"` + Level Level `json:"level,omitempty"` + Timestamp time.Time `json:"timestamp,omitzero"` +} + +// TODO: provide constants for known breadcrumb types. +// See https://develop.sentry.dev/sdk/event-payloads/breadcrumbs/#breadcrumb-types. + +// Logger provides a chaining API for structured logging to Sentry. +type Logger interface { + // Write implements the io.Writer interface. Currently, the [sentry.Hub] is + // context aware, in order to get the correct trace correlation. Using this + // might result in incorrect span association on logs. If you need to use + // Write it is recommended to create a NewLogger so that the associated context + // is passed correctly. + Write(p []byte) (n int, err error) + + // SetAttributes allows attaching parameters to the logger using the attribute API. + // These attributes will be included in all subsequent log entries. + SetAttributes(...attribute.Builder) + + // Trace defines the [sentry.LogLevel] for the log entry. + Trace() LogEntry + // Debug defines the [sentry.LogLevel] for the log entry. + Debug() LogEntry + // Info defines the [sentry.LogLevel] for the log entry. + Info() LogEntry + // Warn defines the [sentry.LogLevel] for the log entry. + Warn() LogEntry + // Error defines the [sentry.LogLevel] for the log entry. + Error() LogEntry + // Fatal defines the [sentry.LogLevel] for the log entry. + Fatal() LogEntry + // Panic defines the [sentry.LogLevel] for the log entry. + Panic() LogEntry + // LFatal defines the [sentry.LogLevel] for the log entry. This only sets + // the level to fatal, but does not panic or exit. + LFatal() LogEntry + // GetCtx returns the [context.Context] set on the logger. + GetCtx() context.Context +} + +// LogEntry defines the interface for a log entry that supports chaining attributes. +type LogEntry interface { + // WithCtx creates a new LogEntry with the specified context without overwriting the previous one. + WithCtx(ctx context.Context) LogEntry + // StringSlice adds a string slice attribute to the LogEntry. + StringSlice(key string, value []string) LogEntry + // String adds a string attribute to the LogEntry. + String(key, value string) LogEntry + // Int adds an int attribute to the LogEntry. + Int(key string, value int) LogEntry + // Int64Slice adds an int64 slice attribute to the LogEntry. + Int64Slice(key string, value []int64) LogEntry + // Int64 adds an int64 attribute to the LogEntry. + Int64(key string, value int64) LogEntry + // Float64Slice adds a float64 slice attribute to the LogEntry. + Float64Slice(key string, value []float64) LogEntry + // Float64 adds a float64 attribute to the LogEntry. + Float64(key string, value float64) LogEntry + // BoolSlice adds a bool slice attribute to the LogEntry. + BoolSlice(key string, value []bool) LogEntry + // Bool adds a bool attribute to the LogEntry. + Bool(key string, value bool) LogEntry + // Emit emits the LogEntry with the provided arguments. + Emit(args ...interface{}) + // Emitf emits the LogEntry using a format string and arguments. + Emitf(format string, args ...interface{}) +} + +// Meter provides an interface for recording metrics. +type Meter interface { + // WithCtx returns a new Meter that uses the given context for trace/span association. + WithCtx(ctx context.Context) Meter + // SetAttributes allows attaching parameters to the meter using the attribute API. + // These attributes will be included in all subsequent metrics. + SetAttributes(attrs ...attribute.Builder) + // Count records a count metric. + Count(name string, count int64, opts ...MeterOption) + // Gauge records a gauge metric. + Gauge(name string, value float64, opts ...MeterOption) + // Distribution records a distribution metric. + Distribution(name string, sample float64, opts ...MeterOption) +} + +// MeterOption configures a metric recording call. +type MeterOption func(*meterOptions) + +type meterOptions struct { + unit string + scope *Scope + attributes map[string]attribute.Value +} + +// WithUnit sets the unit for the metric (e.g., "millisecond", "byte"). +func WithUnit(unit string) MeterOption { + return func(o *meterOptions) { + o.unit = unit + } +} + +// WithScopeOverride sets a custom scope for the metric, overriding the default scope from the hub. +func WithScopeOverride(scope *Scope) MeterOption { + return func(o *meterOptions) { + o.scope = scope + } +} + +// WithAttributes sets attributes for the metric. +func WithAttributes(attrs ...attribute.Builder) MeterOption { + return func(o *meterOptions) { + if o.attributes == nil { + o.attributes = make(map[string]attribute.Value, len(attrs)) + } + for _, a := range attrs { + if a.Value.Type() == attribute.INVALID { + debuglog.Printf("invalid attribute: %v", a) + continue + } + o.attributes[a.Key] = a.Value + } + } +} + +// Attachment allows associating files with your events to aid in investigation. +// An event may contain one or more attachments. +type Attachment struct { + Filename string + ContentType string + Payload []byte +} + +// User describes the user associated with an Event. If this is used, at least +// an ID or an IP address should be provided. +type User struct { + ID string `json:"id,omitempty"` + Email string `json:"email,omitempty"` + IPAddress string `json:"ip_address,omitempty"` + Username string `json:"username,omitempty"` + Name string `json:"name,omitempty"` + Data map[string]string `json:"data,omitempty"` +} + +func (u User) IsEmpty() bool { + if u.ID != "" { + return false + } + + if u.Email != "" { + return false + } + + if u.IPAddress != "" { + return false + } + + if u.Username != "" { + return false + } + + if u.Name != "" { + return false + } + + if len(u.Data) > 0 { + return false + } + + return true +} + +// Request contains information on a HTTP request related to the event. +type Request struct { + URL string `json:"url,omitempty"` + Method string `json:"method,omitempty"` + Data string `json:"data,omitempty"` + QueryString string `json:"query_string,omitempty"` + Cookies string `json:"cookies,omitempty"` + Headers map[string]string `json:"headers,omitempty"` + Env map[string]string `json:"env,omitempty"` +} + +func newRequest(r *http.Request, client *Client) *Request { + prot := protocol.SchemeHTTP + if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" { + prot = protocol.SchemeHTTPS + } + url := fmt.Sprintf("%s://%s%s", prot, r.Host, r.URL.Path) + + dc := client.GetDataCollection() + + var cookies string + headers := make(map[string]string, len(r.Header)+1) + if dc.CollectCookies() { + cookies = dc.FilterCookies(r.Header.Values("Cookie")) + if cookies != "" { + headers["Cookie"] = cookies + } + } + for k, v := range r.Header { + if strings.EqualFold(k, "Cookie") { + continue + } + headers[k] = strings.Join(v, ",") + } + headers["Host"] = r.Host + headers = dc.FilterRequestHeaders(headers) + + var env map[string]string + if dc.UserInfo.Value { + if addr, port, err := net.SplitHostPort(r.RemoteAddr); err == nil { + env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port} + } + } + + return &Request{ + URL: url, + Method: r.Method, + QueryString: dc.FilterQueryString(r.URL.RawQuery), + Cookies: cookies, + Headers: headers, + Env: env, + } +} + +// NewRequest returns a new Sentry Request from the given http.Request. +// +// NewRequest avoids operations that depend on network access. In particular, it +// does not read r.Body. +func NewRequest(r *http.Request) *Request { + return newRequest(r, CurrentHub().Client()) +} + +// Mechanism is the mechanism by which an exception was generated and handled. +type Mechanism struct { + Type string `json:"type"` + Description string `json:"description,omitempty"` + HelpLink string `json:"help_link,omitempty"` + Source string `json:"source,omitempty"` + Handled *bool `json:"handled,omitempty"` + ParentID *int `json:"parent_id,omitempty"` + ExceptionID int `json:"exception_id"` + IsExceptionGroup bool `json:"is_exception_group,omitempty"` + Data map[string]any `json:"data,omitempty"` +} + +// SetUnhandled indicates that the exception is an unhandled exception, i.e. +// from a panic. +func (m *Mechanism) SetUnhandled() { + m.Handled = Pointer(false) +} + +// Exception specifies an error that occurred. +type Exception struct { + Type string `json:"type,omitempty"` // used as the main issue title + Value string `json:"value,omitempty"` // used as the main issue subtitle + Module string `json:"module,omitempty"` + ThreadID uint64 `json:"thread_id,omitempty"` + Stacktrace *Stacktrace `json:"stacktrace,omitempty"` + Mechanism *Mechanism `json:"mechanism,omitempty"` +} + +// SDKMetaData is a struct to stash data which is needed at some point in the SDK's event processing pipeline +// but which shouldn't get send to Sentry. +type SDKMetaData struct { + dsc DynamicSamplingContext +} + +// Contains information about how the name of the transaction was determined. +type TransactionInfo struct { + Source TransactionSource `json:"source,omitempty"` +} + +// The DebugMeta interface is not used in Golang apps, but may be populated +// when proxying Events from other platforms, like iOS, Android, and the +// Web. (See: https://develop.sentry.dev/sdk/event-payloads/debugmeta/ ). +type DebugMeta struct { + SdkInfo *DebugMetaSdkInfo `json:"sdk_info,omitempty"` + Images []DebugMetaImage `json:"images,omitempty"` +} + +type DebugMetaSdkInfo struct { + SdkName string `json:"sdk_name,omitempty"` + VersionMajor int `json:"version_major,omitempty"` + VersionMinor int `json:"version_minor,omitempty"` + VersionPatchlevel int `json:"version_patchlevel,omitempty"` +} + +type DebugMetaImage struct { + Type string `json:"type,omitempty"` // all + ImageAddr string `json:"image_addr,omitempty"` // macho,elf,pe + ImageSize int `json:"image_size,omitempty"` // macho,elf,pe + DebugID string `json:"debug_id,omitempty"` // macho,elf,pe,wasm,sourcemap + DebugFile string `json:"debug_file,omitempty"` // macho,elf,pe,wasm + CodeID string `json:"code_id,omitempty"` // macho,elf,pe,wasm + CodeFile string `json:"code_file,omitempty"` // macho,elf,pe,wasm,sourcemap + ImageVmaddr string `json:"image_vmaddr,omitempty"` // macho,elf,pe + Arch string `json:"arch,omitempty"` // macho,elf,pe + UUID string `json:"uuid,omitempty"` // proguard +} + +// EventID is a hexadecimal string representing a unique uuid4 for an Event. +// An EventID must be 32 characters long, lowercase and not have any dashes. +type EventID string + +type Context = map[string]interface{} + +// Event is the fundamental data structure that is sent to Sentry. +type Event struct { + Breadcrumbs []*Breadcrumb `json:"breadcrumbs,omitempty"` + Contexts map[string]Context `json:"contexts,omitempty"` + Dist string `json:"dist,omitempty"` + Environment string `json:"environment,omitempty"` + EventID EventID `json:"event_id,omitempty"` + Fingerprint []string `json:"fingerprint,omitempty"` + Level Level `json:"level,omitempty"` + Message string `json:"message,omitempty"` + Platform string `json:"platform,omitempty"` + Release string `json:"release,omitempty"` + Sdk SdkInfo `json:"sdk,omitempty"` + ServerName string `json:"server_name,omitempty"` + Threads []Thread `json:"threads,omitempty"` + Tags map[string]string `json:"tags,omitempty"` + Timestamp time.Time `json:"timestamp,omitzero"` + Transaction string `json:"transaction,omitempty"` + User User `json:"user,omitempty"` + Logger string `json:"logger,omitempty"` + Modules map[string]string `json:"modules,omitempty"` + Request *Request `json:"request,omitempty"` + Exception []Exception `json:"exception,omitempty"` + DebugMeta *DebugMeta `json:"debug_meta,omitempty"` + Attachments []*Attachment `json:"-"` + + // The fields below are only relevant for transactions. + + Type string `json:"type,omitempty"` + StartTime time.Time `json:"start_timestamp,omitzero"` + Spans []*Span `json:"spans,omitempty"` + TransactionInfo *TransactionInfo `json:"transaction_info,omitempty"` + + // The fields below are only relevant for crons/check ins + + CheckIn *CheckIn `json:"check_in,omitempty"` + MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"` + + // The fields below are only relevant for logs + Logs []Log `json:"-"` + + // The fields below are only relevant for metrics + Metrics []Metric `json:"-"` + + // The fields below are not part of the final JSON payload. + + sdkMetaData SDKMetaData + + // Pre-serialized copies of mutable fields, set by MakeSerializationSafe. + serializedTags json.RawMessage + serializedContexts json.RawMessage + serializedBreadcrumbs json.RawMessage + serializedException json.RawMessage + serializedUser json.RawMessage + serializationSafe bool +} + +// SetException appends the unwrapped errors to the event's exception list. +// +// maxErrorDepth is the maximum depth of the error chain we will look +// into while unwrapping the errors. If maxErrorDepth is -1, we will +// unwrap all errors in the chain. +func (e *Event) SetException(exception error, maxErrorDepth int) { + if exception == nil { + return + } + + exceptions := convertErrorToExceptions(exception, maxErrorDepth) + if len(exceptions) == 0 { + return + } + + e.Exception = exceptions +} + +// safeMarshal wraps json.Marshal with a recover guard. +// +// we shouldn't panic since we already pre serialized all user mutable fields, but using this just to be safe. +func (e *Event) safeMarshal() (b []byte, err error) { + defer func() { + if r := recover(); r != nil { + b = nil + err = fmt.Errorf("panic during event marshaling: %v", r) + } + }() + return json.Marshal(e) +} + +// ToEnvelopeItem converts the Event to a Sentry envelope item. +func (e *Event) ToEnvelopeItem() (item *protocol.EnvelopeItem, err error) { + eventBody, err := e.safeMarshal() + if err != nil { + return nil, fmt.Errorf("could not encode event as JSON, skipping delivery: %w", err) + } + + switch e.Type { + case transactionType: + item = protocol.NewTransactionItem(e.GetSpanCount(), eventBody) + case checkInType: + item = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeCheckIn, eventBody) + case logEvent.Type: + item = protocol.NewLogItem(len(e.Logs), eventBody) + case traceMetricEvent.Type: + item = protocol.NewTraceMetricItem(len(e.Metrics), eventBody) + default: + item = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeEvent, eventBody) + } + + return item, nil +} + +// ToEnvelope converts the Event to a Sentry envelope. +func (e *Event) ToEnvelope(header *protocol.EnvelopeHeader) (*protocol.Envelope, error) { + item, err := e.ToEnvelopeItem() + if err != nil { + return nil, err + } + + envelope := protocol.NewEnvelope(header, item) + for _, attachment := range e.Attachments { + attachmentItem := protocol.NewAttachmentItem(attachment.Filename, attachment.ContentType, attachment.Payload) + envelope.AddItem(attachmentItem) + } + return envelope, nil +} + +// GetCategory returns the rate limit category for this event. +func (e *Event) GetCategory() ratelimit.Category { + return e.toCategory() +} + +// GetEventID returns the event ID. +func (e *Event) GetEventID() string { + return string(e.EventID) +} + +// GetSdkInfo returns SDK information for the envelope header. +func (e *Event) GetSdkInfo() *protocol.SdkInfo { + return &e.Sdk +} + +// GetDynamicSamplingContext returns trace context for the envelope header. +func (e *Event) GetDynamicSamplingContext() map[string]string { + trace := make(map[string]string) + if dsc := e.sdkMetaData.dsc; dsc.HasEntries() { + for k, v := range dsc.Entries { + trace[k] = v + } + } + return trace +} + +// GetSpanCount returns the number of spans in the transaction including the transaction itself. It is used for client +// reports. Returns 0 for non-transaction events. +func (e *Event) GetSpanCount() int { + if e.Type != transactionType { + return 0 + } + return len(e.Spans) + 1 +} + +// GetLogByteSize returns the approximate total byte size of all logs in the event. It is used for client +// reports. Returns 0 for non-log events. +func (e *Event) GetLogByteSize() int { + if e.Type != logEvent.Type { + return 0 + } + var size int + for i := range e.Logs { + size += e.Logs[i].ApproximateSize() + } + return size +} + +// TODO: Event.Contexts map[string]interface{} => map[string]EventContext, +// to prevent accidentally storing T when we mean *T. +// For example, the TraceContext must be stored as *TraceContext to pick up the +// MarshalJSON method (and avoid copying). +// type EventContext interface{ EventContext() } + +// MarshalJSON converts the Event struct to JSON. +func (e *Event) MarshalJSON() ([]byte, error) { + if e.Type == checkInType { + return e.checkInMarshalJSON() + } + return e.defaultMarshalJSON() +} + +func (e *Event) defaultMarshalJSON() ([]byte, error) { + // event aliases Event to allow calling json.Marshal without an infinite + // loop. It preserves all fields while none of the attached methods. + type event Event + + // Use pre-serialized bytes for fields that contain user mutable data. + if e.hasPreSerializedFields() { + return e.preSerializedMarshalJSON() + } + + if e.Type == transactionType { + return json.Marshal(struct{ *event }{(*event)(e)}) + } + // metrics and logs should be serialized under the same `items` json field. + if e.Type == logEvent.Type { + type logEvent struct { + *event + Items []Log `json:"items,omitempty"` + Type json.RawMessage `json:"type,omitempty"` + } + return json.Marshal(logEvent{event: (*event)(e), Items: e.Logs}) + } + + if e.Type == traceMetricEvent.Type { + type metricEvent struct { + *event + Items []Metric `json:"items,omitempty"` + Type json.RawMessage `json:"type,omitempty"` + } + return json.Marshal(metricEvent{event: (*event)(e), Items: e.Metrics}) + } + + // errorEvent is like Event with shadowed fields for customizing JSON + // marshaling. + type errorEvent struct { + *event + + // The fields below are not part of error events and only make sense to + // be sent for transactions. They shadow the respective fields in Event + // and are meant to remain nil, triggering the omitempty behavior. + + Type json.RawMessage `json:"type,omitempty"` + StartTime json.RawMessage `json:"start_timestamp,omitempty"` + Spans json.RawMessage `json:"spans,omitempty"` + TransactionInfo json.RawMessage `json:"transaction_info,omitempty"` + } + + x := errorEvent{event: (*event)(e)} + return json.Marshal(x) +} + +func (e *Event) hasPreSerializedFields() bool { + return e.serializationSafe +} + +// preSerializedMarshalJSON handles marshaling when MakeSerializationSafe has +// pre-serialized mutable fields. Shadow structs ensure the json.RawMessage +// bytes are emitted directly, overriding the original fields. +func (e *Event) preSerializedMarshalJSON() ([]byte, error) { + type event Event + + if e.Type == transactionType { + type safeTransaction struct { + *event + Tags json.RawMessage `json:"tags,omitempty"` + Contexts json.RawMessage `json:"contexts,omitempty"` + Breadcrumbs json.RawMessage `json:"breadcrumbs,omitempty"` + Exception json.RawMessage `json:"exception,omitempty"` + User json.RawMessage `json:"user,omitempty"` + } + return json.Marshal(safeTransaction{ + event: (*event)(e), + Tags: e.serializedTags, + Contexts: e.serializedContexts, + Breadcrumbs: e.serializedBreadcrumbs, + Exception: e.serializedException, + User: e.serializedUser, + }) + } + + // Error event: also shadow transaction-only fields to exclude them. + type safeErrorEvent struct { + *event + Tags json.RawMessage `json:"tags,omitempty"` + Contexts json.RawMessage `json:"contexts,omitempty"` + Breadcrumbs json.RawMessage `json:"breadcrumbs,omitempty"` + Exception json.RawMessage `json:"exception,omitempty"` + User json.RawMessage `json:"user,omitempty"` + Type json.RawMessage `json:"type,omitempty"` + StartTime json.RawMessage `json:"start_timestamp,omitempty"` + Spans json.RawMessage `json:"spans,omitempty"` + TransactionInfo json.RawMessage `json:"transaction_info,omitempty"` + } + return json.Marshal(safeErrorEvent{ + event: (*event)(e), + Tags: e.serializedTags, + Contexts: e.serializedContexts, + Breadcrumbs: e.serializedBreadcrumbs, + Exception: e.serializedException, + User: e.serializedUser, + }) +} + +func (e *Event) checkInMarshalJSON() ([]byte, error) { + checkIn := serializedCheckIn{ + CheckInID: string(e.CheckIn.ID), + MonitorSlug: e.CheckIn.MonitorSlug, + Status: e.CheckIn.Status, + Duration: e.CheckIn.Duration.Seconds(), + Release: e.Release, + Environment: e.Environment, + MonitorConfig: nil, + } + + if e.MonitorConfig != nil { + checkIn.MonitorConfig = &MonitorConfig{ + Schedule: e.MonitorConfig.Schedule, + CheckInMargin: e.MonitorConfig.CheckInMargin, + MaxRuntime: e.MonitorConfig.MaxRuntime, + Timezone: e.MonitorConfig.Timezone, + FailureIssueThreshold: e.MonitorConfig.FailureIssueThreshold, + RecoveryThreshold: e.MonitorConfig.RecoveryThreshold, + } + } + + return json.Marshal(checkIn) +} + +func (e *Event) toCategory() ratelimit.Category { + switch e.Type { + case errorType: + return ratelimit.CategoryError + case transactionType: + return ratelimit.CategoryTransaction + case logEvent.Type: + return ratelimit.CategoryLog + case checkInType: + return ratelimit.CategoryMonitor + case traceMetricEvent.Type: + return ratelimit.CategoryTraceMetric + default: + return ratelimit.CategoryUnknown + } +} + +// NewEvent creates a new Event. +func NewEvent() *Event { + return &Event{ + Contexts: make(map[string]Context), + Tags: make(map[string]string), + Modules: make(map[string]string), + } +} + +// Thread specifies threads that were running at the time of an event. +type Thread struct { + ID string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Stacktrace *Stacktrace `json:"stacktrace,omitempty"` + Crashed bool `json:"crashed,omitempty"` + Current bool `json:"current,omitempty"` +} + +// EventHint contains information that can be associated with an Event. +type EventHint struct { + Data interface{} + EventID string + OriginalException error + RecoveredException interface{} + Context context.Context + Request *http.Request + Response *http.Response +} + +type Log struct { + Timestamp time.Time `json:"timestamp,omitzero"` + TraceID TraceID `json:"trace_id"` + SpanID SpanID `json:"span_id,omitzero"` + Level LogLevel `json:"level"` + Severity int `json:"severity_number,omitempty"` + Body string `json:"body"` + Attributes map[string]attribute.Value `json:"attributes,omitempty"` + + // approximateSize is the pre-computed approximate size in bytes. + approximateSize int +} + +// ApproximateSize returns the pre-computed approximate serialized size in bytes. +func (l *Log) ApproximateSize() int { + return l.approximateSize +} + +// computeLogSize estimates the serialized JSON size of a log entry. +func computeLogSize(l *Log) int { + // Base overhead: timestamp, trace_id, level, severity, JSON structure + size := len(l.Body) + 60 + for k, v := range l.Attributes { + // Key + type/value JSON overhead + size += len(k) + 20 + s := fmt.Sprint(v.AsInterface()) + size += len(s) + } + return size +} + +// MakeSerializationSafe is a no-op for Log, all fields are passed from the safe attribute API. +func (l *Log) MakeSerializationSafe() {} + +// GetCategory returns the rate limit category for logs. +func (l *Log) GetCategory() ratelimit.Category { + return ratelimit.CategoryLog +} + +type MetricType string + +const ( + MetricTypeInvalid MetricType = "" + MetricTypeCounter MetricType = "counter" + MetricTypeGauge MetricType = "gauge" + MetricTypeDistribution MetricType = "distribution" +) + +type Metric struct { + Timestamp time.Time `json:"timestamp,omitzero"` + TraceID TraceID `json:"trace_id"` + SpanID SpanID `json:"span_id,omitzero"` + Type MetricType `json:"type"` + Name string `json:"name"` + Value MetricValue `json:"value"` + Unit string `json:"unit,omitempty"` + Attributes map[string]attribute.Value `json:"attributes,omitempty"` +} + +// MakeSerializationSafe is a no-op for Metric, all fields are passed from the safe attribute API. +func (m *Metric) MakeSerializationSafe() {} + +// GetCategory returns the rate limit category for metrics. +func (m *Metric) GetCategory() ratelimit.Category { + return ratelimit.CategoryTraceMetric +} + +// MetricValue stores metric values with full precision. +// It supports int64 (for counters) and float64 (for gauges and distributions). +type MetricValue struct { + value attribute.Value +} + +// Int64MetricValue creates a MetricValue from an int64. +// Used for counter metrics to preserve full int64 precision. +func Int64MetricValue(v int64) MetricValue { + return MetricValue{value: attribute.Int64Value(v)} +} + +// Float64MetricValue creates a MetricValue from a float64. +// Used for gauge and distribution metrics. +func Float64MetricValue(v float64) MetricValue { + return MetricValue{value: attribute.Float64Value(v)} +} + +// Type returns the type of the stored value (attribute.INT64 or attribute.FLOAT64). +func (v MetricValue) Type() attribute.Type { + return v.value.Type() +} + +// Int64 returns the value as int64 if it holds an int64. +// The second return value indicates whether the type matched. +func (v MetricValue) Int64() (int64, bool) { + if v.value.Type() == attribute.INT64 { + return v.value.AsInt64(), true + } + return 0, false +} + +// Float64 returns the value as float64 if it holds a float64. +// The second return value indicates whether the type matched. +func (v MetricValue) Float64() (float64, bool) { + if v.value.Type() == attribute.FLOAT64 { + return v.value.AsFloat64(), true + } + return 0, false +} + +// AsInterface returns the value as int64 or float64. +// Use type assertion or type switch to handle the result. +func (v MetricValue) AsInterface() any { + return v.value.AsInterface() +} + +// MarshalJSON serializes the value as a bare number. +func (v MetricValue) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value.AsInterface()) +} + +// MakeSerializationSafe pre-serializes all fields containing user mutable data to json.RawMessage, preventing race +// conditions when the event is later serialized on a background goroutine. +func (e *Event) MakeSerializationSafe() { + if len(e.Tags) > 0 { + if b, err := json.Marshal(e.Tags); err == nil { + e.serializedTags = b + } + } + + if len(e.Contexts) > 0 { + if b, err := json.Marshal(e.Contexts); err == nil { + e.serializedContexts = b + } + } + + if len(e.Breadcrumbs) > 0 { + if b, err := json.Marshal(e.Breadcrumbs); err == nil { + e.serializedBreadcrumbs = b + } + } + + if len(e.Exception) > 0 { + if b, err := json.Marshal(e.Exception); err == nil { + e.serializedException = b + } + } + + if !e.User.IsEmpty() { + if b, err := json.Marshal(e.User); err == nil { + e.serializedUser = b + } + } + + for _, span := range e.Spans { + span.makeSerializationSafe() + } + + e.serializationSafe = true +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/debug/transport.go b/vendor/github.com/getsentry/sentry-go/internal/debug/transport.go new file mode 100644 index 0000000..199c3a3 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/debug/transport.go @@ -0,0 +1,79 @@ +package debug + +import ( + "bytes" + "fmt" + "io" + "net/http" + "net/http/httptrace" + "net/http/httputil" +) + +// Transport implements http.RoundTripper and can be used to wrap other HTTP +// transports for debugging, normally http.DefaultTransport. +type Transport struct { + http.RoundTripper + Output io.Writer + // Dump controls whether to dump HTTP request and responses. + Dump bool + // Trace enables usage of net/http/httptrace. + Trace bool +} + +func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { + var buf bytes.Buffer + if t.Dump { + b, err := httputil.DumpRequestOut(req, true) + if err != nil { + panic(err) + } + _, err = buf.Write(ensureTrailingNewline(b)) + if err != nil { + panic(err) + } + } + if t.Trace { + trace := &httptrace.ClientTrace{ + DNSDone: func(di httptrace.DNSDoneInfo) { + fmt.Fprintf(&buf, "* DNS %v → %v\n", req.Host, di.Addrs) + }, + GotConn: func(ci httptrace.GotConnInfo) { + fmt.Fprintf(&buf, "* Connection local=%v remote=%v", ci.Conn.LocalAddr(), ci.Conn.RemoteAddr()) + if ci.Reused { + fmt.Fprint(&buf, " (reused)") + } + if ci.WasIdle { + fmt.Fprintf(&buf, " (idle %v)", ci.IdleTime) + } + fmt.Fprintln(&buf) + }, + } + req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) + } + resp, err := t.RoundTripper.RoundTrip(req) + if err != nil { + return nil, err + } + if t.Dump { + b, err := httputil.DumpResponse(resp, true) + if err != nil { + panic(err) + } + _, err = buf.Write(ensureTrailingNewline(b)) + if err != nil { + panic(err) + } + } + _, err = io.Copy(t.Output, &buf) + if err != nil { + panic(err) + } + return resp, nil +} + +func ensureTrailingNewline(b []byte) []byte { + if len(b) > 0 && b[len(b)-1] != '\n' { + b = append(b, '\n') + } + return b +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go b/vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go new file mode 100644 index 0000000..37fa4d0 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/debuglog/log.go @@ -0,0 +1,35 @@ +package debuglog + +import ( + "io" + "log" +) + +// logger is the global debug logger instance. +var logger = log.New(io.Discard, "[Sentry] ", log.LstdFlags) + +// SetOutput changes the output destination of the logger. +func SetOutput(w io.Writer) { + logger.SetOutput(w) +} + +// GetLogger returns the current logger instance. +// This function is thread-safe and can be called concurrently. +func GetLogger() *log.Logger { + return logger +} + +// Printf calls Printf on the underlying logger. +func Printf(format string, args ...interface{}) { + logger.Printf(format, args...) +} + +// Println calls Println on the underlying logger. +func Println(args ...interface{}) { + logger.Println(args...) +} + +// Print calls Print on the underlying logger. +func Print(args ...interface{}) { + logger.Print(args...) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/http/transport.go b/vendor/github.com/getsentry/sentry-go/internal/http/transport.go new file mode 100644 index 0000000..8dbfe03 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/http/transport.go @@ -0,0 +1,642 @@ +package http + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "net/http" + "net/url" + "sync" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/internal/util" + "github.com/getsentry/sentry-go/report" +) + +const ( + apiVersion = 7 + + defaultTimeout = time.Second * 30 + defaultQueueSize = 1000 + defaultClientReportsTick = time.Second * 30 +) + +var ( + ErrTransportQueueFull = errors.New("transport queue full") + ErrTransportClosed = errors.New("transport is closed") + ErrEmptyEnvelope = errors.New("empty envelope provided") +) + +type TransportOptions struct { + Dsn string + HTTPClient *http.Client + HTTPTransport http.RoundTripper + HTTPProxy string + HTTPSProxy string + CaCerts *x509.CertPool + Recorder report.ClientReportRecorder + Provider report.ClientReportProvider + SdkInfo func() *protocol.SdkInfo +} + +func getProxyConfig(options TransportOptions) func(*http.Request) (*url.URL, error) { + if len(options.HTTPSProxy) > 0 { + return func(*http.Request) (*url.URL, error) { + return url.Parse(options.HTTPSProxy) + } + } + + if len(options.HTTPProxy) > 0 { + return func(*http.Request) (*url.URL, error) { + return url.Parse(options.HTTPProxy) + } + } + + return http.ProxyFromEnvironment +} + +func getTLSConfig(options TransportOptions) *tls.Config { + if options.CaCerts != nil { + return &tls.Config{ + RootCAs: options.CaCerts, + MinVersion: tls.VersionTLS12, + } + } + + return nil +} + +func getSentryRequestFromEnvelope(ctx context.Context, dsn *protocol.Dsn, envelope *protocol.Envelope) (r *http.Request, err error) { + defer func() { + if r != nil { + var sdkName, sdkVersion string + if envelope.Header.Sdk != nil { + sdkVersion = envelope.Header.Sdk.Version + sdkName = envelope.Header.Sdk.Name + } + + r.Header.Set("User-Agent", fmt.Sprintf("%s/%s", sdkName, sdkVersion)) + r.Header.Set("Content-Type", "application/x-sentry-envelope") + + auth := fmt.Sprintf("Sentry sentry_version=%d, "+ + "sentry_client=%s/%s, sentry_key=%s", apiVersion, sdkName, sdkVersion, dsn.GetPublicKey()) + + if dsn.GetSecretKey() != "" { + auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.GetSecretKey()) + } + + r.Header.Set("X-Sentry-Auth", auth) + } + }() + + var buf bytes.Buffer + _, err = envelope.WriteTo(&buf) + if err != nil { + return nil, err + } + + return http.NewRequestWithContext( + ctx, + http.MethodPost, + dsn.GetAPIURL().String(), + &buf, + ) +} + +func categoryFromEnvelope(envelope *protocol.Envelope) ratelimit.Category { + if envelope == nil || len(envelope.Items) == 0 { + return ratelimit.CategoryAll + } + + for _, item := range envelope.Items { + if item == nil || item.Header == nil { + continue + } + + switch item.Header.Type { + case protocol.EnvelopeItemTypeEvent: + return ratelimit.CategoryError + case protocol.EnvelopeItemTypeTransaction: + return ratelimit.CategoryTransaction + case protocol.EnvelopeItemTypeCheckIn: + return ratelimit.CategoryMonitor + case protocol.EnvelopeItemTypeLog: + return ratelimit.CategoryLog + case protocol.EnvelopeItemTypeAttachment: + continue + default: + return ratelimit.CategoryAll + } + } + + return ratelimit.CategoryAll +} + +// SyncTransport is a blocking implementation of Transport. +// +// Clients using this transport will send requests to Sentry sequentially and +// block until a response is returned. +// +// The blocking behavior is useful in a limited set of use cases. For example, +// use it when deploying code to a Function as a Service ("Serverless") +// platform, where any work happening in a background goroutine is not +// guaranteed to execute. +// +// For most cases, prefer AsyncTransport. +type SyncTransport struct { + dsn *protocol.Dsn + client *http.Client + transport http.RoundTripper + recorder report.ClientReportRecorder + provider report.ClientReportProvider + sdkInfo func() *protocol.SdkInfo + + mu sync.Mutex + limits ratelimit.Map + + Timeout time.Duration +} + +func NewSyncTransport(options TransportOptions) protocol.TelemetryTransport { + dsn, err := protocol.NewDsn(options.Dsn) + if err != nil || dsn == nil { + debuglog.Printf("Transport is disabled: invalid dsn: %v\n", err) + return NewNoopTransport() + } + + recorder := options.Recorder + if recorder == nil { + recorder = report.NoopRecorder() + } + provider := options.Provider + if provider == nil { + provider = report.NoopProvider() + } + + transport := &SyncTransport{ + Timeout: defaultTimeout, + limits: make(ratelimit.Map), + dsn: dsn, + recorder: recorder, + provider: provider, + sdkInfo: options.SdkInfo, + } + + if options.HTTPTransport != nil { + transport.transport = options.HTTPTransport + } else { + transport.transport = &http.Transport{ + Proxy: getProxyConfig(options), + TLSClientConfig: getTLSConfig(options), + } + } + + if options.HTTPClient != nil { + transport.client = options.HTTPClient + } else { + transport.client = &http.Client{ + Transport: transport.transport, + Timeout: transport.Timeout, + } + } + + return transport +} + +func (t *SyncTransport) SendEnvelope(envelope *protocol.Envelope) error { + return t.SendEnvelopeWithContext(context.Background(), envelope) +} + +func (t *SyncTransport) Close() {} + +func (t *SyncTransport) IsRateLimited(category ratelimit.Category) bool { + return t.disabled(category) +} + +func (t *SyncTransport) HasCapacity() bool { return true } + +func (t *SyncTransport) SendEnvelopeWithContext(ctx context.Context, envelope *protocol.Envelope) error { + if envelope == nil || len(envelope.Items) == 0 { + return ErrEmptyEnvelope + } + + category := categoryFromEnvelope(envelope) + if t.disabled(category) { + t.recorder.RecordForEnvelope(report.ReasonRateLimitBackoff, envelope) + return nil + } + // the sync transport needs to attach client reports when available + t.provider.AttachToEnvelope(envelope) + + request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope) + if err != nil { + debuglog.Printf("There was an issue creating the request: %v", err) + t.recorder.RecordForEnvelope(report.ReasonInternalError, envelope) + return err + } + identifier := util.EnvelopeIdentifier(envelope) + debuglog.Printf( + "Sending %s to %s project: %s", + identifier, + t.dsn.GetHost(), + t.dsn.GetProjectID(), + ) + + result, err := util.DoSendRequest(t.client, request, identifier) + if err != nil { + debuglog.Printf("There was an issue with sending an event: %v", err) + t.recorder.RecordForEnvelope(report.ReasonNetworkError, envelope) + return err + } + if result.IsSendError() { + t.recorder.RecordForEnvelope(report.ReasonSendError, envelope) + } + + t.mu.Lock() + t.limits.Merge(result.Limits) + t.mu.Unlock() + + return nil +} + +func (t *SyncTransport) Flush(_ time.Duration) bool { + return true +} + +func (t *SyncTransport) FlushWithContext(_ context.Context) bool { + return true +} + +func (t *SyncTransport) disabled(c ratelimit.Category) bool { + t.mu.Lock() + defer t.mu.Unlock() + disabled := t.limits.IsRateLimited(c) + if disabled { + debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) + } + return disabled +} + +// AsyncTransport is the default, non-blocking, implementation of Transport. +// +// Clients using this transport will enqueue requests in a queue and return to +// the caller before any network communication has happened. Requests are sent +// to Sentry sequentially from a background goroutine. +type AsyncTransport struct { + dsn *protocol.Dsn + client *http.Client + transport http.RoundTripper + recorder report.ClientReportRecorder + provider report.ClientReportProvider + sdkInfo func() *protocol.SdkInfo + + queue chan *protocol.Envelope + + mu sync.RWMutex + limits ratelimit.Map + + done chan struct{} + wg sync.WaitGroup + + flushRequest chan chan struct{} + + closeMu sync.RWMutex + + QueueSize int + Timeout time.Duration + + startOnce sync.Once + closeOnce sync.Once +} + +func NewAsyncTransport(options TransportOptions) protocol.TelemetryTransport { + dsn, err := protocol.NewDsn(options.Dsn) + if err != nil || dsn == nil { + debuglog.Printf("Transport is disabled: invalid dsn: %v", err) + return NewNoopTransport() + } + + recorder := options.Recorder + if recorder == nil { + recorder = report.NoopRecorder() + } + provider := options.Provider + if provider == nil { + provider = report.NoopProvider() + } + + transport := &AsyncTransport{ + QueueSize: defaultQueueSize, + Timeout: defaultTimeout, + done: make(chan struct{}), + limits: make(ratelimit.Map), + dsn: dsn, + recorder: recorder, + provider: provider, + sdkInfo: options.SdkInfo, + } + + transport.queue = make(chan *protocol.Envelope, transport.QueueSize) + transport.flushRequest = make(chan chan struct{}) + + if options.HTTPTransport != nil { + transport.transport = options.HTTPTransport + } else { + transport.transport = &http.Transport{ + Proxy: getProxyConfig(options), + TLSClientConfig: getTLSConfig(options), + } + } + + if options.HTTPClient != nil { + transport.client = options.HTTPClient + } else { + transport.client = &http.Client{ + Transport: transport.transport, + Timeout: transport.Timeout, + } + } + + transport.start() + return transport +} + +func (t *AsyncTransport) start() { + t.startOnce.Do(func() { + if t.recorder == nil { + t.recorder = report.NoopRecorder() + } + if t.provider == nil { + t.provider = report.NoopProvider() + } + t.wg.Add(1) + go t.worker() + }) +} + +// HasCapacity reports whether the async transport queue appears to have space +// for at least one more envelope. This is a best-effort, non-blocking check. +func (t *AsyncTransport) HasCapacity() bool { + t.mu.RLock() + defer t.mu.RUnlock() + select { + case <-t.done: + return false + default: + } + return len(t.queue) < cap(t.queue) +} + +func (t *AsyncTransport) SendEnvelope(envelope *protocol.Envelope) error { + t.closeMu.RLock() + defer t.closeMu.RUnlock() + + select { + case <-t.done: + return ErrTransportClosed + default: + } + + if envelope == nil || len(envelope.Items) == 0 { + return ErrEmptyEnvelope + } + + category := categoryFromEnvelope(envelope) + if t.isRateLimited(category) { + t.recorder.RecordForEnvelope(report.ReasonRateLimitBackoff, envelope) + return nil + } + + identifier := util.EnvelopeIdentifier(envelope) + + select { + case <-t.done: + return ErrTransportClosed + case t.queue <- envelope: + debuglog.Printf( + "Sending %s to %s project: %s", + identifier, + t.dsn.GetHost(), + t.dsn.GetProjectID(), + ) + return nil + default: + t.recorder.RecordForEnvelope(report.ReasonQueueOverflow, envelope) + return ErrTransportQueueFull + } +} + +func (t *AsyncTransport) Flush(timeout time.Duration) bool { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return t.FlushWithContext(ctx) +} + +func (t *AsyncTransport) FlushWithContext(ctx context.Context) bool { + t.closeMu.RLock() + defer t.closeMu.RUnlock() + + flushResponse := make(chan struct{}) + select { + case <-t.done: + debuglog.Println("Failed to flush, transport is closed.") + return false + case t.flushRequest <- flushResponse: + select { + case <-flushResponse: + debuglog.Println("Buffer flushed successfully.") + return true + case <-ctx.Done(): + debuglog.Println("Failed to flush, buffer timed out.") + return false + } + case <-ctx.Done(): + debuglog.Println("Failed to flush, buffer timed out.") + return false + } +} + +func (t *AsyncTransport) Close() { + t.closeOnce.Do(func() { + t.closeMu.Lock() + defer t.closeMu.Unlock() + + close(t.done) + t.wg.Wait() + }) +} + +func (t *AsyncTransport) IsRateLimited(category ratelimit.Category) bool { + return t.isRateLimited(category) +} + +func (t *AsyncTransport) resolveSdkInfo() *protocol.SdkInfo { + if t.sdkInfo == nil { + return &protocol.SdkInfo{} + } + return t.sdkInfo() +} + +func (t *AsyncTransport) worker() { + defer t.wg.Done() + + crTicker := time.NewTicker(defaultClientReportsTick) + defer crTicker.Stop() + + for { + select { + case <-t.done: + return + case <-crTicker.C: + t.sendClientReport() + case envelope, open := <-t.queue: + if !open { + return + } + t.sendEnvelopeHTTP(envelope) + case flushResponse, open := <-t.flushRequest: + if !open { + return + } + t.drainQueue() + close(flushResponse) + } + } +} + +// sendClientReport sends a standalone envelope containing only a client report. +func (t *AsyncTransport) sendClientReport() { + r := t.provider.TakeReport() + if r == nil { + return + } + item, err := r.ToEnvelopeItem() + if err != nil { + debuglog.Printf("Failed to serialize client report: %v", err) + return + } + header := &protocol.EnvelopeHeader{ + SentAt: time.Now(), + Dsn: t.dsn, + Sdk: t.resolveSdkInfo(), + } + envelope := protocol.NewEnvelope(header) + envelope.AddItem(item) + + ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) + defer cancel() + + request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope) + if err != nil { + debuglog.Printf("Failed to create client report request: %v", err) + return + } + result, err := util.DoSendRequest(t.client, request, "client report") + if err != nil { + debuglog.Printf("Failed to send client report: %v", err) + return + } + + t.mu.Lock() + t.limits.Merge(result.Limits) + t.mu.Unlock() +} + +func (t *AsyncTransport) drainQueue() { + for { + select { + case envelope, open := <-t.queue: + if !open { + return + } + t.sendEnvelopeHTTP(envelope) + default: + return + } + } +} + +func (t *AsyncTransport) sendEnvelopeHTTP(envelope *protocol.Envelope) bool { //nolint: unparam + category := categoryFromEnvelope(envelope) + if t.isRateLimited(category) { + t.recorder.RecordForEnvelope(report.ReasonRateLimitBackoff, envelope) + return false + } + // attach to envelope after rate-limit check + t.provider.AttachToEnvelope(envelope) + + ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout) + defer cancel() + + request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope) + if err != nil { + debuglog.Printf("Failed to create request from envelope: %v", err) + t.recorder.RecordForEnvelope(report.ReasonInternalError, envelope) + return false + } + + identifier := util.EnvelopeIdentifier(envelope) + result, err := util.DoSendRequest(t.client, request, identifier) + if err != nil { + debuglog.Printf("HTTP request failed: %v", err) + t.recorder.RecordForEnvelope(report.ReasonNetworkError, envelope) + return false + } + if result.IsSendError() { + t.recorder.RecordForEnvelope(report.ReasonSendError, envelope) + } + + t.mu.Lock() + t.limits.Merge(result.Limits) + t.mu.Unlock() + + return result.Success +} + +func (t *AsyncTransport) isRateLimited(category ratelimit.Category) bool { + t.mu.RLock() + defer t.mu.RUnlock() + limited := t.limits.IsRateLimited(category) + if limited { + debuglog.Printf("Rate limited for category %q until %v", category, t.limits.Deadline(category)) + } + return limited +} + +// NoopTransport is a transport implementation that drops all events. +// Used internally when an empty or invalid DSN is provided. +type NoopTransport struct{} + +func NewNoopTransport() *NoopTransport { + debuglog.Println("Transport initialized with invalid DSN. Using NoopTransport. No events will be delivered.") + return &NoopTransport{} +} + +func (t *NoopTransport) SendEnvelope(_ *protocol.Envelope) error { + debuglog.Println("Envelope dropped due to NoopTransport usage.") + return nil +} + +func (t *NoopTransport) IsRateLimited(_ ratelimit.Category) bool { + return false +} + +func (t *NoopTransport) Flush(_ time.Duration) bool { + return true +} + +func (t *NoopTransport) FlushWithContext(_ context.Context) bool { + return true +} + +func (t *NoopTransport) Close() { + // Nothing to close +} + +func (t *NoopTransport) HasCapacity() bool { return true } diff --git a/vendor/github.com/getsentry/sentry-go/internal/httputils/body.go b/vendor/github.com/getsentry/sentry-go/internal/httputils/body.go new file mode 100644 index 0000000..4488c86 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/httputils/body.go @@ -0,0 +1,78 @@ +package httputils + +import ( + "bytes" + "io" +) + +// MaxBodyBytes is the maximum number of bytes the SDK captures from an HTTP +// body for attaching to events or spans. Bodies larger than this are dropped +// rather than truncated, to avoid invalid partial structured payloads. +const MaxBodyBytes = 10 * 1024 + +// ReadCloser combines an io.Reader and an io.Closer to implement io.ReadCloser. +type ReadCloser struct { + io.Reader + io.Closer +} + +// LimitedBuffer is like a bytes.Buffer, but limited to store at most Capacity +// bytes. Any writes past the capacity are silently discarded, similar to +// io.Discard. +type LimitedBuffer struct { + Capacity int + + bytes.Buffer + overflow bool +} + +// NewLimitedBuffer returns a LimitedBuffer with the given capacity. +func NewLimitedBuffer(capacity int) *LimitedBuffer { + return &LimitedBuffer{Capacity: capacity} +} + +// NewLimitedBufferFromBytes returns a LimitedBuffer initialized from b. +func NewLimitedBufferFromBytes(capacity int, b []byte) *LimitedBuffer { + buf := NewLimitedBuffer(capacity) + if len(b) > capacity { + buf.overflow = true + b = b[:capacity] + } + buf.Buffer = *bytes.NewBuffer(b) + return buf +} + +// Write implements io.Writer. +func (b *LimitedBuffer) Write(p []byte) (n int, err error) { + originalLen := len(p) + if b.overflow { + return originalLen, nil + } + left := b.Capacity - b.Len() + if left < 0 { + left = 0 + } + if len(p) > left { + b.overflow = true + p = p[:left] + } + _, err = b.Buffer.Write(p) + return originalLen, err +} + +// Overflow returns true if the LimitedBuffer discarded bytes written to it. +func (b *LimitedBuffer) Overflow() bool { + return b.overflow +} + +// ReadBody reads up to MaxBodyBytes from r and returns the bytes read. +func ReadBody(r io.Reader) []byte { + if r == nil { + return nil + } + data, err := io.ReadAll(io.LimitReader(r, MaxBodyBytes+1)) + if err != nil || len(data) == 0 || len(data) > MaxBodyBytes { + return nil + } + return data +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go b/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go new file mode 100644 index 0000000..51bf910 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/httputils/wrap_writer.go @@ -0,0 +1,199 @@ +package httputils + +import ( + "bufio" + "io" + "net" + "net/http" +) + +// This wrapper is derived from https://github.com/go-chi/chi/blob/master/middleware/wrap_writer.go +// Copyright (c) 2015-present Peter Kieltyka (https://github.com/pkieltyka), Google Inc. + +// MIT License + +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NewWrapResponseWriter wraps an http.ResponseWriter, returning a proxy that allows you to +// hook into various parts of the response process. + +func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWriter { + _, fl := w.(http.Flusher) + + bw := basicWriter{ResponseWriter: w, code: http.StatusOK} + + if protoMajor == 2 { + _, ps := w.(http.Pusher) + if fl && ps { + return &http2FancyWriter{bw} + } + } else { + _, hj := w.(http.Hijacker) + _, rf := w.(io.ReaderFrom) + if fl && hj && rf { + return &httpFancyWriter{bw} + } + } + if fl { + return &flushWriter{bw} + } + + return &bw +} + +// WrapResponseWriter is a proxy around an http.ResponseWriter that allows you to hook +// into various parts of the response process. +type WrapResponseWriter interface { + http.ResponseWriter + // Status returns the HTTP status of the request, or 200 if one has not + // yet been sent. + Status() int + // BytesWritten returns the total number of bytes sent to the client. + BytesWritten() int + // Tee causes the response body to be written to the given io.Writer in + // addition to proxying the writes through. Only one io.Writer can be + // tee'd to at once: setting a second one will overwrite the first. + // Writes will be sent to the proxy before being written to this + // io.Writer. It is illegal for the tee'd writer to be modified + // concurrently with writes. + Tee(io.Writer) + // Unwrap returns the original proxied target. + Unwrap() http.ResponseWriter +} + +// basicWriter wraps a http.ResponseWriter that implements the minimal +// http.ResponseWriter interface. +type basicWriter struct { + http.ResponseWriter + tee io.Writer + code int + bytes int + wroteHeader bool +} + +func (b *basicWriter) WriteHeader(code int) { + if !b.wroteHeader { + b.code = code + b.wroteHeader = true + } + b.ResponseWriter.WriteHeader(code) +} + +func (b *basicWriter) Write(buf []byte) (int, error) { + b.maybeWriteHeader() + n, err := b.ResponseWriter.Write(buf) + if b.tee != nil { + _, err2 := b.tee.Write(buf[:n]) + // Prefer errors generated by the proxied writer. + if err == nil { + err = err2 + } + } + b.bytes += n + return n, err +} + +func (b *basicWriter) maybeWriteHeader() { + if !b.wroteHeader { + b.WriteHeader(http.StatusOK) + } +} + +func (b *basicWriter) Status() int { + return b.code +} + +func (b *basicWriter) BytesWritten() int { + return b.bytes +} + +func (b *basicWriter) Tee(w io.Writer) { + b.tee = w +} + +func (b *basicWriter) Unwrap() http.ResponseWriter { + return b.ResponseWriter +} + +type flushWriter struct { + basicWriter +} + +func (f *flushWriter) Flush() { + f.wroteHeader = true + + fl := f.ResponseWriter.(http.Flusher) + fl.Flush() +} + +var _ http.Flusher = &flushWriter{} + +// httpFancyWriter is a HTTP writer that additionally satisfies +// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case +// of wrapping the http.ResponseWriter that package http gives you, in order to +// make the proxied object support the full method set of the proxied object. +type httpFancyWriter struct { + basicWriter +} + +func (f *httpFancyWriter) Flush() { + f.wroteHeader = true + f.ResponseWriter.(http.Flusher).Flush() +} + +func (f *httpFancyWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return f.ResponseWriter.(http.Hijacker).Hijack() +} + +func (f *http2FancyWriter) Push(target string, opts *http.PushOptions) error { + return f.ResponseWriter.(http.Pusher).Push(target, opts) +} + +func (f *httpFancyWriter) ReadFrom(r io.Reader) (int64, error) { + if f.tee != nil { + n, err := io.Copy(&f.basicWriter, r) + f.bytes += int(n) + return n, err + } + rf := f.ResponseWriter.(io.ReaderFrom) + f.maybeWriteHeader() + n, err := rf.ReadFrom(r) + f.bytes += int(n) + return n, err +} + +var _ http.Flusher = &httpFancyWriter{} +var _ http.Hijacker = &httpFancyWriter{} +var _ http.Pusher = &http2FancyWriter{} +var _ io.ReaderFrom = &httpFancyWriter{} + +// http2FancyWriter is a HTTP2 writer that additionally satisfies +// http.Flusher, and io.ReaderFrom. It exists for the common case +// of wrapping the http.ResponseWriter that package http gives you, in order to +// make the proxied object support the full method set of the proxied object. +type http2FancyWriter struct { + basicWriter +} + +func (f *http2FancyWriter) Flush() { + f.wroteHeader = true + + f.basicWriter.ResponseWriter.(http.Flusher).Flush() +} + +var _ http.Flusher = &http2FancyWriter{} diff --git a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md new file mode 100644 index 0000000..2718f31 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/README.md @@ -0,0 +1,12 @@ +## Why do we have this "otel/baggage" folder? + +The root sentry-go SDK (namely, the Dynamic Sampling functionality) needs an implementation of the [baggage spec](https://www.w3.org/TR/baggage/). +For that reason, we've taken the existing baggage implementation from the [opentelemetry-go](https://github.com/open-telemetry/opentelemetry-go/) repository, and fixed a few things that in our opinion were violating the specification. + +These issues are: +1. Baggage string value `one%20two` should be properly parsed as "one two" +1. Baggage string value `one+two` should be parsed as "one+two" +1. Go string value "one two" should be encoded as `one%20two` (percent encoding), and NOT as `one+two` (URL query encoding). +1. Go string value "1=1" might be encoded as `1=1`, because the spec says: "Note, value MAY contain any number of the equal sign (=) characters. Parsers MUST NOT assume that the equal sign is only used to separate key and value.". `1%3D1` is also valid, but to simplify the implementation we're not doing it. + +Changes were made in this PR: https://github.com/getsentry/sentry-go/pull/568 diff --git a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go new file mode 100644 index 0000000..1806555 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/baggage.go @@ -0,0 +1,604 @@ +// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/c21b6b6bb31a2f74edd06e262f1690f3f6ea3d5c/baggage/baggage.go +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package baggage + +import ( + "errors" + "fmt" + "net/url" + "regexp" + "strings" + "unicode/utf8" + + "github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage" +) + +const ( + maxMembers = 180 + maxBytesPerMembers = 4096 + maxBytesPerBaggageString = 8192 + + listDelimiter = "," + keyValueDelimiter = "=" + propertyDelimiter = ";" + + keyDef = `([\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5a\x5e-\x7a\x7c\x7e]+)` + valueDef = `([\x21\x23-\x2b\x2d-\x3a\x3c-\x5B\x5D-\x7e]*)` + keyValueDef = `\s*` + keyDef + `\s*` + keyValueDelimiter + `\s*` + valueDef + `\s*` +) + +var ( + keyRe = regexp.MustCompile(`^` + keyDef + `$`) + valueRe = regexp.MustCompile(`^` + valueDef + `$`) + propertyRe = regexp.MustCompile(`^(?:\s*` + keyDef + `\s*|` + keyValueDef + `)$`) +) + +var ( + errInvalidKey = errors.New("invalid key") + errInvalidValue = errors.New("invalid value") + errInvalidProperty = errors.New("invalid baggage list-member property") + errInvalidMember = errors.New("invalid baggage list-member") + errMemberNumber = errors.New("too many list-members in baggage-string") + errMemberBytes = errors.New("list-member too large") + errBaggageBytes = errors.New("baggage-string too large") +) + +// Property is an additional metadata entry for a baggage list-member. +type Property struct { + key, value string + + // hasValue indicates if a zero-value value means the property does not + // have a value or if it was the zero-value. + hasValue bool + + // hasData indicates whether the created property contains data or not. + // Properties that do not contain data are invalid with no other check + // required. + hasData bool +} + +// NewKeyProperty returns a new Property for key. +// +// If key is invalid, an error will be returned. +func NewKeyProperty(key string) (Property, error) { + if !keyRe.MatchString(key) { + return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) + } + + p := Property{key: key, hasData: true} + return p, nil +} + +// NewKeyValueProperty returns a new Property for key with value. +// +// If key or value are invalid, an error will be returned. +func NewKeyValueProperty(key, value string) (Property, error) { + if !keyRe.MatchString(key) { + return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidKey, key) + } + if !valueRe.MatchString(value) { + return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidValue, value) + } + + p := Property{ + key: key, + value: value, + hasValue: true, + hasData: true, + } + return p, nil +} + +func newInvalidProperty() Property { + return Property{} +} + +// parseProperty attempts to decode a Property from the passed string. It +// returns an error if the input is invalid according to the W3C Baggage +// specification. +func parseProperty(property string) (Property, error) { + if property == "" { + return newInvalidProperty(), nil + } + + match := propertyRe.FindStringSubmatch(property) + if len(match) != 4 { + return newInvalidProperty(), fmt.Errorf("%w: %q", errInvalidProperty, property) + } + + p := Property{hasData: true} + if match[1] != "" { + p.key = match[1] + } else { + p.key = match[2] + p.value = match[3] + p.hasValue = true + } + + return p, nil +} + +// validate ensures p conforms to the W3C Baggage specification, returning an +// error otherwise. +func (p Property) validate() error { + errFunc := func(err error) error { + return fmt.Errorf("invalid property: %w", err) + } + + if !p.hasData { + return errFunc(fmt.Errorf("%w: %q", errInvalidProperty, p)) + } + + if !keyRe.MatchString(p.key) { + return errFunc(fmt.Errorf("%w: %q", errInvalidKey, p.key)) + } + if p.hasValue && !valueRe.MatchString(p.value) { + return errFunc(fmt.Errorf("%w: %q", errInvalidValue, p.value)) + } + if !p.hasValue && p.value != "" { + return errFunc(errors.New("inconsistent value")) + } + return nil +} + +// Key returns the Property key. +func (p Property) Key() string { + return p.key +} + +// Value returns the Property value. Additionally, a boolean value is returned +// indicating if the returned value is the empty if the Property has a value +// that is empty or if the value is not set. +func (p Property) Value() (string, bool) { + return p.value, p.hasValue +} + +// String encodes Property into a string compliant with the W3C Baggage +// specification. +func (p Property) String() string { + if p.hasValue { + return fmt.Sprintf("%s%s%v", p.key, keyValueDelimiter, p.value) + } + return p.key +} + +type properties []Property + +func fromInternalProperties(iProps []baggage.Property) properties { + if len(iProps) == 0 { + return nil + } + + props := make(properties, len(iProps)) + for i, p := range iProps { + props[i] = Property{ + key: p.Key, + value: p.Value, + hasValue: p.HasValue, + } + } + return props +} + +func (p properties) asInternal() []baggage.Property { + if len(p) == 0 { + return nil + } + + iProps := make([]baggage.Property, len(p)) + for i, prop := range p { + iProps[i] = baggage.Property{ + Key: prop.key, + Value: prop.value, + HasValue: prop.hasValue, + } + } + return iProps +} + +func (p properties) Copy() properties { + if len(p) == 0 { + return nil + } + + props := make(properties, len(p)) + copy(props, p) + return props +} + +// validate ensures each Property in p conforms to the W3C Baggage +// specification, returning an error otherwise. +func (p properties) validate() error { + for _, prop := range p { + if err := prop.validate(); err != nil { + return err + } + } + return nil +} + +// String encodes properties into a string compliant with the W3C Baggage +// specification. +func (p properties) String() string { + props := make([]string, len(p)) + for i, prop := range p { + props[i] = prop.String() + } + return strings.Join(props, propertyDelimiter) +} + +// Member is a list-member of a baggage-string as defined by the W3C Baggage +// specification. +type Member struct { + key, value string + properties properties + + // hasData indicates whether the created property contains data or not. + // Properties that do not contain data are invalid with no other check + // required. + hasData bool +} + +// NewMember returns a new Member from the passed arguments. The key will be +// used directly while the value will be url decoded after validation. An error +// is returned if the created Member would be invalid according to the W3C +// Baggage specification. +func NewMember(key, value string, props ...Property) (Member, error) { + m := Member{ + key: key, + value: value, + properties: properties(props).Copy(), + hasData: true, + } + if err := m.validate(); err != nil { + return newInvalidMember(), err + } + //// NOTE(anton): I don't think we need to unescape here + // decodedValue, err := url.PathUnescape(value) + // if err != nil { + // return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) + // } + // m.value = decodedValue + return m, nil +} + +func newInvalidMember() Member { + return Member{} +} + +// parseMember attempts to decode a Member from the passed string. It returns +// an error if the input is invalid according to the W3C Baggage +// specification. +func parseMember(member string) (Member, error) { + if n := len(member); n > maxBytesPerMembers { + return newInvalidMember(), fmt.Errorf("%w: %d", errMemberBytes, n) + } + + var ( + key, value string + props properties + ) + + parts := strings.SplitN(member, propertyDelimiter, 2) + switch len(parts) { + case 2: + // Parse the member properties. + for _, pStr := range strings.Split(parts[1], propertyDelimiter) { + p, err := parseProperty(pStr) + if err != nil { + return newInvalidMember(), err + } + props = append(props, p) + } + fallthrough + case 1: + // Parse the member key/value pair. + + // Take into account a value can contain equal signs (=). + kv := strings.SplitN(parts[0], keyValueDelimiter, 2) + if len(kv) != 2 { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidMember, member) + } + // "Leading and trailing whitespaces are allowed but MUST be trimmed + // when converting the header into a data structure." + key = strings.TrimSpace(kv[0]) + value = strings.TrimSpace(kv[1]) + var err error + if !keyRe.MatchString(key) { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidKey, key) + } + if !valueRe.MatchString(value) { + return newInvalidMember(), fmt.Errorf("%w: %q", errInvalidValue, value) + } + decodedValue, err := url.PathUnescape(value) + if err != nil { + return newInvalidMember(), fmt.Errorf("%w: %q", err, value) + } + value = decodedValue + default: + // This should never happen unless a developer has changed the string + // splitting somehow. Panic instead of failing silently and allowing + // the bug to slip past the CI checks. + panic("failed to parse baggage member") + } + + return Member{key: key, value: value, properties: props, hasData: true}, nil +} + +// validate ensures m conforms to the W3C Baggage specification. +// A key is just an ASCII string, but a value must be URL encoded UTF-8, +// returning an error otherwise. +func (m Member) validate() error { + if !m.hasData { + return fmt.Errorf("%w: %q", errInvalidMember, m) + } + + if !keyRe.MatchString(m.key) { + return fmt.Errorf("%w: %q", errInvalidKey, m.key) + } + //// NOTE(anton): IMO it's too early to validate the value here. + // if !valueRe.MatchString(m.value) { + // return fmt.Errorf("%w: %q", errInvalidValue, m.value) + // } + return m.properties.validate() +} + +// Key returns the Member key. +func (m Member) Key() string { return m.key } + +// Value returns the Member value. +func (m Member) Value() string { return m.value } + +// Properties returns a copy of the Member properties. +func (m Member) Properties() []Property { return m.properties.Copy() } + +// String encodes Member into a string compliant with the W3C Baggage +// specification. +func (m Member) String() string { + // A key is just an ASCII string, but a value is URL encoded UTF-8. + s := fmt.Sprintf("%s%s%s", m.key, keyValueDelimiter, percentEncodeValue(m.value)) + if len(m.properties) > 0 { + s = fmt.Sprintf("%s%s%s", s, propertyDelimiter, m.properties.String()) + } + return s +} + +// percentEncodeValue encodes the baggage value, using percent-encoding for +// disallowed octets. +func percentEncodeValue(s string) string { + const upperhex = "0123456789ABCDEF" + var sb strings.Builder + + for byteIndex, width := 0, 0; byteIndex < len(s); byteIndex += width { + runeValue, w := utf8.DecodeRuneInString(s[byteIndex:]) + width = w + char := string(runeValue) + if valueRe.MatchString(char) && char != "%" { + // The character is returned as is, no need to percent-encode + sb.WriteString(char) + } else { + // We need to percent-encode each byte of the multi-octet character + for j := 0; j < width; j++ { + b := s[byteIndex+j] + sb.WriteByte('%') + // Bitwise operations are inspired by "net/url" + sb.WriteByte(upperhex[b>>4]) + sb.WriteByte(upperhex[b&15]) + } + } + } + return sb.String() +} + +// Baggage is a list of baggage members representing the baggage-string as +// defined by the W3C Baggage specification. +type Baggage struct { //nolint:golint + list baggage.List +} + +// New returns a new valid Baggage. It returns an error if it results in a +// Baggage exceeding limits set in that specification. +// +// It expects all the provided members to have already been validated. +func New(members ...Member) (Baggage, error) { + if len(members) == 0 { + return Baggage{}, nil + } + + b := make(baggage.List) + for _, m := range members { + if !m.hasData { + return Baggage{}, errInvalidMember + } + + // OpenTelemetry resolves duplicates by last-one-wins. + b[m.key] = baggage.Item{ + Value: m.value, + Properties: m.properties.asInternal(), + } + } + + // Check member numbers after deduplication. + if len(b) > maxMembers { + return Baggage{}, errMemberNumber + } + + bag := Baggage{b} + if n := len(bag.String()); n > maxBytesPerBaggageString { + return Baggage{}, fmt.Errorf("%w: %d", errBaggageBytes, n) + } + + return bag, nil +} + +// Parse attempts to decode a baggage-string from the passed string. It +// returns an error if the input is invalid according to the W3C Baggage +// specification. +// +// If there are duplicate list-members contained in baggage, the last one +// defined (reading left-to-right) will be the only one kept. This diverges +// from the W3C Baggage specification which allows duplicate list-members, but +// conforms to the OpenTelemetry Baggage specification. +func Parse(bStr string) (Baggage, error) { + if bStr == "" { + return Baggage{}, nil + } + + if n := len(bStr); n > maxBytesPerBaggageString { + return Baggage{}, fmt.Errorf("%w: %d", errBaggageBytes, n) + } + + b := make(baggage.List) + for _, memberStr := range strings.Split(bStr, listDelimiter) { + m, err := parseMember(memberStr) + if err != nil { + return Baggage{}, err + } + // OpenTelemetry resolves duplicates by last-one-wins. + b[m.key] = baggage.Item{ + Value: m.value, + Properties: m.properties.asInternal(), + } + } + + // OpenTelemetry does not allow for duplicate list-members, but the W3C + // specification does. Now that we have deduplicated, ensure the baggage + // does not exceed list-member limits. + if len(b) > maxMembers { + return Baggage{}, errMemberNumber + } + + return Baggage{b}, nil +} + +// Member returns the baggage list-member identified by key. +// +// If there is no list-member matching the passed key the returned Member will +// be a zero-value Member. +// The returned member is not validated, as we assume the validation happened +// when it was added to the Baggage. +func (b Baggage) Member(key string) Member { + v, ok := b.list[key] + if !ok { + // We do not need to worry about distinguishing between the situation + // where a zero-valued Member is included in the Baggage because a + // zero-valued Member is invalid according to the W3C Baggage + // specification (it has an empty key). + return newInvalidMember() + } + + return Member{ + key: key, + value: v.Value, + properties: fromInternalProperties(v.Properties), + hasData: true, + } +} + +// Members returns all the baggage list-members. +// The order of the returned list-members does not have significance. +// +// The returned members are not validated, as we assume the validation happened +// when they were added to the Baggage. +func (b Baggage) Members() []Member { + if len(b.list) == 0 { + return nil + } + + members := make([]Member, 0, len(b.list)) + for k, v := range b.list { + members = append(members, Member{ + key: k, + value: v.Value, + properties: fromInternalProperties(v.Properties), + hasData: true, + }) + } + return members +} + +// SetMember returns a copy the Baggage with the member included. If the +// baggage contains a Member with the same key the existing Member is +// replaced. +// +// If member is invalid according to the W3C Baggage specification, an error +// is returned with the original Baggage. +func (b Baggage) SetMember(member Member) (Baggage, error) { + if !member.hasData { + return b, errInvalidMember + } + + n := len(b.list) + if _, ok := b.list[member.key]; !ok { + n++ + } + list := make(baggage.List, n) + + for k, v := range b.list { + // Do not copy if we are just going to overwrite. + if k == member.key { + continue + } + list[k] = v + } + + list[member.key] = baggage.Item{ + Value: member.value, + Properties: member.properties.asInternal(), + } + + return Baggage{list: list}, nil +} + +// DeleteMember returns a copy of the Baggage with the list-member identified +// by key removed. +func (b Baggage) DeleteMember(key string) Baggage { + n := len(b.list) + if _, ok := b.list[key]; ok { + n-- + } + list := make(baggage.List, n) + + for k, v := range b.list { + if k == key { + continue + } + list[k] = v + } + + return Baggage{list: list} +} + +// Len returns the number of list-members in the Baggage. +func (b Baggage) Len() int { + return len(b.list) +} + +// String encodes Baggage into a string compliant with the W3C Baggage +// specification. The returned string will be invalid if the Baggage contains +// any invalid list-members. +func (b Baggage) String() string { + members := make([]string, 0, len(b.list)) + for k, v := range b.list { + members = append(members, Member{ + key: k, + value: v.Value, + properties: fromInternalProperties(v.Properties), + }.String()) + } + return strings.Join(members, listDelimiter) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go new file mode 100644 index 0000000..ea99ccb --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/otel/baggage/internal/baggage/baggage.go @@ -0,0 +1,45 @@ +// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/c21b6b6bb31a2f74edd06e262f1690f3f6ea3d5c/internal/baggage/baggage.go +// +// Copyright The OpenTelemetry Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* +Package baggage provides base types and functionality to store and retrieve +baggage in Go context. This package exists because the OpenTracing bridge to +OpenTelemetry needs to synchronize state whenever baggage for a context is +modified and that context contains an OpenTracing span. If it were not for +this need this package would not need to exist and the +`go.opentelemetry.io/otel/baggage` package would be the singular place where +W3C baggage is handled. +*/ +package baggage + +// List is the collection of baggage members. The W3C allows for duplicates, +// but OpenTelemetry does not, therefore, this is represented as a map. +type List map[string]Item + +// Item is the value and metadata properties part of a list-member. +type Item struct { + Value string + Properties []Property +} + +// Property is a metadata entry for a list-member. +type Property struct { + Key, Value string + + // HasValue indicates if a zero-value value means the property does not + // have a value or if it was the zero-value. + HasValue bool +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go new file mode 100644 index 0000000..b49e88c --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/dsn.go @@ -0,0 +1,261 @@ +package protocol + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" + "time" +) + +// apiVersion is the version of the Sentry API. +const apiVersion = "7" + +type scheme string + +const ( + SchemeHTTP scheme = "http" + SchemeHTTPS scheme = "https" +) + +func (scheme scheme) defaultPort() int { + switch scheme { + case SchemeHTTPS: + return 443 + case SchemeHTTP: + return 80 + default: + return 80 + } +} + +// DsnParseError represents an error that occurs if a Sentry +// DSN cannot be parsed. +type DsnParseError struct { + Message string +} + +func (e DsnParseError) Error() string { + return "[Sentry] DsnParseError: " + e.Message +} + +// Dsn is used as the remote address source to client transport. +type Dsn struct { + scheme scheme + publicKey string + secretKey string + host string + port int + path string + projectID string + orgID uint64 +} + +// NewDsn creates a Dsn by parsing rawURL. Most users will never call this +// function directly. It is provided for use in custom Transport +// implementations. +func NewDsn(rawURL string) (*Dsn, error) { + // Parse + parsedURL, err := url.Parse(rawURL) + if err != nil { + return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)} + } + + // Scheme + var scheme scheme + switch parsedURL.Scheme { + case "http": + scheme = SchemeHTTP + case "https": + scheme = SchemeHTTPS + default: + return nil, &DsnParseError{"invalid scheme"} + } + + // PublicKey + publicKey := parsedURL.User.Username() + if publicKey == "" { + return nil, &DsnParseError{"empty username"} + } + + // SecretKey + var secretKey string + if parsedSecretKey, ok := parsedURL.User.Password(); ok { + secretKey = parsedSecretKey + } + + // Host + host := parsedURL.Hostname() + if host == "" { + return nil, &DsnParseError{"empty host"} + } + + // OrgID (optional) + var orgID uint64 + parts := strings.Split(host, ".") + orgPart := parts[0] + if len(orgPart) >= 2 && orgPart[0] == 'o' { + parsedOrgID, err := strconv.ParseUint(orgPart[1:], 10, 64) + if err == nil { + orgID = parsedOrgID + } + } + + // Port + var port int + if p := parsedURL.Port(); p != "" { + port, err = strconv.Atoi(p) + if err != nil { + return nil, &DsnParseError{"invalid port"} + } + } else { + port = scheme.defaultPort() + } + + // ProjectID + if parsedURL.Path == "" || parsedURL.Path == "/" { + return nil, &DsnParseError{"empty project id"} + } + pathSegments := strings.Split(parsedURL.Path[1:], "/") + projectID := pathSegments[len(pathSegments)-1] + + if projectID == "" { + return nil, &DsnParseError{"empty project id"} + } + + // Path + var path string + if len(pathSegments) > 1 { + path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/") + } + + return &Dsn{ + scheme: scheme, + publicKey: publicKey, + secretKey: secretKey, + host: host, + port: port, + path: path, + projectID: projectID, + orgID: orgID, + }, nil +} + +// String formats Dsn struct into a valid string url. +func (dsn Dsn) String() string { + var url string + url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey) + if dsn.secretKey != "" { + url += fmt.Sprintf(":%s", dsn.secretKey) + } + url += fmt.Sprintf("@%s", dsn.host) + if dsn.port != dsn.scheme.defaultPort() { + url += fmt.Sprintf(":%d", dsn.port) + } + if dsn.path != "" { + url += dsn.path + } + url += fmt.Sprintf("/%s", dsn.projectID) + return url +} + +// Get the scheme of the DSN. +func (dsn Dsn) GetScheme() string { + return string(dsn.scheme) +} + +// Get the public key of the DSN. +func (dsn Dsn) GetPublicKey() string { + return dsn.publicKey +} + +// Get the secret key of the DSN. +func (dsn Dsn) GetSecretKey() string { + return dsn.secretKey +} + +// Get the host of the DSN. +func (dsn Dsn) GetHost() string { + return dsn.host +} + +// Get the port of the DSN. +func (dsn Dsn) GetPort() int { + return dsn.port +} + +// Get the path of the DSN. +func (dsn Dsn) GetPath() string { + return dsn.path +} + +// Get the project ID of the DSN. +func (dsn Dsn) GetProjectID() string { + return dsn.projectID +} + +// GetOrgID returns the orgID that was parsed from the DSN. +func (dsn Dsn) GetOrgID() uint64 { + return dsn.orgID +} + +// SetOrgID sets the orgID used for trace continuation. +// +// This function is used for overriding the orgID parsed from the DSN. +func (dsn *Dsn) SetOrgID(orgID uint64) { + dsn.orgID = orgID +} + +// GetAPIURL returns the URL of the envelope endpoint of the project +// associated with the DSN. +func (dsn Dsn) GetAPIURL() *url.URL { + var rawURL string + rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host) + if dsn.port != dsn.scheme.defaultPort() { + rawURL += fmt.Sprintf(":%d", dsn.port) + } + if dsn.path != "" { + rawURL += dsn.path + } + rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope") + parsedURL, _ := url.Parse(rawURL) + return parsedURL +} + +// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events +// to the /store endpoint. +// +// Deprecated: This method shall only be used if you want to implement your own transport that sends events to +// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate +// against the /envelope endpoint are added automatically. +func (dsn Dsn) RequestHeaders(sdkVersion string) map[string]string { + auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+ + "sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), sdkVersion, dsn.publicKey) + + if dsn.secretKey != "" { + auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey) + } + + return map[string]string{ + "Content-Type": "application/json", + "X-Sentry-Auth": auth, + } +} + +// MarshalJSON converts the Dsn struct to JSON. +func (dsn Dsn) MarshalJSON() ([]byte, error) { + return json.Marshal(dsn.String()) +} + +// UnmarshalJSON converts JSON data to the Dsn struct. +func (dsn *Dsn) UnmarshalJSON(data []byte) error { + var str string + _ = json.Unmarshal(data, &str) + newDsn, err := NewDsn(str) + if err != nil { + return err + } + *dsn = *newDsn + return nil +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go new file mode 100644 index 0000000..024053c --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/envelope.go @@ -0,0 +1,258 @@ +package protocol + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "time" +) + +// Envelope represents a Sentry envelope containing headers and items. +type Envelope struct { + Header *EnvelopeHeader `json:"-"` + Items []*EnvelopeItem `json:"-"` +} + +// EnvelopeHeader represents the header of a Sentry envelope. +type EnvelopeHeader struct { + // EventID is the unique identifier for this event + EventID string `json:"event_id,omitempty"` + + // SentAt is the timestamp when the event was sent from the SDK as string in RFC 3339 format. + // Used for clock drift correction of the event timestamp. The time zone must be UTC. + SentAt time.Time `json:"sent_at,omitzero"` + + // Dsn can be used for self-authenticated envelopes. + // This means that the envelope has all the information necessary to be sent to sentry. + // In this case the full DSN must be stored in this key. + Dsn *Dsn `json:"dsn,omitempty"` + + // Sdk carries the same payload as the sdk interface in the event payload but can be carried for all events. + // This means that SDK information can be carried for minidumps, session data and other submissions. + Sdk *SdkInfo `json:"sdk,omitempty"` + + // Trace contains the [Dynamic Sampling Context](https://develop.sentry.dev/sdk/telemetry/traces/dynamic-sampling-context/) + Trace map[string]string `json:"trace,omitempty"` +} + +// EnvelopeItemType represents the type of envelope item. +type EnvelopeItemType string + +// Constants for envelope item types as defined in the Sentry documentation. +const ( + EnvelopeItemTypeEvent EnvelopeItemType = "event" + EnvelopeItemTypeTransaction EnvelopeItemType = "transaction" + EnvelopeItemTypeCheckIn EnvelopeItemType = "check_in" + EnvelopeItemTypeAttachment EnvelopeItemType = "attachment" + EnvelopeItemTypeLog EnvelopeItemType = "log" + EnvelopeItemTypeTraceMetric EnvelopeItemType = "trace_metric" + EnvelopeItemTypeClientReport EnvelopeItemType = "client_report" +) + +// EnvelopeItemHeader represents the header of an envelope item. +type EnvelopeItemHeader struct { + // Type specifies the type of this Item and its contents. + // Based on the Item type, more headers may be required. + Type EnvelopeItemType `json:"type"` + + // Length is the length of the payload in bytes. + // If no length is specified, the payload implicitly goes to the next newline. + // For payloads containing newline characters, the length must be specified. + Length *int `json:"length,omitempty"` + + // Filename is the name of the attachment file (used for attachments) + Filename string `json:"filename,omitempty"` + + // ContentType is the MIME type of the item payload (used for attachments and some other item types) + ContentType string `json:"content_type,omitempty"` + + // ItemCount is the number of items in a batch (used for logs) + ItemCount *int `json:"item_count,omitempty"` + + // SpanCount is the number of spans in a transaction (used for client reports) + SpanCount int `json:"-"` +} + +// EnvelopeItem represents a single item or batch within an envelope. +type EnvelopeItem struct { + Header *EnvelopeItemHeader `json:"-"` + Payload []byte `json:"-"` +} + +// NewEnvelope creates a new envelope with the given header and items. +func NewEnvelope(header *EnvelopeHeader, items ...*EnvelopeItem) *Envelope { + envelope := &Envelope{ + Header: header, + Items: make([]*EnvelopeItem, 0, len(items)), + } + for _, item := range items { + envelope.AddItem(item) + } + return envelope +} + +// AddItem adds an item to the envelope. +func (e *Envelope) AddItem(item *EnvelopeItem) { + if item == nil { + return + } + e.Items = append(e.Items, item) +} + +// Serialize serializes the envelope to the Sentry envelope format. +// +// Format: Headers "\n" { Item } [ "\n" ] +// Item: Headers "\n" Payload "\n". +func (e *Envelope) Serialize() ([]byte, error) { + var buf bytes.Buffer + + headerBytes, err := json.Marshal(e.Header) + if err != nil { + return nil, fmt.Errorf("failed to marshal envelope header: %w", err) + } + + if _, err := buf.Write(headerBytes); err != nil { + return nil, fmt.Errorf("failed to write envelope header: %w", err) + } + + if _, err := buf.WriteString("\n"); err != nil { + return nil, fmt.Errorf("failed to write newline after envelope header: %w", err) + } + + for _, item := range e.Items { + if err := e.writeItem(&buf, item); err != nil { + return nil, fmt.Errorf("failed to write envelope item: %w", err) + } + } + + return buf.Bytes(), nil +} + +// WriteTo writes the envelope to the given writer in the Sentry envelope format. +func (e *Envelope) WriteTo(w io.Writer) (int64, error) { + data, err := e.Serialize() + if err != nil { + return 0, err + } + + n, err := w.Write(data) + return int64(n), err +} + +// writeItem writes a single envelope item to the buffer. +func (e *Envelope) writeItem(buf *bytes.Buffer, item *EnvelopeItem) error { + headerBytes, err := json.Marshal(item.Header) + if err != nil { + return fmt.Errorf("failed to marshal item header: %w", err) + } + + if _, err := buf.Write(headerBytes); err != nil { + return fmt.Errorf("failed to write item header: %w", err) + } + + if _, err := buf.WriteString("\n"); err != nil { + return fmt.Errorf("failed to write newline after item header: %w", err) + } + + if len(item.Payload) > 0 { + if _, err := buf.Write(item.Payload); err != nil { + return fmt.Errorf("failed to write item payload: %w", err) + } + } + + if _, err := buf.WriteString("\n"); err != nil { + return fmt.Errorf("failed to write newline after item payload: %w", err) + } + + return nil +} + +// Size returns the total size of the envelope when serialized. +func (e *Envelope) Size() (int, error) { + data, err := e.Serialize() + if err != nil { + return 0, err + } + return len(data), nil +} + +// NewEnvelopeItem creates a new envelope item with the specified type and payload. +func NewEnvelopeItem(itemType EnvelopeItemType, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: itemType, + Length: &length, + }, + Payload: payload, + } +} + +// NewTransactionItem creates a new envelope item including the span count of the transaction. +func NewTransactionItem(spanCount int, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeTransaction, + Length: &length, + SpanCount: spanCount, + }, + Payload: payload, + } +} + +// NewAttachmentItem creates a new envelope item for an attachment. +// Parameters: filename, contentType, payload. +func NewAttachmentItem(filename, contentType string, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeAttachment, + Length: &length, + ContentType: contentType, + Filename: filename, + }, + Payload: payload, + } +} + +// NewLogItem creates a new envelope item for logs. +func NewLogItem(itemCount int, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeLog, + Length: &length, + ItemCount: &itemCount, + ContentType: "application/vnd.sentry.items.log+json", + }, + Payload: payload, + } +} + +// NewTraceMetricItem creates a new envelope item for trace metrics. +func NewTraceMetricItem(itemCount int, payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeTraceMetric, + Length: &length, + ItemCount: &itemCount, + ContentType: "application/vnd.sentry.items.trace-metric+json", + }, + Payload: payload, + } +} + +// NewClientReportItem creates a new envelope item for client reports. +func NewClientReportItem(payload []byte) *EnvelopeItem { + length := len(payload) + return &EnvelopeItem{ + Header: &EnvelopeItemHeader{ + Type: EnvelopeItemTypeClientReport, + Length: &length, + }, + Payload: payload, + } +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go new file mode 100644 index 0000000..2db5623 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/interfaces.go @@ -0,0 +1,60 @@ +package protocol + +import ( + "context" + "time" + + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// TelemetryItem represents any telemetry data that can be stored in buffers. +type TelemetryItem interface { + // GetCategory returns the rate limit category for this item. + GetCategory() ratelimit.Category + + // MakeSerializationSafe prevents serialization races, by serializing user mutable data on the foreground. + // Should be used before passing telemetry to the processor. + MakeSerializationSafe() +} + +// EnvelopeConvertible represents items that can convert themselves to envelopes. +type EnvelopeConvertible interface { + // GetCategory returns the rate limit category for this item. + GetCategory() ratelimit.Category + + // GetEventID returns the event ID for this item. + GetEventID() string + + // GetSdkInfo returns SDK information for the envelope header. + GetSdkInfo() *SdkInfo + + // GetDynamicSamplingContext returns trace context for the envelope header. + GetDynamicSamplingContext() map[string]string + + // ToEnvelope converts the item to a Sentry envelope using the provided header. + ToEnvelope(*EnvelopeHeader) (*Envelope, error) +} + +// TelemetryTransport represents the envelope-first transport interface. +// This interface is designed for the telemetry buffer system and provides +// non-blocking sends with backpressure signals. +type TelemetryTransport interface { + // SendEnvelope sends an envelope to Sentry. Returns immediately with + // backpressure error if the queue is full. + SendEnvelope(envelope *Envelope) error + + // HasCapacity reports whether the transport has capacity to accept at least one more envelope. + HasCapacity() bool + + // IsRateLimited checks if a specific category is currently rate limited + IsRateLimited(category ratelimit.Category) bool + + // Flush waits for all pending envelopes to be sent, with timeout + Flush(timeout time.Duration) bool + + // FlushWithContext waits for all pending envelopes to be sent + FlushWithContext(ctx context.Context) bool + + // Close shuts down the transport gracefully + Close() +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/item_container.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/item_container.go new file mode 100644 index 0000000..f83ad01 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/item_container.go @@ -0,0 +1,82 @@ +package protocol + +import ( + "encoding/json" + "errors" + "fmt" + + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +var errNoSerializableItems = errors.New("item container contains no serializable items") + +type ItemContainer struct { + items []TelemetryItem + category ratelimit.Category +} + +// NewItemContainer constructs a batched envelope producer from buffered telemetry items. +func NewItemContainer(category ratelimit.Category, items []TelemetryItem) ItemContainer { + return ItemContainer{category: category, items: items} +} + +func (b ItemContainer) marshalPayload() ([]byte, int, error) { + items := make([]json.RawMessage, 0, len(b.items)) + for _, item := range b.items { + itemPayload, err := json.Marshal(item) + if err != nil { + continue + } + items = append(items, itemPayload) + } + + if len(items) == 0 { + return nil, 0, nil + } + + wrapper := struct { + Items []json.RawMessage `json:"items"` + }{Items: items} + + payload, err := json.Marshal(wrapper) + if err != nil { + return nil, 0, err + } + return payload, len(items), nil +} + +func (b ItemContainer) newEnvelopeItem(itemCount int, payload []byte) (*EnvelopeItem, error) { + switch b.category { + case ratelimit.CategoryLog: + return NewLogItem(itemCount, payload), nil + case ratelimit.CategoryTraceMetric: + return NewTraceMetricItem(itemCount, payload), nil + default: + return nil, fmt.Errorf("unsupported batched category: %s", b.category) + } +} + +func (b ItemContainer) ToEnvelopeItem() (*EnvelopeItem, error) { + payload, itemCount, err := b.marshalPayload() + if err != nil { + return nil, err + } + if len(payload) == 0 { + return nil, errNoSerializableItems + } + + return b.newEnvelopeItem(itemCount, payload) +} + +func (b ItemContainer) ToEnvelope(header *EnvelopeHeader) (*Envelope, error) { + item, err := b.ToEnvelopeItem() + if err != nil { + return nil, err + } + return NewEnvelope(header, item), nil +} + +func (b ItemContainer) GetCategory() ratelimit.Category { return b.category } +func (ItemContainer) GetEventID() string { return "" } +func (ItemContainer) GetSdkInfo() *SdkInfo { return nil } +func (ItemContainer) GetDynamicSamplingContext() map[string]string { return nil } diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/types.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/types.go new file mode 100644 index 0000000..5237c9e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/types.go @@ -0,0 +1,15 @@ +package protocol + +// SdkInfo contains SDK metadata. +type SdkInfo struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` + Integrations []string `json:"integrations,omitempty"` + Packages []SdkPackage `json:"packages,omitempty"` +} + +// SdkPackage describes a package that was installed. +type SdkPackage struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/protocol/uuid.go b/vendor/github.com/getsentry/sentry-go/internal/protocol/uuid.go new file mode 100644 index 0000000..5aff3b1 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/protocol/uuid.go @@ -0,0 +1,18 @@ +package protocol + +import ( + "crypto/rand" + "encoding/hex" +) + +// GenerateEventID generates a random UUID v4 for use as a Sentry event ID. +func GenerateEventID() string { + id := make([]byte, 16) + // Prefer rand.Read over rand.Reader, see https://go-review.googlesource.com/c/go/+/272326/. + _, _ = rand.Read(id) + id[6] &= 0x0F // clear version + id[6] |= 0x40 // set version to 4 (random uuid) + id[8] &= 0x3F // clear variant + id[8] |= 0x80 // set to IETF variant + return hex.EncodeToString(id) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go new file mode 100644 index 0000000..60dbfec --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/category.go @@ -0,0 +1,115 @@ +package ratelimit + +import ( + "strings" + + "golang.org/x/text/cases" + "golang.org/x/text/language" +) + +// Reference: +// https://github.com/getsentry/relay/blob/46dfaa850b8717a6e22c3e9a275ba17fe673b9da/relay-base-schema/src/data_category.rs#L231-L271 + +// Category classifies supported payload types that can be ingested by Sentry +// and, therefore, rate limited. +type Category string + +// Known rate limit categories that are specified in rate limit headers. +const ( + CategoryUnknown Category = "unknown" // Unknown category should not get rate limited + CategoryAll Category = "" // Special category for empty categories (applies to all) + CategoryError Category = "error" + CategoryTransaction Category = "transaction" + CategorySpan Category = "span" + CategoryLog Category = "log_item" + CategoryLogByte Category = "log_byte" + CategoryMonitor Category = "monitor" + CategoryTraceMetric Category = "trace_metric" +) + +// knownCategories is the set of currently known categories. Other categories +// are ignored for the purpose of rate-limiting. +var knownCategories = map[Category]struct{}{ + CategoryAll: {}, + CategoryError: {}, + CategoryTransaction: {}, + CategoryLog: {}, + CategoryMonitor: {}, + CategoryTraceMetric: {}, +} + +// String returns the category formatted for debugging. +func (c Category) String() string { + switch c { + case CategoryAll: + return "CategoryAll" + case CategoryError: + return "CategoryError" + case CategoryTransaction: + return "CategoryTransaction" + case CategorySpan: + return "CategorySpan" + case CategoryLog: + return "CategoryLog" + case CategoryLogByte: + return "CategoryLogByte" + case CategoryMonitor: + return "CategoryMonitor" + case CategoryTraceMetric: + return "CategoryTraceMetric" + default: + // For unknown categories, use the original formatting logic + caser := cases.Title(language.English) + rv := "Category" + for _, w := range strings.Fields(string(c)) { + rv += caser.String(w) + } + return rv + } +} + +// Priority represents the importance level of a category for buffer management. +type Priority int + +const ( + PriorityCritical Priority = iota + 1 + PriorityHigh + PriorityMedium + PriorityLow + PriorityLowest +) + +func (p Priority) String() string { + switch p { + case PriorityCritical: + return "critical" + case PriorityHigh: + return "high" + case PriorityMedium: + return "medium" + case PriorityLow: + return "low" + case PriorityLowest: + return "lowest" + default: + return "unknown" + } +} + +// GetPriority returns the priority level for this category. +func (c Category) GetPriority() Priority { + switch c { + case CategoryError: + return PriorityCritical + case CategoryMonitor: + return PriorityHigh + case CategoryLog: + return PriorityLow + case CategoryTransaction: + return PriorityMedium + case CategoryTraceMetric: + return PriorityLow + default: + return PriorityMedium + } +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go new file mode 100644 index 0000000..c002583 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/deadline.go @@ -0,0 +1,22 @@ +package ratelimit + +import "time" + +// A Deadline is a time instant when a rate limit expires. +type Deadline time.Time + +// After reports whether the deadline d is after other. +func (d Deadline) After(other Deadline) bool { + return time.Time(d).After(time.Time(other)) +} + +// Equal reports whether d and e represent the same deadline. +func (d Deadline) Equal(e Deadline) bool { + return time.Time(d).Equal(time.Time(e)) +} + +// String returns the deadline formatted for debugging. +func (d Deadline) String() string { + // Like time.Time.String, but without the monotonic clock reading. + return time.Time(d).Round(0).String() +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go new file mode 100644 index 0000000..80b9fdd --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/doc.go @@ -0,0 +1,3 @@ +// Package ratelimit provides tools to work with rate limits imposed by Sentry's +// data ingestion pipeline. +package ratelimit diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go new file mode 100644 index 0000000..e590430 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/map.go @@ -0,0 +1,64 @@ +package ratelimit + +import ( + "net/http" + "time" +) + +// Map maps categories to rate limit deadlines. +// +// A rate limit is in effect for a given category if either the category's +// deadline or the deadline for the special CategoryAll has not yet expired. +// +// Use IsRateLimited to check whether a category is rate-limited. +type Map map[Category]Deadline + +// IsRateLimited returns true if the category is currently rate limited. +func (m Map) IsRateLimited(c Category) bool { + return m.isRateLimited(c, time.Now()) +} + +func (m Map) isRateLimited(c Category, now time.Time) bool { + return m.Deadline(c).After(Deadline(now)) +} + +// Deadline returns the deadline when the rate limit for the given category or +// the special CategoryAll expire, whichever is furthest into the future. +func (m Map) Deadline(c Category) Deadline { + categoryDeadline := m[c] + allDeadline := m[CategoryAll] + if categoryDeadline.After(allDeadline) { + return categoryDeadline + } + return allDeadline +} + +// Merge merges the other map into m. +// +// If a category appears in both maps, the deadline that is furthest into the +// future is preserved. +func (m Map) Merge(other Map) { + for c, d := range other { + if d.After(m[c]) { + m[c] = d + } + } +} + +// FromResponse returns a rate limit map from an HTTP response. +func FromResponse(r *http.Response) Map { + return fromResponse(r, time.Now()) +} + +func fromResponse(r *http.Response, now time.Time) Map { + s := r.Header.Get("X-Sentry-Rate-Limits") + if s != "" { + return parseXSentryRateLimits(s, now) + } + if r.StatusCode == http.StatusTooManyRequests { + s := r.Header.Get("Retry-After") + deadline, _ := parseRetryAfter(s, now) + return Map{CategoryAll: deadline} + } + return Map{} +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go new file mode 100644 index 0000000..579297e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/rate_limits.go @@ -0,0 +1,76 @@ +package ratelimit + +import ( + "errors" + "math" + "strconv" + "strings" + "time" +) + +var errInvalidXSRLRetryAfter = errors.New("invalid retry-after value") + +// parseXSentryRateLimits returns a RateLimits map by parsing an input string in +// the format of the X-Sentry-Rate-Limits header. +// +// Example +// +// X-Sentry-Rate-Limits: 60:transaction, 2700:default;error;security +// +// This will rate limit transactions for the next 60 seconds and errors for the +// next 2700 seconds. +// +// Limits for unknown categories are ignored. +func parseXSentryRateLimits(s string, now time.Time) Map { + // https://github.com/getsentry/relay/blob/0424a2e017d193a93918053c90cdae9472d164bf/relay-server/src/utils/rate_limits.rs#L44-L82 + m := make(Map, len(knownCategories)) + for _, limit := range strings.Split(s, ",") { + limit = strings.TrimSpace(limit) + if limit == "" { + continue + } + components := strings.Split(limit, ":") + if len(components) == 0 { + continue + } + retryAfter, err := parseXSRLRetryAfter(strings.TrimSpace(components[0]), now) + if err != nil { + continue + } + categories := "" + if len(components) > 1 { + categories = components[1] + } + for _, category := range strings.Split(categories, ";") { + c := Category(strings.ToLower(strings.TrimSpace(category))) + if _, ok := knownCategories[c]; !ok { + // skip unknown categories, keep m small + continue + } + // always keep the deadline furthest into the future + if retryAfter.After(m[c]) { + m[c] = retryAfter + } + } + } + return m +} + +// parseXSRLRetryAfter parses a string into a retry-after rate limit deadline. +// +// Valid input is a number, possibly signed and possibly floating-point, +// indicating the number of seconds to wait before sending another request. +// Negative values are treated as zero. Fractional values are rounded to the +// next integer. +func parseXSRLRetryAfter(s string, now time.Time) (Deadline, error) { + // https://github.com/getsentry/relay/blob/0424a2e017d193a93918053c90cdae9472d164bf/relay-quotas/src/rate_limit.rs#L88-L96 + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return Deadline{}, errInvalidXSRLRetryAfter + } + d := time.Duration(math.Ceil(math.Max(f, 0.0))) * time.Second + if d < 0 { + d = 0 + } + return Deadline(now.Add(d)), nil +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go new file mode 100644 index 0000000..576e29d --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/ratelimit/retry_after.go @@ -0,0 +1,40 @@ +package ratelimit + +import ( + "errors" + "strconv" + "time" +) + +const defaultRetryAfter = 1 * time.Minute + +var errInvalidRetryAfter = errors.New("invalid input") + +// parseRetryAfter parses a string s as in the standard Retry-After HTTP header +// and returns a deadline until when requests are rate limited and therefore new +// requests should not be sent. The input may be either a date or a non-negative +// integer number of seconds. +// +// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After +// +// parseRetryAfter always returns a usable deadline, even in case of an error. +// +// This is the original rate limiting mechanism used by Sentry, superseeded by +// the X-Sentry-Rate-Limits response header. +func parseRetryAfter(s string, now time.Time) (Deadline, error) { + if s == "" { + goto invalid + } + if n, err := strconv.Atoi(s); err == nil { + if n < 0 { + goto invalid + } + d := time.Duration(n) * time.Second + return Deadline(now.Add(d)), nil + } + if date, err := time.Parse(time.RFC1123, s); err == nil { + return Deadline(date), nil + } +invalid: + return Deadline(now.Add(defaultRetryAfter)), errInvalidRetryAfter +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go new file mode 100644 index 0000000..81ee3ba --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/bucketed_buffer.go @@ -0,0 +1,421 @@ +package telemetry + +import ( + "sync" + "sync/atomic" + "time" + + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/report" +) + +const ( + defaultBucketedCapacity = 100 + perBucketItemLimit = 100 +) + +type Bucket[T any] struct { + traceID string + items []T + createdAt time.Time + lastUpdatedAt time.Time +} + +// BucketedBuffer groups items by trace id, flushing per bucket. +type BucketedBuffer[T any] struct { + mu sync.RWMutex + + buckets []*Bucket[T] + traceIndex map[string]int + + head int + tail int + + itemCapacity int + bucketCapacity int + + totalItems int + bucketCount int + + category ratelimit.Category + priority ratelimit.Priority + overflowPolicy OverflowPolicy + recorder report.ClientReportRecorder + batchSize int + timeout time.Duration + lastFlushTime time.Time + + // atomic.Int64 instead of int64 + atomic ops: 64-bit atomics on plain + // mid-struct fields panic on 32-bit platforms (4-byte field alignment). + offered atomic.Int64 + dropped atomic.Int64 + onDropped func(item T, reason string) +} + +func NewBucketedBuffer[T any]( + category ratelimit.Category, + capacity int, + overflowPolicy OverflowPolicy, + batchSize int, + timeout time.Duration, + recorder report.ClientReportRecorder, +) *BucketedBuffer[T] { + if capacity <= 0 { + capacity = defaultBucketedCapacity + } + if batchSize <= 0 { + batchSize = 1 + } + if timeout < 0 { + timeout = 0 + } + + if recorder == nil { + recorder = report.NoopRecorder() + } + + bucketCapacity := capacity / 10 + if bucketCapacity < 10 { + bucketCapacity = 10 + } + + return &BucketedBuffer[T]{ + buckets: make([]*Bucket[T], bucketCapacity), + traceIndex: make(map[string]int), + itemCapacity: capacity, + bucketCapacity: bucketCapacity, + category: category, + priority: category.GetPriority(), + overflowPolicy: overflowPolicy, + recorder: recorder, + batchSize: batchSize, + timeout: timeout, + lastFlushTime: time.Now(), + } +} + +func (b *BucketedBuffer[T]) Offer(item T) bool { + b.offered.Add(1) + + traceID := "" + if ta, ok := any(item).(TraceAware); ok { + if tid, hasTrace := ta.GetTraceID(); hasTrace { + traceID = tid + } + } + + b.mu.Lock() + defer b.mu.Unlock() + return b.offerToBucket(item, traceID) +} + +func (b *BucketedBuffer[T]) offerToBucket(item T, traceID string) bool { + if traceID != "" { + if idx, exists := b.traceIndex[traceID]; exists { + bucket := b.buckets[idx] + if len(bucket.items) >= perBucketItemLimit { + delete(b.traceIndex, traceID) + } else { + bucket.items = append(bucket.items, item) + bucket.lastUpdatedAt = time.Now() + b.totalItems++ + return true + } + } + } + + if b.totalItems >= b.itemCapacity { + return b.handleOverflow(item, traceID) + } + if b.bucketCount >= b.bucketCapacity { + return b.handleOverflow(item, traceID) + } + + bucket := &Bucket[T]{ + traceID: traceID, + items: []T{item}, + createdAt: time.Now(), + lastUpdatedAt: time.Now(), + } + b.buckets[b.tail] = bucket + if traceID != "" { + b.traceIndex[traceID] = b.tail + } + b.tail = (b.tail + 1) % b.bucketCapacity + b.bucketCount++ + b.totalItems++ + return true +} + +func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool { + switch b.overflowPolicy { + case OverflowPolicyDropOldest: + oldestBucket := b.buckets[b.head] + if oldestBucket == nil { + b.recordDroppedItem(item) + b.dropped.Add(1) + if b.onDropped != nil { + b.onDropped(item, "buffer_full_invalid_state") + } + return false + } + if oldestBucket.traceID != "" { + delete(b.traceIndex, oldestBucket.traceID) + } + droppedCount := len(oldestBucket.items) + b.dropped.Add(int64(droppedCount)) + for _, di := range oldestBucket.items { + b.recordDroppedItem(di) + if b.onDropped != nil { + b.onDropped(di, "buffer_full_drop_oldest_bucket") + } + } + b.totalItems -= droppedCount + b.bucketCount-- + b.head = (b.head + 1) % b.bucketCapacity + // add new bucket + bucket := &Bucket[T]{traceID: traceID, items: []T{item}, createdAt: time.Now(), lastUpdatedAt: time.Now()} + b.buckets[b.tail] = bucket + if traceID != "" { + b.traceIndex[traceID] = b.tail + } + b.tail = (b.tail + 1) % b.bucketCapacity + b.bucketCount++ + b.totalItems++ + return true + case OverflowPolicyDropNewest: + b.dropped.Add(1) + b.recordDroppedItem(item) + if b.onDropped != nil { + b.onDropped(item, "buffer_full_drop_newest") + } + return false + default: + b.dropped.Add(1) + b.recordDroppedItem(item) + if b.onDropped != nil { + b.onDropped(item, "unknown_overflow_policy") + } + return false + } +} + +func (b *BucketedBuffer[T]) Poll() (T, bool) { + b.mu.Lock() + defer b.mu.Unlock() + var zero T + if b.bucketCount == 0 { + return zero, false + } + bucket := b.buckets[b.head] + if bucket == nil || len(bucket.items) == 0 { + return zero, false + } + item := bucket.items[0] + bucket.items = bucket.items[1:] + b.totalItems-- + if len(bucket.items) == 0 { + if bucket.traceID != "" { + delete(b.traceIndex, bucket.traceID) + } + b.buckets[b.head] = nil + b.head = (b.head + 1) % b.bucketCapacity + b.bucketCount-- + } + return item, true +} + +func (b *BucketedBuffer[T]) PollBatch(maxItems int) []T { + if maxItems <= 0 { + return nil + } + b.mu.Lock() + defer b.mu.Unlock() + if b.bucketCount == 0 { + return nil + } + res := make([]T, 0, maxItems) + for len(res) < maxItems && b.bucketCount > 0 { + bucket := b.buckets[b.head] + if bucket == nil { + break + } + n := maxItems - len(res) + if n > len(bucket.items) { + n = len(bucket.items) + } + res = append(res, bucket.items[:n]...) + bucket.items = bucket.items[n:] + b.totalItems -= n + if len(bucket.items) == 0 { + if bucket.traceID != "" { + delete(b.traceIndex, bucket.traceID) + } + b.buckets[b.head] = nil + b.head = (b.head + 1) % b.bucketCapacity + b.bucketCount-- + } + } + return res +} + +func (b *BucketedBuffer[T]) PollIfReady() []T { + b.mu.Lock() + defer b.mu.Unlock() + if b.bucketCount == 0 { + return nil + } + ready := b.totalItems >= b.batchSize || (b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout) + if !ready { + return nil + } + oldest := b.buckets[b.head] + if oldest == nil { + return nil + } + items := oldest.items + if oldest.traceID != "" { + delete(b.traceIndex, oldest.traceID) + } + b.buckets[b.head] = nil + b.head = (b.head + 1) % b.bucketCapacity + b.totalItems -= len(items) + b.bucketCount-- + b.lastFlushTime = time.Now() + return items +} + +func (b *BucketedBuffer[T]) Drain() []T { + b.mu.Lock() + defer b.mu.Unlock() + if b.bucketCount == 0 { + return nil + } + res := make([]T, 0, b.totalItems) + for i := 0; i < b.bucketCount; i++ { + idx := (b.head + i) % b.bucketCapacity + bucket := b.buckets[idx] + if bucket != nil { + res = append(res, bucket.items...) + b.buckets[idx] = nil + } + } + b.traceIndex = make(map[string]int) + b.head = 0 + b.tail = 0 + b.totalItems = 0 + b.bucketCount = 0 + return res +} + +func (b *BucketedBuffer[T]) Peek() (T, bool) { + b.mu.RLock() + defer b.mu.RUnlock() + var zero T + if b.bucketCount == 0 { + return zero, false + } + bucket := b.buckets[b.head] + if bucket == nil || len(bucket.items) == 0 { + return zero, false + } + return bucket.items[0], true +} + +func (b *BucketedBuffer[T]) Size() int { b.mu.RLock(); defer b.mu.RUnlock(); return b.totalItems } +func (b *BucketedBuffer[T]) Capacity() int { b.mu.RLock(); defer b.mu.RUnlock(); return b.itemCapacity } +func (b *BucketedBuffer[T]) Category() ratelimit.Category { + b.mu.RLock() + defer b.mu.RUnlock() + return b.category +} +func (b *BucketedBuffer[T]) Priority() ratelimit.Priority { + b.mu.RLock() + defer b.mu.RUnlock() + return b.priority +} +func (b *BucketedBuffer[T]) IsEmpty() bool { + b.mu.RLock() + defer b.mu.RUnlock() + return b.bucketCount == 0 +} +func (b *BucketedBuffer[T]) IsFull() bool { + b.mu.RLock() + defer b.mu.RUnlock() + return b.totalItems >= b.itemCapacity +} +func (b *BucketedBuffer[T]) Utilization() float64 { + b.mu.RLock() + defer b.mu.RUnlock() + if b.itemCapacity == 0 { + return 0 + } + return float64(b.totalItems) / float64(b.itemCapacity) +} +func (b *BucketedBuffer[T]) OfferedCount() int64 { return b.offered.Load() } +func (b *BucketedBuffer[T]) DroppedCount() int64 { return b.dropped.Load() } +func (b *BucketedBuffer[T]) AcceptedCount() int64 { return b.OfferedCount() - b.DroppedCount() } +func (b *BucketedBuffer[T]) DropRate() float64 { + off := b.OfferedCount() + if off == 0 { + return 0 + } + return float64(b.DroppedCount()) / float64(off) +} + +func (b *BucketedBuffer[T]) GetMetrics() BufferMetrics { + b.mu.RLock() + size := b.totalItems + util := 0.0 + if b.itemCapacity > 0 { + util = float64(b.totalItems) / float64(b.itemCapacity) + } + b.mu.RUnlock() + return BufferMetrics{Category: b.category, Priority: b.priority, Capacity: b.itemCapacity, Size: size, Utilization: util, OfferedCount: b.OfferedCount(), DroppedCount: b.DroppedCount(), AcceptedCount: b.AcceptedCount(), DropRate: b.DropRate(), LastUpdated: time.Now()} +} + +func (b *BucketedBuffer[T]) SetDroppedCallback(callback func(item T, reason string)) { + b.mu.Lock() + defer b.mu.Unlock() + b.onDropped = callback +} +func (b *BucketedBuffer[T]) Clear() { + b.mu.Lock() + defer b.mu.Unlock() + for i := 0; i < b.bucketCapacity; i++ { + b.buckets[i] = nil + } + b.traceIndex = make(map[string]int) + b.head = 0 + b.tail = 0 + b.totalItems = 0 + b.bucketCount = 0 +} +func (b *BucketedBuffer[T]) IsReadyToFlush() bool { + b.mu.RLock() + defer b.mu.RUnlock() + if b.bucketCount == 0 { + return false + } + if b.totalItems >= b.batchSize { + return true + } + if b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout { + return true + } + return false +} +func (b *BucketedBuffer[T]) MarkFlushed() { + b.mu.Lock() + defer b.mu.Unlock() + b.lastFlushTime = time.Now() +} + +func (b *BucketedBuffer[T]) recordDroppedItem(item T) { + if ti, ok := any(item).(protocol.TelemetryItem); ok { + b.recorder.RecordItem(report.ReasonBufferOverflow, ti) + } else { + b.recorder.RecordOne(report.ReasonBufferOverflow, b.category) + } +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/buffer.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/buffer.go new file mode 100644 index 0000000..011a60a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/buffer.go @@ -0,0 +1,42 @@ +package telemetry + +import ( + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// Buffer defines the common interface for all buffer implementations. +type Buffer[T any] interface { + // Core operations + Offer(item T) bool + Poll() (T, bool) + PollBatch(maxItems int) []T + PollIfReady() []T + Drain() []T + Peek() (T, bool) + + // State queries + Size() int + Capacity() int + IsEmpty() bool + IsFull() bool + Utilization() float64 + + // Flush management + IsReadyToFlush() bool + MarkFlushed() + + // Category/Priority + Category() ratelimit.Category + Priority() ratelimit.Priority + + // Metrics + OfferedCount() int64 + DroppedCount() int64 + AcceptedCount() int64 + DropRate() float64 + GetMetrics() BufferMetrics + + // Configuration + SetDroppedCallback(callback func(item T, reason string)) + Clear() +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/processor.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/processor.go new file mode 100644 index 0000000..1ad3900 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/processor.go @@ -0,0 +1,55 @@ +package telemetry + +import ( + "context" + "time" + + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/report" +) + +// Processor is the top-level object that wraps the scheduler and buffers. +type Processor struct { + scheduler *Scheduler +} + +// NewProcessor creates a new Processor with the given configuration. +func NewProcessor( + buffers map[ratelimit.Category]Buffer[protocol.TelemetryItem], + transport protocol.TelemetryTransport, + dsn *protocol.Dsn, + sdkInfo func() *protocol.SdkInfo, + recorder report.ClientReportRecorder, +) *Processor { + scheduler := NewScheduler(buffers, transport, dsn, sdkInfo, recorder) + scheduler.Start() + + return &Processor{ + scheduler: scheduler, + } +} + +// Add adds a TelemetryItem to the appropriate buffer based on its category. +// +// The processor should call MakeSerializationSafe to eliminate any race on user mutable fields, +// since the serialization happens on a background goroutine. +func (b *Processor) Add(item protocol.TelemetryItem) bool { + item.MakeSerializationSafe() + return b.scheduler.Add(item) +} + +// Flush forces all buffers to flush within the given timeout. +func (b *Processor) Flush(timeout time.Duration) bool { + return b.scheduler.Flush(timeout) +} + +// FlushWithContext flushes with a custom context for cancellation. +func (b *Processor) FlushWithContext(ctx context.Context) bool { + return b.scheduler.FlushWithContext(ctx) +} + +// Close stops the buffer, flushes remaining data, and releases resources. +func (b *Processor) Close(timeout time.Duration) { + b.scheduler.Stop(timeout) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go new file mode 100644 index 0000000..8ef0e0f --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/ring_buffer.go @@ -0,0 +1,399 @@ +package telemetry + +import ( + "sync" + "sync/atomic" + "time" + + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/report" +) + +const defaultCapacity = 100 + +// RingBuffer is a thread-safe ring buffer with overflow policies. +type RingBuffer[T any] struct { + mu sync.RWMutex + items []T + head int + tail int + size int + capacity int + + category ratelimit.Category + priority ratelimit.Priority + overflowPolicy OverflowPolicy + recorder report.ClientReportRecorder + + batchSize int + timeout time.Duration + lastFlushTime time.Time + + // atomic.Int64 instead of int64 + atomic ops: 64-bit atomics on plain + // mid-struct fields panic on 32-bit platforms (4-byte field alignment). + offered atomic.Int64 + dropped atomic.Int64 + onDropped func(item T, reason string) +} + +func NewRingBuffer[T any](category ratelimit.Category, capacity int, overflowPolicy OverflowPolicy, batchSize int, timeout time.Duration, recorder report.ClientReportRecorder) *RingBuffer[T] { + if capacity <= 0 { + capacity = defaultCapacity + } + + if batchSize <= 0 { + batchSize = 1 + } + + if timeout < 0 { + timeout = 0 + } + + if recorder == nil { + recorder = report.NoopRecorder() + } + + return &RingBuffer[T]{ + items: make([]T, capacity), + capacity: capacity, + category: category, + priority: category.GetPriority(), + overflowPolicy: overflowPolicy, + recorder: recorder, + batchSize: batchSize, + timeout: timeout, + lastFlushTime: time.Now(), + } +} + +func (b *RingBuffer[T]) SetDroppedCallback(callback func(item T, reason string)) { + b.mu.Lock() + defer b.mu.Unlock() + b.onDropped = callback +} + +func (b *RingBuffer[T]) Offer(item T) bool { + b.offered.Add(1) + + b.mu.Lock() + defer b.mu.Unlock() + + if b.size < b.capacity { + b.items[b.tail] = item + b.tail = (b.tail + 1) % b.capacity + b.size++ + return true + } + + switch b.overflowPolicy { + case OverflowPolicyDropOldest: + oldItem := b.items[b.head] + b.items[b.head] = item + b.head = (b.head + 1) % b.capacity + b.tail = (b.tail + 1) % b.capacity + + b.dropped.Add(1) + b.recordDroppedItem(oldItem) + if b.onDropped != nil { + b.onDropped(oldItem, "buffer_full_drop_oldest") + } + return true + + case OverflowPolicyDropNewest: + b.dropped.Add(1) + b.recordDroppedItem(item) + if b.onDropped != nil { + b.onDropped(item, "buffer_full_drop_newest") + } + return false + + default: + b.dropped.Add(1) + b.recordDroppedItem(item) + if b.onDropped != nil { + b.onDropped(item, "unknown_overflow_policy") + } + return false + } +} + +func (b *RingBuffer[T]) Poll() (T, bool) { + b.mu.Lock() + defer b.mu.Unlock() + + var zero T + if b.size == 0 { + return zero, false + } + + item := b.items[b.head] + b.items[b.head] = zero + b.head = (b.head + 1) % b.capacity + b.size-- + + return item, true +} + +func (b *RingBuffer[T]) PollBatch(maxItems int) []T { + if maxItems <= 0 { + return nil + } + + b.mu.Lock() + defer b.mu.Unlock() + + if b.size == 0 { + return nil + } + + itemCount := maxItems + if itemCount > b.size { + itemCount = b.size + } + + result := make([]T, itemCount) + var zero T + + for i := 0; i < itemCount; i++ { + result[i] = b.items[b.head] + b.items[b.head] = zero + b.head = (b.head + 1) % b.capacity + b.size-- + } + + return result +} + +func (b *RingBuffer[T]) Drain() []T { + b.mu.Lock() + defer b.mu.Unlock() + + if b.size == 0 { + return nil + } + + result := make([]T, b.size) + index := 0 + var zero T + + for i := 0; i < b.size; i++ { + pos := (b.head + i) % b.capacity + result[index] = b.items[pos] + b.items[pos] = zero + index++ + } + + b.head = 0 + b.tail = 0 + b.size = 0 + + return result +} + +func (b *RingBuffer[T]) Peek() (T, bool) { + b.mu.RLock() + defer b.mu.RUnlock() + + var zero T + if b.size == 0 { + return zero, false + } + + return b.items[b.head], true +} + +func (b *RingBuffer[T]) Size() int { + b.mu.RLock() + defer b.mu.RUnlock() + return b.size +} + +func (b *RingBuffer[T]) Capacity() int { + b.mu.RLock() + defer b.mu.RUnlock() + return b.capacity +} + +func (b *RingBuffer[T]) Category() ratelimit.Category { + b.mu.RLock() + defer b.mu.RUnlock() + return b.category +} + +func (b *RingBuffer[T]) Priority() ratelimit.Priority { + b.mu.RLock() + defer b.mu.RUnlock() + return b.priority +} + +func (b *RingBuffer[T]) IsEmpty() bool { + b.mu.RLock() + defer b.mu.RUnlock() + return b.size == 0 +} + +func (b *RingBuffer[T]) IsFull() bool { + b.mu.RLock() + defer b.mu.RUnlock() + return b.size == b.capacity +} + +func (b *RingBuffer[T]) Utilization() float64 { + b.mu.RLock() + defer b.mu.RUnlock() + return float64(b.size) / float64(b.capacity) +} + +func (b *RingBuffer[T]) OfferedCount() int64 { + return b.offered.Load() +} + +func (b *RingBuffer[T]) DroppedCount() int64 { + return b.dropped.Load() +} + +func (b *RingBuffer[T]) AcceptedCount() int64 { + return b.OfferedCount() - b.DroppedCount() +} + +func (b *RingBuffer[T]) DropRate() float64 { + offered := b.OfferedCount() + if offered == 0 { + return 0.0 + } + return float64(b.DroppedCount()) / float64(offered) +} + +func (b *RingBuffer[T]) Clear() { + b.mu.Lock() + defer b.mu.Unlock() + + var zero T + for i := 0; i < b.capacity; i++ { + b.items[i] = zero + } + + b.head = 0 + b.tail = 0 + b.size = 0 +} + +func (b *RingBuffer[T]) GetMetrics() BufferMetrics { + b.mu.RLock() + size := b.size + util := float64(b.size) / float64(b.capacity) + b.mu.RUnlock() + + return BufferMetrics{ + Category: b.category, + Priority: b.priority, + Capacity: b.capacity, + Size: size, + Utilization: util, + OfferedCount: b.OfferedCount(), + DroppedCount: b.DroppedCount(), + AcceptedCount: b.AcceptedCount(), + DropRate: b.DropRate(), + LastUpdated: time.Now(), + } +} + +func (b *RingBuffer[T]) IsReadyToFlush() bool { + b.mu.RLock() + defer b.mu.RUnlock() + + if b.size == 0 { + return false + } + + if b.size >= b.batchSize { + return true + } + + if b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout { + return true + } + + return false +} + +func (b *RingBuffer[T]) MarkFlushed() { + b.mu.Lock() + defer b.mu.Unlock() + b.lastFlushTime = time.Now() +} + +func (b *RingBuffer[T]) PollIfReady() []T { + b.mu.Lock() + defer b.mu.Unlock() + + if b.size == 0 { + return nil + } + + ready := b.size >= b.batchSize || + (b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout) + + if !ready { + return nil + } + + itemCount := b.batchSize + if itemCount > b.size { + itemCount = b.size + } + + result := make([]T, itemCount) + var zero T + + for i := 0; i < itemCount; i++ { + result[i] = b.items[b.head] + b.items[b.head] = zero + b.head = (b.head + 1) % b.capacity + b.size-- + } + + b.lastFlushTime = time.Now() + return result +} + +func (b *RingBuffer[T]) recordDroppedItem(item T) { + if ti, ok := any(item).(protocol.TelemetryItem); ok { + b.recorder.RecordItem(report.ReasonBufferOverflow, ti) + } else { + b.recorder.RecordOne(report.ReasonBufferOverflow, b.category) + } +} + +type BufferMetrics struct { + Category ratelimit.Category `json:"category"` + Priority ratelimit.Priority `json:"priority"` + Capacity int `json:"capacity"` + Size int `json:"size"` + Utilization float64 `json:"utilization"` + OfferedCount int64 `json:"offered_count"` + DroppedCount int64 `json:"dropped_count"` + AcceptedCount int64 `json:"accepted_count"` + DropRate float64 `json:"drop_rate"` + LastUpdated time.Time `json:"last_updated"` +} + +// OverflowPolicy defines how the ring buffer handles overflow. +type OverflowPolicy int + +const ( + OverflowPolicyDropOldest OverflowPolicy = iota + OverflowPolicyDropNewest +) + +func (op OverflowPolicy) String() string { + switch op { + case OverflowPolicyDropOldest: + return "drop_oldest" + case OverflowPolicyDropNewest: + return "drop_newest" + default: + return "unknown" + } +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go new file mode 100644 index 0000000..f1bdc1e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/scheduler.go @@ -0,0 +1,303 @@ +package telemetry + +import ( + "context" + "sync" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/report" +) + +// Scheduler implements a weighted round-robin scheduler for processing buffered events. +type Scheduler struct { + buffers map[ratelimit.Category]Buffer[protocol.TelemetryItem] + transport protocol.TelemetryTransport + dsn *protocol.Dsn + sdkInfo func() *protocol.SdkInfo + recorder report.ClientReportRecorder + + currentCycle []ratelimit.Priority + cyclePos int + + ctx context.Context + cancel context.CancelFunc + processingWg sync.WaitGroup + + mu sync.Mutex + cond *sync.Cond + startOnce sync.Once + finishOnce sync.Once +} + +func NewScheduler( + buffers map[ratelimit.Category]Buffer[protocol.TelemetryItem], + transport protocol.TelemetryTransport, + dsn *protocol.Dsn, + sdkInfo func() *protocol.SdkInfo, + recorder report.ClientReportRecorder, +) *Scheduler { + if recorder == nil { + recorder = report.NoopRecorder() + } + + ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // G118: cancel is stored in s.cancel and called in Shutdown() + + priorityWeights := map[ratelimit.Priority]int{ + ratelimit.PriorityCritical: 5, + ratelimit.PriorityHigh: 4, + ratelimit.PriorityMedium: 3, + ratelimit.PriorityLow: 2, + ratelimit.PriorityLowest: 1, + } + + var currentCycle []ratelimit.Priority + for priority, weight := range priorityWeights { + hasBuffers := false + for _, buffer := range buffers { + if buffer.Priority() == priority { + hasBuffers = true + break + } + } + + if hasBuffers { + for i := 0; i < weight; i++ { + currentCycle = append(currentCycle, priority) + } + } + } + + s := &Scheduler{ + buffers: buffers, + transport: transport, + dsn: dsn, + sdkInfo: sdkInfo, + recorder: recorder, + currentCycle: currentCycle, + ctx: ctx, + cancel: cancel, + } + s.cond = sync.NewCond(&s.mu) + + return s +} + +func (s *Scheduler) resolveSdkInfo() *protocol.SdkInfo { + if s.sdkInfo == nil { + return &protocol.SdkInfo{} + } + return s.sdkInfo() +} + +func (s *Scheduler) Start() { + s.startOnce.Do(func() { + s.processingWg.Add(1) + go s.run() + }) +} + +func (s *Scheduler) Stop(timeout time.Duration) { + s.finishOnce.Do(func() { + s.Flush(timeout) + + s.cancel() + s.cond.Broadcast() + + done := make(chan struct{}) + go func() { + defer close(done) + s.processingWg.Wait() + }() + + select { + case <-done: + case <-time.After(timeout): + debuglog.Printf("scheduler stop timed out after %v", timeout) + } + }) +} + +func (s *Scheduler) Signal() { + s.cond.Signal() +} + +func (s *Scheduler) Add(item protocol.TelemetryItem) bool { + category := item.GetCategory() + buffer, exists := s.buffers[category] + if !exists { + return false + } + + accepted := buffer.Offer(item) + if accepted { + s.Signal() + } + return accepted +} + +func (s *Scheduler) Flush(timeout time.Duration) bool { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return s.FlushWithContext(ctx) +} + +func (s *Scheduler) FlushWithContext(ctx context.Context) bool { + s.flushBuffers() + return s.transport.FlushWithContext(ctx) +} + +func (s *Scheduler) run() { + defer s.processingWg.Done() + + go func() { + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() + + for { + select { + case <-ticker.C: + s.cond.Broadcast() + case <-s.ctx.Done(): + return + } + } + }() + + for { + s.mu.Lock() + + for !s.hasWork() && s.ctx.Err() == nil { + s.cond.Wait() + } + + if s.ctx.Err() != nil { + s.mu.Unlock() + return + } + + s.mu.Unlock() + s.processNextBatch() + } +} + +func (s *Scheduler) hasWork() bool { + for _, buffer := range s.buffers { + if buffer.IsReadyToFlush() { + return true + } + } + return false +} + +func (s *Scheduler) processNextBatch() { + if len(s.currentCycle) == 0 { + return + } + + priority := s.currentCycle[s.cyclePos] + s.cyclePos = (s.cyclePos + 1) % len(s.currentCycle) + + var bufferToProcess Buffer[protocol.TelemetryItem] + var categoryToProcess ratelimit.Category + for category, buffer := range s.buffers { + if buffer.Priority() == priority && buffer.IsReadyToFlush() { + bufferToProcess = buffer + categoryToProcess = category + break + } + } + + if bufferToProcess != nil { + s.processItems(bufferToProcess, categoryToProcess, false) + } +} + +func (s *Scheduler) processItems(buffer Buffer[protocol.TelemetryItem], category ratelimit.Category, force bool) { + var items []protocol.TelemetryItem + + if force { + items = buffer.Drain() + } else { + items = buffer.PollIfReady() + } + + if len(items) == 0 { + return + } + + if s.isRateLimited(category) { + for _, item := range items { + s.recorder.RecordItem(report.ReasonRateLimitBackoff, item) + } + return + } + if !s.transport.HasCapacity() { + for _, item := range items { + s.recorder.RecordItem(report.ReasonQueueOverflow, item) + } + return + } + + for _, item := range s.envelopeConvertibles(category, items) { + s.sendItem(item) + } +} + +// envelopeConvertibles converts single items or batches to satisfy the EnvelopeConvertible interface. +func (s *Scheduler) envelopeConvertibles(category ratelimit.Category, items []protocol.TelemetryItem) []protocol.EnvelopeConvertible { + switch category { + case ratelimit.CategoryLog, ratelimit.CategoryTraceMetric: + return []protocol.EnvelopeConvertible{protocol.NewItemContainer(category, items)} + default: + convertibles := make([]protocol.EnvelopeConvertible, 0, len(items)) + for _, item := range items { + if convertible, ok := item.(protocol.EnvelopeConvertible); ok { + convertibles = append(convertibles, convertible) + continue + } + debuglog.Printf("item does not implement envelope conversion: %T", item) + } + return convertibles + } +} + +func (s *Scheduler) sendItem(item protocol.EnvelopeConvertible) { + header := &protocol.EnvelopeHeader{ + EventID: item.GetEventID(), + SentAt: time.Now(), + Dsn: s.dsn, + Trace: item.GetDynamicSamplingContext(), + Sdk: item.GetSdkInfo(), + } + if header.EventID == "" { + header.EventID = protocol.GenerateEventID() + } + if header.Sdk == nil { + header.Sdk = s.resolveSdkInfo() + } + + envelope, err := item.ToEnvelope(header) + if err != nil { + debuglog.Printf("error while converting to envelope: %v", err) + s.recorder.RecordItem(report.ReasonInternalError, item) + return + } + if err := s.transport.SendEnvelope(envelope); err != nil { + debuglog.Printf("error sending envelope: %v", err) + } +} + +func (s *Scheduler) flushBuffers() { + for category, buffer := range s.buffers { + if !buffer.IsEmpty() { + s.processItems(buffer, category, true) + } + } +} + +func (s *Scheduler) isRateLimited(category ratelimit.Category) bool { + return s.transport.IsRateLimited(category) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/telemetry/trace_aware.go b/vendor/github.com/getsentry/sentry-go/internal/telemetry/trace_aware.go new file mode 100644 index 0000000..a321033 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/telemetry/trace_aware.go @@ -0,0 +1,7 @@ +package telemetry + +// TraceAware is implemented by items that can expose a trace ID. +// BucketedBuffer uses this to group items by trace. +type TraceAware interface { + GetTraceID() (string, bool) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/util/map.go b/vendor/github.com/getsentry/sentry-go/internal/util/map.go new file mode 100644 index 0000000..7ca9d17 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/util/map.go @@ -0,0 +1,43 @@ +package util + +import "sync" + +type SyncMap[K comparable, V any] struct { + m sync.Map +} + +func (s *SyncMap[K, V]) Store(key K, value V) { + s.m.Store(key, value) +} + +func (s *SyncMap[K, V]) CompareAndDelete(key K, value V) { + s.m.CompareAndDelete(key, value) +} + +func (s *SyncMap[K, V]) Load(key K) (V, bool) { + v, ok := s.m.Load(key) + if !ok { + var zero V + return zero, false + } + return v.(V), true +} + +func (s *SyncMap[K, V]) Delete(key K) { + s.m.Delete(key) +} + +func (s *SyncMap[K, V]) LoadOrStore(key K, value V) (V, bool) { + actual, loaded := s.m.LoadOrStore(key, value) + return actual.(V), loaded +} + +func (s *SyncMap[K, V]) Clear() { + s.m.Clear() +} + +func (s *SyncMap[K, V]) Range(f func(key K, value V) bool) { + s.m.Range(func(key, value any) bool { + return f(key.(K), value.(V)) + }) +} diff --git a/vendor/github.com/getsentry/sentry-go/internal/util/util.go b/vendor/github.com/getsentry/sentry-go/internal/util/util.go new file mode 100644 index 0000000..534e77c --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/internal/util/util.go @@ -0,0 +1,119 @@ +package util + +import ( + "fmt" + "io" + "net/http" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// MaxDrainResponseBytes is the maximum number of bytes that transport +// implementations will read from response bodies when draining them. +const MaxDrainResponseBytes = 16 << 10 + +// HandleHTTPResponse is a helper method that reads the HTTP response and handles debug output. +func HandleHTTPResponse(response *http.Response, identifier string) bool { + if response.StatusCode >= 200 && response.StatusCode < 300 { + return true + } + + if response.StatusCode >= 400 && response.StatusCode <= 599 { + body, err := io.ReadAll(io.LimitReader(response.Body, MaxDrainResponseBytes)) + if err != nil { + debuglog.Printf("Error while reading response body: %v", err) + return false + } + + switch { + case response.StatusCode == http.StatusRequestEntityTooLarge: + debuglog.Printf("Sending %s failed because the request was too large: %s", identifier, string(body)) + case response.StatusCode >= 500: + debuglog.Printf("Sending %s failed with server error %d: %s", identifier, response.StatusCode, string(body)) + default: + debuglog.Printf("Sending %s failed with client error %d: %s", identifier, response.StatusCode, string(body)) + } + return false + } + + debuglog.Printf("Unexpected status code %d for event %s", response.StatusCode, identifier) + return false +} + +// EnvelopeIdentifier returns a human-readable identifier for the event to be used in log messages. +// Format: " []". +func EnvelopeIdentifier(envelope *protocol.Envelope) string { + if envelope == nil || len(envelope.Items) == 0 { + return "empty envelope" + } + + var description string + // we don't currently support mixed envelope types, so all event types would have the same type. + itemType := envelope.Items[0].Header.Type + + switch itemType { + case protocol.EnvelopeItemTypeEvent: + description = "error" + case protocol.EnvelopeItemTypeTransaction: + description = "transaction" + case protocol.EnvelopeItemTypeCheckIn: + description = "check-in" + case protocol.EnvelopeItemTypeLog: + logCount := 0 + for _, item := range envelope.Items { + if item != nil && item.Header != nil && item.Header.Type == protocol.EnvelopeItemTypeLog && item.Header.ItemCount != nil { + logCount += *item.Header.ItemCount + } + } + description = fmt.Sprintf("%d log events", logCount) + case protocol.EnvelopeItemTypeTraceMetric: + metricCount := 0 + for _, item := range envelope.Items { + if item != nil && item.Header != nil && item.Header.Type == protocol.EnvelopeItemTypeTraceMetric && item.Header.ItemCount != nil { + metricCount += *item.Header.ItemCount + } + } + description = fmt.Sprintf("%d metric events", metricCount) + default: + description = fmt.Sprintf("%s event", itemType) + } + + return fmt.Sprintf("%s [%s]", description, envelope.Header.EventID) +} + +// SendResult holds the outcome of an HTTP request sent to Sentry. +type SendResult struct { + Success bool + StatusCode int + Limits ratelimit.Map +} + +// IsSendError returns true if the response indicates a server/client error that should be recorded +// as send_error for client report outcomes (non-429 failures). +func (r *SendResult) IsSendError() bool { + return !r.Success && r.StatusCode != http.StatusTooManyRequests +} + +// DoSendRequest executes an HTTP request, handles response logging, extracts rate limits, and +// drains+closes the response body. +func DoSendRequest(client *http.Client, request *http.Request, identifier string) (*SendResult, error) { + response, err := client.Do(request) //nolint:gosec // G704: request is constructed internally, not from user input + if err != nil { + return nil, err + } + + success := HandleHTTPResponse(response, identifier) + limits := ratelimit.FromResponse(response) + + // Drain body up to a limit and close it, allowing the transport to reuse TCP connections. + _, _ = io.CopyN(io.Discard, response.Body, MaxDrainResponseBytes) + response.Body.Close() + + return &SendResult{ + Success: success, + StatusCode: response.StatusCode, + Limits: limits, + }, nil +} diff --git a/vendor/github.com/getsentry/sentry-go/log.go b/vendor/github.com/getsentry/sentry-go/log.go new file mode 100644 index 0000000..72a2b97 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/log.go @@ -0,0 +1,359 @@ +package sentry + +import ( + "context" + "fmt" + "maps" + "os" + "strings" + "sync" + "time" + + "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" +) + +type LogLevel string + +const ( + LogLevelTrace LogLevel = "trace" + LogLevelDebug LogLevel = "debug" + LogLevelInfo LogLevel = "info" + LogLevelWarn LogLevel = "warn" + LogLevelError LogLevel = "error" + LogLevelFatal LogLevel = "fatal" +) + +const ( + LogSeverityTrace int = 1 + LogSeverityDebug int = 5 + LogSeverityInfo int = 9 + LogSeverityWarning int = 13 + LogSeverityError int = 17 + LogSeverityFatal int = 21 +) + +type sentryLogger struct { + ctx context.Context + hub *Hub + attributes map[string]attribute.Value + defaultAttributes map[string]attribute.Value + mu sync.RWMutex +} + +type logEntry struct { + logger *sentryLogger + ctx context.Context + level LogLevel + severity int + attributes map[string]attribute.Value + shouldPanic bool + shouldFatal bool +} + +// NewLogger returns a Logger that emits logs to Sentry. +func NewLogger(ctx context.Context) Logger { // nolint: dupl + var hub *Hub + hub = GetHubFromContext(ctx) + if hub == nil { + hub = CurrentHub() + } + + client := hub.Client() + if client != nil { + // Build default attrs + serverAddr := client.options.ServerName + if serverAddr == "" { + serverAddr, _ = os.Hostname() + } + + defaults := map[string]string{ + "sentry.release": client.options.Release, + "sentry.environment": client.options.Environment, + "sentry.server.address": serverAddr, + "sentry.sdk.name": client.sdkIdentifier, + "sentry.sdk.version": client.sdkVersion, + } + + defaultAttrs := make(map[string]attribute.Value, len(defaults)) + for k, v := range defaults { + if v != "" { + defaultAttrs[k] = attribute.StringValue(v) + } + } + + return &sentryLogger{ + ctx: ctx, + hub: hub, + attributes: make(map[string]attribute.Value), + defaultAttributes: defaultAttrs, + mu: sync.RWMutex{}, + } + } + + debuglog.Println("fallback to noopLogger: SDK not initialized") + return &noopLogger{} +} + +func (l *sentryLogger) Write(p []byte) (int, error) { + msg := strings.TrimRight(string(p), "\n") + l.Info().Emit(msg) + return len(p), nil +} + +func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, message string, entryAttrs map[string]attribute.Value, format bool, args ...interface{}) { + if message == "" { + return + } + + hub := hubFromContexts(ctx, l.ctx) + if hub == nil { + hub = l.hub + } + client := hub.Client() + if client == nil { + return + } + + scope := hub.Scope() + traceID, spanID := resolveTrace(scope, client, ctx, l.ctx) + + // Pre-allocate with capacity hint to avoid map growth reallocations + estimatedCap := len(l.defaultAttributes) + len(entryAttrs) + len(args) + 8 // scope ~3 + instance ~5 + attrs := make(map[string]attribute.Value, estimatedCap) + + // attribute precedence: default -> scope -> instance (from SetAttrs) -> entry-specific + for k, v := range l.defaultAttributes { + attrs[k] = v + } + scope.populateAttrs(attrs) + + l.mu.RLock() + for k, v := range l.attributes { + attrs[k] = v + } + l.mu.RUnlock() + + for k, v := range entryAttrs { + attrs[k] = v + } + + body := message + if format { + body = fmt.Sprintf(message, args...) + } + + if len(args) > 0 { + attrs["sentry.message.template"] = attribute.StringValue(message) + for i, p := range args { + attrs[fmt.Sprintf("sentry.message.parameters.%d", i)] = attribute.StringValue(fmt.Sprintf("%+v", p)) + } + } + + log := &Log{ + Timestamp: time.Now(), + TraceID: traceID, + SpanID: spanID, + Level: level, + Severity: severity, + Body: body, + Attributes: attrs, + } + log.approximateSize = computeLogSize(log) + + client.captureLog(log, scope) + if client.options.Debug { + debuglog.Print(body) + } +} + +func (l *sentryLogger) SetAttributes(attrs ...attribute.Builder) { + l.mu.Lock() + defer l.mu.Unlock() + + for _, a := range attrs { + if a.Value.Type() == attribute.INVALID { + debuglog.Printf("invalid attribute: %v", a) + continue + } + l.attributes[a.Key] = a.Value + } +} + +func (l *sentryLogger) Trace() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelTrace, + severity: LogSeverityTrace, + attributes: make(map[string]attribute.Value), + } +} + +func (l *sentryLogger) Debug() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelDebug, + severity: LogSeverityDebug, + attributes: make(map[string]attribute.Value), + } +} + +func (l *sentryLogger) Info() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelInfo, + severity: LogSeverityInfo, + attributes: make(map[string]attribute.Value), + } +} + +func (l *sentryLogger) Warn() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelWarn, + severity: LogSeverityWarning, + attributes: make(map[string]attribute.Value), + } +} + +func (l *sentryLogger) Error() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelError, + severity: LogSeverityError, + attributes: make(map[string]attribute.Value), + } +} + +func (l *sentryLogger) Fatal() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelFatal, + severity: LogSeverityFatal, + attributes: make(map[string]attribute.Value), + shouldFatal: true, + } +} + +func (l *sentryLogger) Panic() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelFatal, + severity: LogSeverityFatal, + attributes: make(map[string]attribute.Value), + shouldPanic: true, + } +} + +func (l *sentryLogger) LFatal() LogEntry { + return &logEntry{ + logger: l, + ctx: l.ctx, + level: LogLevelFatal, + severity: LogSeverityFatal, + attributes: make(map[string]attribute.Value), + } +} + +func (l *sentryLogger) GetCtx() context.Context { + return l.ctx +} + +func (e *logEntry) WithCtx(ctx context.Context) LogEntry { + return &logEntry{ + logger: e.logger, + ctx: ctx, + level: e.level, + severity: e.severity, + attributes: maps.Clone(e.attributes), + shouldPanic: e.shouldPanic, + shouldFatal: e.shouldFatal, + } +} + +func (e *logEntry) String(key, value string) LogEntry { + e.attributes[key] = attribute.StringValue(value) + return e +} + +func (e *logEntry) StringSlice(key string, value []string) LogEntry { + e.attributes[key] = attribute.StringSliceValue(value) + return e +} + +func (e *logEntry) Int(key string, value int) LogEntry { + e.attributes[key] = attribute.Int64Value(int64(value)) + return e +} + +func (e *logEntry) Int64Slice(key string, value []int64) LogEntry { + e.attributes[key] = attribute.Int64SliceValue(value) + return e +} + +func (e *logEntry) Int64(key string, value int64) LogEntry { + e.attributes[key] = attribute.Int64Value(value) + return e +} + +func (e *logEntry) Float64Slice(key string, value []float64) LogEntry { + e.attributes[key] = attribute.Float64SliceValue(value) + return e +} + +func (e *logEntry) Float64(key string, value float64) LogEntry { + e.attributes[key] = attribute.Float64Value(value) + return e +} + +func (e *logEntry) BoolSlice(key string, value []bool) LogEntry { + e.attributes[key] = attribute.BoolSliceValue(value) + return e +} + +func (e *logEntry) Bool(key string, value bool) LogEntry { + e.attributes[key] = attribute.BoolValue(value) + return e +} + +// Uint64 adds uint64 attributes to the log entry. +// +// This method is intentionally not part of the LogEntry interface to avoid exposing uint64 in the public API. +func (e *logEntry) Uint64(key string, value uint64) LogEntry { + e.attributes[key] = attribute.Uint64Value(value) + return e +} + +func (e *logEntry) Emit(args ...interface{}) { + e.logger.log(e.ctx, e.level, e.severity, fmt.Sprint(args...), e.attributes, false) + + if e.level == LogLevelFatal { + if e.shouldPanic { + panic(fmt.Sprint(args...)) + } + if e.shouldFatal { + os.Exit(1) + } + } +} + +func (e *logEntry) Emitf(format string, args ...interface{}) { + e.logger.log(e.ctx, e.level, e.severity, format, e.attributes, true, args...) + + if e.level == LogLevelFatal { + if e.shouldPanic { + formattedMessage := fmt.Sprintf(format, args...) + panic(formattedMessage) + } + if e.shouldFatal { + os.Exit(1) + } + } +} diff --git a/vendor/github.com/getsentry/sentry-go/log_batch_processor.go b/vendor/github.com/getsentry/sentry-go/log_batch_processor.go new file mode 100644 index 0000000..e361a39 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/log_batch_processor.go @@ -0,0 +1,32 @@ +package sentry + +import ( + "time" +) + +// logBatchProcessor batches logs and sends them to Sentry. +type logBatchProcessor struct { + *batchProcessor[Log] +} + +func newLogBatchProcessor(client *Client) *logBatchProcessor { + return &logBatchProcessor{ + batchProcessor: newBatchProcessor(func(items []Log) { + if len(items) == 0 { + return + } + + event := NewEvent() + event.Timestamp = time.Now() + event.EventID = EventID(uuid()) + event.Type = logEvent.Type + event.Logs = items + + client.Transport.SendEvent(event) + }), + } +} + +func (p *logBatchProcessor) Send(log *Log) bool { + return p.batchProcessor.Send(*log) +} diff --git a/vendor/github.com/getsentry/sentry-go/log_fallback.go b/vendor/github.com/getsentry/sentry-go/log_fallback.go new file mode 100644 index 0000000..e6c35e4 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/log_fallback.go @@ -0,0 +1,130 @@ +package sentry + +import ( + "context" + "fmt" + "os" + + "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" +) + +// Fallback, no-op logger if logging is disabled. +type noopLogger struct{} + +// noopLogEntry implements LogEntry for the no-op logger. +type noopLogEntry struct { + level LogLevel + shouldPanic bool + shouldFatal bool +} + +func (n *noopLogEntry) WithCtx(_ context.Context) LogEntry { + return n +} + +func (n *noopLogEntry) String(_, _ string) LogEntry { + return n +} + +func (n *noopLogEntry) Int(_ string, _ int) LogEntry { + return n +} + +func (n *noopLogEntry) Int64(_ string, _ int64) LogEntry { + return n +} + +func (n *noopLogEntry) Float64(_ string, _ float64) LogEntry { + return n +} + +func (n *noopLogEntry) Bool(_ string, _ bool) LogEntry { + return n +} + +func (n *noopLogEntry) StringSlice(_ string, _ []string) LogEntry { + return n +} + +func (n *noopLogEntry) Int64Slice(_ string, _ []int64) LogEntry { + return n +} + +func (n *noopLogEntry) Float64Slice(_ string, _ []float64) LogEntry { + return n +} + +func (n *noopLogEntry) BoolSlice(_ string, _ []bool) LogEntry { + return n +} + +func (n *noopLogEntry) Attributes(_ ...attribute.Builder) LogEntry { + return n +} + +func (n *noopLogEntry) Emit(args ...interface{}) { + debuglog.Printf("Log with level=[%v] is being dropped. SDK not initialized or logs disabled", n.level) + if n.level == LogLevelFatal { + if n.shouldPanic { + panic(args) + } + if n.shouldFatal { + os.Exit(1) + } + } +} + +func (n *noopLogEntry) Emitf(message string, args ...interface{}) { + debuglog.Printf("Log with level=[%v] is being dropped. SDK not initialized or logs disabled", n.level) + if n.level == LogLevelFatal { + if n.shouldPanic { + panic(fmt.Sprintf(message, args...)) + } + if n.shouldFatal { + os.Exit(1) + } + } +} + +func (n *noopLogger) GetCtx() context.Context { return context.Background() } + +func (*noopLogger) Trace() LogEntry { + return &noopLogEntry{level: LogLevelTrace} +} + +func (*noopLogger) Debug() LogEntry { + return &noopLogEntry{level: LogLevelDebug} +} + +func (*noopLogger) Info() LogEntry { + return &noopLogEntry{level: LogLevelInfo} +} + +func (*noopLogger) Warn() LogEntry { + return &noopLogEntry{level: LogLevelWarn} +} + +func (*noopLogger) Error() LogEntry { + return &noopLogEntry{level: LogLevelError} +} + +func (*noopLogger) Fatal() LogEntry { + return &noopLogEntry{level: LogLevelFatal, shouldFatal: true} +} + +func (*noopLogger) Panic() LogEntry { + return &noopLogEntry{level: LogLevelFatal, shouldPanic: true} +} + +func (*noopLogger) LFatal() LogEntry { + return &noopLogEntry{level: LogLevelFatal} +} + +func (*noopLogger) SetAttributes(...attribute.Builder) { + debuglog.Printf("No attributes attached. SDK not initialized or logs disabled") +} + +func (*noopLogger) Write(_ []byte) (n int, err error) { + return 0, fmt.Errorf("log with level=[%v] is being dropped. SDK not initialized or logs disabled", LogLevelInfo) +} diff --git a/vendor/github.com/getsentry/sentry-go/metric_batch_processor.go b/vendor/github.com/getsentry/sentry-go/metric_batch_processor.go new file mode 100644 index 0000000..788d3ad --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/metric_batch_processor.go @@ -0,0 +1,32 @@ +package sentry + +import ( + "time" +) + +// metricBatchProcessor batches metrics and sends them to Sentry. +type metricBatchProcessor struct { + *batchProcessor[Metric] +} + +func newMetricBatchProcessor(client *Client) *metricBatchProcessor { + return &metricBatchProcessor{ + batchProcessor: newBatchProcessor(func(items []Metric) { + if len(items) == 0 { + return + } + + event := NewEvent() + event.Timestamp = time.Now() + event.EventID = EventID(uuid()) + event.Type = traceMetricEvent.Type + event.Metrics = items + + client.Transport.SendEvent(event) + }), + } +} + +func (p *metricBatchProcessor) Send(metric *Metric) bool { + return p.batchProcessor.Send(*metric) +} diff --git a/vendor/github.com/getsentry/sentry-go/metrics.go b/vendor/github.com/getsentry/sentry-go/metrics.go new file mode 100644 index 0000000..c3dcb03 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/metrics.go @@ -0,0 +1,241 @@ +package sentry + +import ( + "context" + "maps" + "os" + "sync" + "time" + + "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" +) + +// Duration Units. +const ( + UnitNanosecond = "nanosecond" + UnitMicrosecond = "microsecond" + UnitMillisecond = "millisecond" + UnitSecond = "second" + UnitMinute = "minute" + UnitHour = "hour" + UnitDay = "day" + UnitWeek = "week" +) + +// Information Units. +const ( + UnitBit = "bit" + UnitByte = "byte" + UnitKilobyte = "kilobyte" + UnitKibibyte = "kibibyte" + UnitMegabyte = "megabyte" + UnitMebibyte = "mebibyte" + UnitGigabyte = "gigabyte" + UnitGibibyte = "gibibyte" + UnitTerabyte = "terabyte" + UnitTebibyte = "tebibyte" + UnitPetabyte = "petabyte" + UnitPebibyte = "pebibyte" + UnitExabyte = "exabyte" + UnitExbibyte = "exbibyte" +) + +// Fraction Units. +const ( + UnitRatio = "ratio" + UnitPercent = "percent" +) + +// 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) + if hub == nil { + hub = CurrentHub() + } + client := hub.Client() + if client != nil { + // build default attrs + serverAddr := client.options.ServerName + if serverAddr == "" { + serverAddr, _ = os.Hostname() + } + + defaults := map[string]string{ + "sentry.release": client.options.Release, + "sentry.environment": client.options.Environment, + "sentry.server.address": serverAddr, + "sentry.sdk.name": client.sdkIdentifier, + "sentry.sdk.version": client.sdkVersion, + } + + defaultAttrs := make(map[string]attribute.Value) + for k, v := range defaults { + if v != "" { + defaultAttrs[k] = attribute.StringValue(v) + } + } + + return &sentryMeter{ + ctx: ctx, + hub: hub, + attributes: make(map[string]attribute.Value), + defaultAttributes: defaultAttrs, + mu: sync.RWMutex{}, + } + } + + debuglog.Printf("fallback to noopMeter: SDK not initialized") + return &noopMeter{} +} + +type sentryMeter struct { + ctx context.Context + hub *Hub + attributes map[string]attribute.Value + defaultAttributes map[string]attribute.Value + mu sync.RWMutex +} + +func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name string, value MetricValue, unit string, attributes map[string]attribute.Value, customScope *Scope) { + if name == "" { + debuglog.Println("empty name provided, dropping metric") + return + } + + hub := hubFromContexts(ctx, m.ctx) + if hub == nil { + hub = m.hub + } + + client := hub.Client() + if client == nil { + return + } + + scope := hub.Scope() + if customScope != nil { + scope = customScope + } + traceID, spanID := resolveTrace(scope, client, ctx, m.ctx) + + // Pre-allocate with capacity hint to avoid map growth reallocations + estimatedCap := len(m.defaultAttributes) + len(attributes) + 8 // scope ~3 + call-specific ~5 + attrs := make(map[string]attribute.Value, estimatedCap) + + // attribute precedence: default -> scope -> instance (from SetAttrs) -> entry-specific + for k, v := range m.defaultAttributes { + attrs[k] = v + } + scope.populateAttrs(attrs) + + m.mu.RLock() + for k, v := range m.attributes { + attrs[k] = v + } + m.mu.RUnlock() + + for k, v := range attributes { + attrs[k] = v + } + + metric := &Metric{ + Timestamp: time.Now(), + TraceID: traceID, + SpanID: spanID, + Type: metricType, + Name: name, + Value: value, + Unit: unit, + Attributes: attrs, + } + + if client.captureMetric(metric, scope) && client.options.Debug { + debuglog.Printf("Metric %s [%s]: %v %s", metricType, name, value.AsInterface(), unit) + } +} + +// WithCtx returns a new Meter that uses the given context for trace/span association. +func (m *sentryMeter) WithCtx(ctx context.Context) Meter { + m.mu.RLock() + attrsCopy := maps.Clone(m.attributes) + m.mu.RUnlock() + + return &sentryMeter{ + ctx: ctx, + hub: m.hub, + attributes: attrsCopy, + defaultAttributes: m.defaultAttributes, + mu: sync.RWMutex{}, + } +} + +func (m *sentryMeter) applyOptions(opts []MeterOption) *meterOptions { + o := &meterOptions{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Count implements Meter. +func (m *sentryMeter) Count(name string, count int64, opts ...MeterOption) { + o := m.applyOptions(opts) + m.emit(m.ctx, MetricTypeCounter, name, Int64MetricValue(count), o.unit, o.attributes, o.scope) +} + +// Distribution implements Meter. +func (m *sentryMeter) Distribution(name string, sample float64, opts ...MeterOption) { + o := m.applyOptions(opts) + m.emit(m.ctx, MetricTypeDistribution, name, Float64MetricValue(sample), o.unit, o.attributes, o.scope) +} + +// Gauge implements Meter. +func (m *sentryMeter) Gauge(name string, value float64, opts ...MeterOption) { + o := m.applyOptions(opts) + m.emit(m.ctx, MetricTypeGauge, name, Float64MetricValue(value), o.unit, o.attributes, o.scope) +} + +// SetAttributes implements Meter. +func (m *sentryMeter) SetAttributes(attrs ...attribute.Builder) { + m.mu.Lock() + defer m.mu.Unlock() + + for _, a := range attrs { + if a.Value.Type() == attribute.INVALID { + debuglog.Printf("invalid attribute: %v", a) + continue + } + m.attributes[a.Key] = a.Value + } +} + +// noopMeter is a no-operation implementation of Meter. +// This is used when there is no client available in the context or when metrics are disabled. +type noopMeter struct{} + +// WithCtx implements Meter. +func (n *noopMeter) WithCtx(_ context.Context) Meter { + return n +} + +// Count implements Meter. +func (n *noopMeter) Count(name string, _ int64, _ ...MeterOption) { + 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. Ensure the SDK is initialized", name) +} + +// Gauge implements Meter. +func (n *noopMeter) Gauge(name string, _ float64, _ ...MeterOption) { + 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") +} diff --git a/vendor/github.com/getsentry/sentry-go/mocks.go b/vendor/github.com/getsentry/sentry-go/mocks.go new file mode 100644 index 0000000..9492b1c --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/mocks.go @@ -0,0 +1,99 @@ +package sentry + +import ( + "context" + "sync" + "time" +) + +// MockScope implements [Scope] for use in tests. +type MockScope struct { + breadcrumb *Breadcrumb + shouldDropEvent bool +} + +func (scope *MockScope) AddBreadcrumb(breadcrumb *Breadcrumb, _ int) { + scope.breadcrumb = breadcrumb +} + +func (scope *MockScope) ApplyToEvent(event *Event, _ *EventHint, _ *Client) *Event { + if scope.shouldDropEvent { + return nil + } + return event +} + +// MockTransport implements [Transport] for use in tests. +type MockTransport struct { + mu sync.Mutex + events []*Event + lastEvent *Event +} + +func (t *MockTransport) Configure(_ ClientOptions) {} +func (t *MockTransport) SendEvent(event *Event) { + t.mu.Lock() + defer t.mu.Unlock() + t.events = append(t.events, event) + t.lastEvent = event +} +func (t *MockTransport) Flush(_ time.Duration) bool { + return true +} +func (t *MockTransport) FlushWithContext(_ context.Context) bool { return true } +func (t *MockTransport) Events() []*Event { + t.mu.Lock() + defer t.mu.Unlock() + return t.events +} +func (t *MockTransport) Close() {} + +// MockLogEntry implements [sentry.LogEntry] for use in tests. +type MockLogEntry struct { + Attributes map[string]any +} + +func (m *MockLogEntry) StringSlice(key string, value []string) LogEntry { + m.Attributes[key] = value + return m +} + +func (m *MockLogEntry) Int64Slice(key string, value []int64) LogEntry { + m.Attributes[key] = value + return m +} + +func (m *MockLogEntry) Float64Slice(key string, value []float64) LogEntry { + m.Attributes[key] = value + return m +} + +func (m *MockLogEntry) BoolSlice(key string, value []bool) LogEntry { + m.Attributes[key] = value + return m +} + +func NewMockLogEntry() *MockLogEntry { + return &MockLogEntry{Attributes: make(map[string]any)} +} + +func (m *MockLogEntry) WithCtx(_ context.Context) LogEntry { return m } +func (m *MockLogEntry) String(key, value string) LogEntry { m.Attributes[key] = value; return m } +func (m *MockLogEntry) Int(key string, value int) LogEntry { + m.Attributes[key] = int64(value) + return m +} +func (m *MockLogEntry) Int64(key string, value int64) LogEntry { + m.Attributes[key] = value + return m +} +func (m *MockLogEntry) Float64(key string, value float64) LogEntry { + m.Attributes[key] = value + return m +} +func (m *MockLogEntry) Bool(key string, value bool) LogEntry { + m.Attributes[key] = value + return m +} +func (m *MockLogEntry) Emit(...any) {} +func (m *MockLogEntry) Emitf(string, ...any) {} diff --git a/vendor/github.com/getsentry/sentry-go/option.go b/vendor/github.com/getsentry/sentry-go/option.go new file mode 100644 index 0000000..4941ab3 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/option.go @@ -0,0 +1,23 @@ +package sentry + +// Option represents an optional configuration value. +// +// The zero value is unset. Use Set to distinguish an explicitly configured +// zero value, such as false, 0, or "", from an unset option. +type Option[T any] struct { + Value T + IsSet bool +} + +// Set returns an Option containing v. +func Set[T any](v T) Option[T] { + return Option[T]{Value: v, IsSet: true} +} + +// Or returns the option value when set, or defaultValue otherwise. +func (o Option[T]) Or(defaultValue T) T { + if o.IsSet { + return o.Value + } + return defaultValue +} diff --git a/vendor/github.com/getsentry/sentry-go/propagation_context.go b/vendor/github.com/getsentry/sentry-go/propagation_context.go new file mode 100644 index 0000000..310de72 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/propagation_context.go @@ -0,0 +1,74 @@ +package sentry + +import ( + "crypto/rand" +) + +type PropagationContext struct { + TraceID TraceID `json:"trace_id"` + SpanID SpanID `json:"span_id"` + ParentSpanID SpanID `json:"parent_span_id,omitzero"` + DynamicSamplingContext DynamicSamplingContext `json:"-"` +} + +func (p PropagationContext) Map() map[string]interface{} { + m := map[string]interface{}{ + "trace_id": p.TraceID, + "span_id": p.SpanID, + } + + if p.ParentSpanID != zeroSpanID { + m["parent_span_id"] = p.ParentSpanID + } + + return m +} + +func NewPropagationContext() PropagationContext { + p := PropagationContext{} + + if _, err := rand.Read(p.TraceID[:]); err != nil { + panic(err) + } + + if _, err := rand.Read(p.SpanID[:]); err != nil { + panic(err) + } + + return p +} + +func PropagationContextFromHeaders(trace, baggage string) (PropagationContext, error) { + p := NewPropagationContext() + + if _, err := rand.Read(p.SpanID[:]); err != nil { + panic(err) + } + + hasTrace := false + if trace != "" { + if tpc, valid := ParseTraceParentContext([]byte(trace)); valid { + hasTrace = true + p.TraceID = tpc.TraceID + p.ParentSpanID = tpc.ParentSpanID + } + } + + if baggage != "" { + dsc, err := DynamicSamplingContextFromHeader([]byte(baggage)) + if err != nil { + return PropagationContext{}, err + } + p.DynamicSamplingContext = dsc + } + + // In case a sentry-trace header is present but there are no sentry-related + // values in the baggage, create an empty, frozen DynamicSamplingContext. + if hasTrace && !p.DynamicSamplingContext.HasEntries() { + p.DynamicSamplingContext = DynamicSamplingContext{ + Frozen: true, + } + } + + return p, nil +} diff --git a/vendor/github.com/getsentry/sentry-go/report/aggregator.go b/vendor/github.com/getsentry/sentry-go/report/aggregator.go new file mode 100644 index 0000000..c48d634 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/report/aggregator.go @@ -0,0 +1,169 @@ +package report + +import ( + "sync" + "sync/atomic" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// Aggregator collects discarded event outcomes for client reports. +// Uses atomic operations to be safe for concurrent use. +type Aggregator struct { + mu sync.Mutex + outcomes map[OutcomeKey]*atomic.Int64 +} + +// NewAggregator creates a new client report Aggregator. +func NewAggregator() *Aggregator { + a := &Aggregator{ + outcomes: make(map[OutcomeKey]*atomic.Int64), + } + return a +} + +// Record records a discarded event outcome. +func (a *Aggregator) Record(reason DiscardReason, category ratelimit.Category, quantity int64) { + if a == nil || quantity <= 0 { + return + } + + key := OutcomeKey{Reason: reason, Category: category} + + a.mu.Lock() + defer a.mu.Unlock() + counter, exists := a.outcomes[key] + if !exists { + counter = &atomic.Int64{} + a.outcomes[key] = counter + } + counter.Add(quantity) +} + +// RecordOne is a helper method to record one discarded event outcome. +func (a *Aggregator) RecordOne(reason DiscardReason, category ratelimit.Category) { + a.Record(reason, category, 1) +} + +// TakeReport atomically takes all accumulated outcomes and returns a ClientReport. +func (a *Aggregator) TakeReport() *ClientReport { + if a == nil { + return nil + } + a.mu.Lock() + defer a.mu.Unlock() + + if len(a.outcomes) == 0 { + return nil + } + + var events []DiscardedEvent + for key, counter := range a.outcomes { + quantity := counter.Swap(0) + if quantity > 0 { + events = append(events, DiscardedEvent{ + Reason: key.Reason, + Category: key.Category, + Quantity: quantity, + }) + } + } + + // Clear empty counters to prevent unbounded growth + for key, counter := range a.outcomes { + if counter.Load() == 0 { + delete(a.outcomes, key) + } + } + + if len(events) == 0 { + return nil + } + + return &ClientReport{ + Timestamp: time.Now(), + DiscardedEvents: events, + } +} + +// RecordForEnvelope records client report outcomes for all items in the envelope. +// It inspects envelope item headers to derive categories, span counts, and log byte sizes. +func (a *Aggregator) RecordForEnvelope(reason DiscardReason, envelope *protocol.Envelope) { + if a == nil { + return + } + + for _, item := range envelope.Items { + if item == nil || item.Header == nil { + continue + } + switch item.Header.Type { + case protocol.EnvelopeItemTypeEvent: + a.RecordOne(reason, ratelimit.CategoryError) + case protocol.EnvelopeItemTypeTransaction: + a.RecordOne(reason, ratelimit.CategoryTransaction) + spanCount := int64(item.Header.SpanCount) + a.Record(reason, ratelimit.CategorySpan, spanCount) + case protocol.EnvelopeItemTypeLog: + if item.Header.ItemCount != nil { + a.Record(reason, ratelimit.CategoryLog, int64(*item.Header.ItemCount)) + } + if item.Header.Length != nil { + a.Record(reason, ratelimit.CategoryLogByte, int64(*item.Header.Length)) + } + case protocol.EnvelopeItemTypeTraceMetric: + a.RecordOne(reason, ratelimit.CategoryTraceMetric) + case protocol.EnvelopeItemTypeCheckIn: + a.RecordOne(reason, ratelimit.CategoryMonitor) + case protocol.EnvelopeItemTypeAttachment, protocol.EnvelopeItemTypeClientReport: + // Skip — not reportable categories + } + } +} + +// RecordItem records outcomes for a telemetry item, including supplementary +// categories (span outcomes for transactions, byte size for logs). +func (a *Aggregator) RecordItem(reason DiscardReason, item ReportableItem) { + category := item.GetCategory() + a.RecordOne(reason, category) + + // Span outcomes for transactions + if category == ratelimit.CategoryTransaction { + type spanCounter interface{ GetSpanCount() int } + if sc, ok := item.(spanCounter); ok { + if count := sc.GetSpanCount(); count > 0 { + a.Record(reason, ratelimit.CategorySpan, int64(count)) + } + } + } + + // Byte size outcomes for logs + if category == ratelimit.CategoryLog { + type sizer interface{ ApproximateSize() int } + if s, ok := item.(sizer); ok { + if size := s.ApproximateSize(); size > 0 { + a.Record(reason, ratelimit.CategoryLogByte, int64(size)) + } + } + } +} + +// AttachToEnvelope adds a client report to the envelope if the Aggregator has outcomes available. +func (a *Aggregator) AttachToEnvelope(envelope *protocol.Envelope) { + if a == nil { + return + } + + r := a.TakeReport() + if r != nil { + rItem, err := r.ToEnvelopeItem() + if err == nil { + envelope.AddItem(rItem) + } else { + debuglog.Printf("failed to serialize client report: %v, with err: %v", r, err) + } + } +} diff --git a/vendor/github.com/getsentry/sentry-go/report/interfaces.go b/vendor/github.com/getsentry/sentry-go/report/interfaces.go new file mode 100644 index 0000000..849b999 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/report/interfaces.go @@ -0,0 +1,45 @@ +package report + +import ( + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// ReportableItem is the minimal surface needed for client report accounting. +type ReportableItem interface { + GetCategory() ratelimit.Category +} + +// ClientReportRecorder is used by components that need to record lost/discarded events. +type ClientReportRecorder interface { + Record(reason DiscardReason, category ratelimit.Category, quantity int64) + RecordOne(reason DiscardReason, category ratelimit.Category) + RecordForEnvelope(reason DiscardReason, envelope *protocol.Envelope) + RecordItem(reason DiscardReason, item ReportableItem) +} + +// ClientReportProvider is used by the single component responsible for sending client reports. +type ClientReportProvider interface { + TakeReport() *ClientReport + AttachToEnvelope(envelope *protocol.Envelope) +} + +// noopRecorder is a no-op implementation of ClientReportRecorder. +type noopRecorder struct{} + +func (noopRecorder) Record(DiscardReason, ratelimit.Category, int64) {} +func (noopRecorder) RecordOne(DiscardReason, ratelimit.Category) {} +func (noopRecorder) RecordForEnvelope(DiscardReason, *protocol.Envelope) {} +func (noopRecorder) RecordItem(DiscardReason, ReportableItem) {} + +// noopProvider is a no-op implementation of ClientReportProvider. +type noopProvider struct{} + +func (noopProvider) TakeReport() *ClientReport { return nil } +func (noopProvider) AttachToEnvelope(_ *protocol.Envelope) {} + +// NoopRecorder returns a no-op ClientReportRecorder that silently discards all records. +func NoopRecorder() ClientReportRecorder { return noopRecorder{} } + +// NoopProvider returns a no-op ClientReportProvider that always returns nil reports. +func NoopProvider() ClientReportProvider { return noopProvider{} } diff --git a/vendor/github.com/getsentry/sentry-go/report/outcome.go b/vendor/github.com/getsentry/sentry-go/report/outcome.go new file mode 100644 index 0000000..63d6eaf --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/report/outcome.go @@ -0,0 +1,18 @@ +package report + +import ( + "github.com/getsentry/sentry-go/internal/ratelimit" +) + +// OutcomeKey uniquely identifies an outcome bucket for aggregation. +type OutcomeKey struct { + Reason DiscardReason + Category ratelimit.Category +} + +// DiscardedEvent represents a single discard event outcome for the OutcomeKey. +type DiscardedEvent struct { + Reason DiscardReason `json:"reason"` + Category ratelimit.Category `json:"category"` + Quantity int64 `json:"quantity"` +} diff --git a/vendor/github.com/getsentry/sentry-go/report/reason.go b/vendor/github.com/getsentry/sentry-go/report/reason.go new file mode 100644 index 0000000..5a1d218 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/report/reason.go @@ -0,0 +1,38 @@ +package report + +// DiscardReason represents why an item was discarded. +type DiscardReason string + +const ( + // ReasonQueueOverflow indicates the transport queue was full. + ReasonQueueOverflow DiscardReason = "queue_overflow" + + // ReasonBufferOverflow indicates that an internal buffer was full. + ReasonBufferOverflow DiscardReason = "buffer_overflow" + + // ReasonRateLimitBackoff indicates the item was dropped due to rate limiting. + ReasonRateLimitBackoff DiscardReason = "ratelimit_backoff" + + // ReasonBeforeSend indicates the item was dropped due to a BeforeSend callback. + ReasonBeforeSend DiscardReason = "before_send" + + // ReasonEventProcessor indicates the item was dropped due to an event processor callback. + ReasonEventProcessor DiscardReason = "event_processor" + + // ReasonSampleRate indicates the item was dropped due to sampling. + ReasonSampleRate DiscardReason = "sample_rate" + + // ReasonNetworkError indicates an HTTP request failed (connection error). + ReasonNetworkError DiscardReason = "network_error" + + // ReasonSendError indicates HTTP returned an error status (4xx, 5xx). + // + // The party that drops an envelope is responsible for counting the event (we skip outcomes that the server records + // `http.StatusTooManyRequests` 429). However, relay does not always record an outcome for oversized envelopes, so + // we accept the trade-off of double counting `http.StatusRequestEntityTooLarge` (413) codes, to record all events. + // For more details https://develop.sentry.dev/sdk/expected-features/#dealing-with-network-failures + ReasonSendError DiscardReason = "send_error" + + // ReasonInternalError indicates an internal SDK error. + ReasonInternalError DiscardReason = "internal_sdk_error" +) diff --git a/vendor/github.com/getsentry/sentry-go/report/report.go b/vendor/github.com/getsentry/sentry-go/report/report.go new file mode 100644 index 0000000..9d1e720 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/report/report.go @@ -0,0 +1,23 @@ +package report + +import ( + "encoding/json" + "time" + + "github.com/getsentry/sentry-go/internal/protocol" +) + +// ClientReport is the payload sent to Sentry for tracking discarded events. +type ClientReport struct { + Timestamp time.Time `json:"timestamp"` + DiscardedEvents []DiscardedEvent `json:"discarded_events"` +} + +// ToEnvelopeItem converts the ClientReport to an envelope item. +func (r *ClientReport) ToEnvelopeItem() (*protocol.EnvelopeItem, error) { + payload, err := json.Marshal(r) + if err != nil { + return nil, err + } + return protocol.NewClientReportItem(payload), nil +} diff --git a/vendor/github.com/getsentry/sentry-go/scope.go b/vendor/github.com/getsentry/sentry-go/scope.go new file mode 100644 index 0000000..c7a6067 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/scope.go @@ -0,0 +1,552 @@ +package sentry + +import ( + "context" + "io" + "maps" + "net/http" + "sync" + "time" + + "github.com/getsentry/sentry-go/attribute" + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/httputils" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/report" +) + +// Scope holds contextual data for the current scope. +// +// The scope is an object that can cloned efficiently and stores data that is +// locally relevant to an event. For instance the scope will hold recorded +// breadcrumbs and similar information. +// +// The scope can be interacted with in two ways. First, the scope is routinely +// updated with information by functions such as AddBreadcrumb which will modify +// the current scope. Second, the current scope can be configured through the +// ConfigureScope function or Hub method of the same name. +// +// The scope is meant to be modified but not inspected directly. When preparing +// an event for reporting, the current client adds information from the current +// scope into the event. +type Scope struct { + mu sync.RWMutex + attributes map[string]attribute.Value + breadcrumbs []*Breadcrumb + attachments []*Attachment + user User + tags map[string]string + contexts map[string]Context + fingerprint []string + level Level + request *http.Request + // requestBody holds a reference to the original request.Body. + requestBody interface { + // Bytes returns bytes from the original body, lazily buffered as the + // original body is read. + Bytes() []byte + // Overflow returns true if the body is larger than the maximum buffer + // size. + Overflow() bool + } + eventProcessors []EventProcessor + + propagationContext PropagationContext + span *Span +} + +// NewScope creates a new Scope. +func NewScope() *Scope { + return &Scope{ + attributes: make(map[string]attribute.Value), + breadcrumbs: make([]*Breadcrumb, 0), + attachments: make([]*Attachment, 0), + tags: make(map[string]string), + contexts: make(map[string]Context), + fingerprint: make([]string, 0), + propagationContext: NewPropagationContext(), + } +} + +// AddBreadcrumb adds new breadcrumb to the current scope +// and optionally throws the old one if limit is reached. +func (scope *Scope) AddBreadcrumb(breadcrumb *Breadcrumb, limit int) { + if breadcrumb.Timestamp.IsZero() { + breadcrumb.Timestamp = time.Now() + } + + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.breadcrumbs = append(scope.breadcrumbs, breadcrumb) + if len(scope.breadcrumbs) > limit { + scope.breadcrumbs = scope.breadcrumbs[1 : limit+1] + } +} + +// ClearBreadcrumbs clears all breadcrumbs from the current scope. +func (scope *Scope) ClearBreadcrumbs() { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.breadcrumbs = []*Breadcrumb{} +} + +// AddAttachment adds new attachment to the current scope. +func (scope *Scope) AddAttachment(attachment *Attachment) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.attachments = append(scope.attachments, attachment) +} + +// ClearAttachments clears all attachments from the current scope. +func (scope *Scope) ClearAttachments() { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.attachments = []*Attachment{} +} + +// SetUser sets the user for the current scope. +func (scope *Scope) SetUser(user User) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.user = user +} + +// SetRequest sets the request for the current scope. +func (scope *Scope) SetRequest(r *http.Request) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.request = r + + if r == nil { + return + } + + // Don't buffer request body if we know it is oversized. + if r.ContentLength > httputils.MaxBodyBytes { + return + } + // Don't buffer if there is no body. + if r.Body == nil || r.Body == http.NoBody { + return + } + buf := httputils.NewLimitedBuffer(httputils.MaxBodyBytes) + r.Body = httputils.ReadCloser{ + Reader: io.TeeReader(r.Body, buf), + Closer: r.Body, + } + scope.requestBody = buf +} + +// SetRequestBody sets the request body for the current scope. +// +// This method should only be called when the body bytes are already available +// in memory. Typically, the request body is buffered lazily from the +// Request.Body from SetRequest. +func (scope *Scope) SetRequestBody(b []byte) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.requestBody = httputils.NewLimitedBufferFromBytes(httputils.MaxBodyBytes, b) +} + +// SetAttributes adds attributes to the current scope. +func (scope *Scope) SetAttributes(attrs ...attribute.Builder) { + scope.mu.Lock() + defer scope.mu.Unlock() + + for _, a := range attrs { + if a.Value.Type() == attribute.INVALID { + debuglog.Printf("invalid attribute: %v", a) + continue + } + scope.attributes[a.Key] = a.Value + } +} + +// RemoveAttribute removes an attribute from the current scope. +func (scope *Scope) RemoveAttribute(key string) { + scope.mu.Lock() + defer scope.mu.Unlock() + delete(scope.attributes, key) +} + +// SetTag adds a tag to the current scope. +func (scope *Scope) SetTag(key, value string) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.tags[key] = value +} + +// SetTags assigns multiple tags to the current scope. +func (scope *Scope) SetTags(tags map[string]string) { + scope.mu.Lock() + defer scope.mu.Unlock() + + for k, v := range tags { + scope.tags[k] = v + } +} + +// RemoveTag removes a tag from the current scope. +func (scope *Scope) RemoveTag(key string) { + scope.mu.Lock() + defer scope.mu.Unlock() + + delete(scope.tags, key) +} + +// SetContext adds a context to the current scope. +func (scope *Scope) SetContext(key string, value Context) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.contexts[key] = value +} + +// SetContexts assigns multiple contexts to the current scope. +func (scope *Scope) SetContexts(contexts map[string]Context) { + scope.mu.Lock() + defer scope.mu.Unlock() + + for k, v := range contexts { + scope.contexts[k] = v + } +} + +// RemoveContext removes a context from the current scope. +func (scope *Scope) RemoveContext(key string) { + scope.mu.Lock() + defer scope.mu.Unlock() + + delete(scope.contexts, key) +} + +// SetFingerprint sets new fingerprint for the current scope. +func (scope *Scope) SetFingerprint(fingerprint []string) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.fingerprint = fingerprint +} + +// SetLevel sets new level for the current scope. +func (scope *Scope) SetLevel(level Level) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.level = level +} + +// SetPropagationContext sets the propagation context for the current scope. +func (scope *Scope) SetPropagationContext(propagationContext PropagationContext) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.propagationContext = propagationContext +} + +func (scope *Scope) propagationContextSnapshot() PropagationContext { + scope.mu.RLock() + defer scope.mu.RUnlock() + + return scope.propagationContext +} + +// GetSpan returns the span from the current scope. +func (scope *Scope) GetSpan() *Span { + scope.mu.RLock() + defer scope.mu.RUnlock() + + return scope.span +} + +// SetSpan sets a span for the current scope. +func (scope *Scope) SetSpan(span *Span) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.span = span +} + +// Clone returns a copy of the current scope with all data copied over. +func (scope *Scope) Clone() *Scope { + scope.mu.RLock() + defer scope.mu.RUnlock() + + clone := NewScope() + clone.user = scope.user + clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs)) + copy(clone.breadcrumbs, scope.breadcrumbs) + clone.attachments = make([]*Attachment, len(scope.attachments)) + copy(clone.attachments, scope.attachments) + clone.attributes = maps.Clone(scope.attributes) + clone.contexts = maps.Clone(scope.contexts) + clone.tags = maps.Clone(scope.tags) + clone.fingerprint = make([]string, len(scope.fingerprint)) + copy(clone.fingerprint, scope.fingerprint) + clone.level = scope.level + clone.request = scope.request + clone.requestBody = scope.requestBody + clone.eventProcessors = scope.eventProcessors[:len(scope.eventProcessors):len(scope.eventProcessors)] + clone.propagationContext = scope.propagationContext + clone.span = scope.span + return clone +} + +// Clear removes the data from the current scope. Not safe for concurrent use. +func (scope *Scope) Clear() { + *scope = *NewScope() +} + +// AddEventProcessor adds an event processor to the current scope. +func (scope *Scope) AddEventProcessor(processor EventProcessor) { + scope.mu.Lock() + defer scope.mu.Unlock() + + scope.eventProcessors = append(scope.eventProcessors, processor) +} + +// ApplyToEvent takes the data from the current scope and attaches it to the event. +func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event { //nolint:gocyclo + scope.mu.RLock() + defer scope.mu.RUnlock() + + if len(scope.breadcrumbs) > 0 { + event.Breadcrumbs = append(event.Breadcrumbs, scope.breadcrumbs...) + } + + if len(scope.attachments) > 0 { + event.Attachments = append(event.Attachments, scope.attachments...) + } + + if len(scope.tags) > 0 { + if event.Tags == nil { + event.Tags = make(map[string]string, len(scope.tags)) + } + + for key, value := range scope.tags { + event.Tags[key] = value + } + } + + if len(scope.contexts) > 0 { + if event.Contexts == nil { + event.Contexts = make(map[string]Context) + } + + for key, value := range scope.contexts { + if key == "trace" && event.Type == transactionType { + // Do not override trace context of + // transactions, otherwise it breaks the + // transaction event representation. + // For error events, the trace context is used + // to link errors and traces/spans in Sentry. + continue + } + + // Ensure we are not overwriting event fields + if _, ok := event.Contexts[key]; !ok { + event.Contexts[key] = cloneContext(value) + } + } + } + + if event.Contexts == nil { + event.Contexts = make(map[string]Context) + } + + if scope.span != nil { + if _, ok := event.Contexts["trace"]; !ok { + event.Contexts["trace"] = scope.span.traceContext().Map() + } + + transaction := scope.span.GetTransaction() + if transaction != nil { + event.sdkMetaData.dsc = DynamicSamplingContextFromTransaction(transaction) + } + } else { + event.Contexts["trace"] = scope.propagationContext.Map() + + dsc := scope.propagationContext.DynamicSamplingContext + if !dsc.HasEntries() && client != nil { + dsc = DynamicSamplingContextFromScope(scope, client) + } + event.sdkMetaData.dsc = dsc + } + + // If an external trace resolver is registered (e.g. OTel), override + // trace/span IDs from the hint context or the scope's request context. + if client != nil { + var ctx context.Context + if hint != nil { + ctx = hint.Context + } + if ctx == nil && scope.request != nil { + ctx = scope.request.Context() + } + if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); event.Type != transactionType && ok { + traceCtx := event.Contexts["trace"] + traceCtx["trace_id"] = traceID.String() + traceCtx["span_id"] = spanID.String() + } + } + + if event.User.IsEmpty() { + event.User = scope.user + } + + if len(event.Fingerprint) == 0 { + event.Fingerprint = append(event.Fingerprint, scope.fingerprint...) + } + + if scope.level != "" { + event.Level = scope.level + } + + if event.Request == nil && scope.request != nil { + event.Request = newRequest(scope.request, client) + // NOTE: The SDK does not attempt to send partial request body data. + // + // The reason being that Sentry's ingest pipeline and UI are optimized + // to show structured data. Additionally, tooling around PII scrubbing + // relies on structured data; truncated request bodies would create + // invalid payloads that are more prone to leaking PII data. + // + // Users can still send more data along their events if they want to, + // for example using Event.Contexts. + dc := client.GetDataCollection() + if scope.requestBody != nil && !scope.requestBody.Overflow() && dc.CollectHTTPBody(BodyIncomingRequest) { + event.Request.Data = dc.FilterHTTPBody(scope.requestBody.Bytes(), scope.request.Header.Get("Content-Type")) + } + } + + for _, processor := range scope.eventProcessors { + id := event.EventID + category := event.toCategory() + spanCountBefore := event.GetSpanCount() + event = processor(event, hint) + if event == nil { + debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id) + if client != nil { + client.reportRecorder.RecordOne(report.ReasonEventProcessor, category) + if category == ratelimit.CategoryTransaction { + client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore)) + } + } + return nil + } + if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 { + if client != nil { + client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans)) + } + } + } + + return event +} + +// cloneContext returns a new context with keys and values copied from the passed one. +// +// Note: a new Context (map) is returned, but the function does NOT do +// a proper deep copy: if some context values are pointer types (e.g. maps), +// they won't be properly copied. +func cloneContext(c Context) Context { + res := make(Context, len(c)) + for k, v := range c { + res[k] = v + } + return res +} + +func (scope *Scope) populateAttrs(attrs map[string]attribute.Value) { + if scope == nil { + return + } + + scope.mu.RLock() + defer scope.mu.RUnlock() + + // Add user-related attributes + if !scope.user.IsEmpty() { + if scope.user.ID != "" { + attrs["user.id"] = attribute.StringValue(scope.user.ID) + } + if scope.user.Name != "" { + attrs["user.name"] = attribute.StringValue(scope.user.Name) + } + if scope.user.Email != "" { + attrs["user.email"] = attribute.StringValue(scope.user.Email) + } + } + + for k, v := range scope.attributes { + attrs[k] = v + } +} + +// hubFromContexts is a helper to return the first hub found in the given contexts. +func hubFromContexts(ctxs ...context.Context) *Hub { + for _, ctx := range ctxs { + if ctx == nil { + continue + } + if hub := GetHubFromContext(ctx); hub != nil { + return hub + } + } + return nil +} + +// resolveTrace resolves trace ID and span ID from the given scope and contexts. +// +// The resolution order follows a most-specific-to-least-specific pattern: +// 1. If an external trace resolver was registered (eg. OTel), we prioritise trace context +// information from that +// 2. Check for span directly in contexts (SpanFromContext) - this is the most specific +// source as it represents a span explicitly attached to the current operation's context +// 3. Check scope's span - provides access to span set on the hub's scope +// 4. Fall back to scope's propagation context trace ID +// +// This ordering ensures we always use the most contextually relevant tracing information. +// For example, if a specific span is active for an operation, we use that span's trace/span IDs +// rather than accidentally using a different span that might be set on the hub's scope. +func resolveTrace(scope *Scope, client *Client, ctxs ...context.Context) (traceID TraceID, spanID SpanID) { + var span *Span + + for _, ctx := range ctxs { + if ctx == nil { + continue + } + if client != nil { + if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok { + return traceID, spanID + } + } + if span = SpanFromContext(ctx); span != nil { + break + } + } + + if scope != nil { + scope.mu.RLock() + if span == nil { + span = scope.span + } + if span != nil { + traceID = span.TraceID + spanID = span.SpanID + } else { + traceID = scope.propagationContext.TraceID + } + scope.mu.RUnlock() + } + + return traceID, spanID +} diff --git a/vendor/github.com/getsentry/sentry-go/sentry.go b/vendor/github.com/getsentry/sentry-go/sentry.go new file mode 100644 index 0000000..0faa11e --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/sentry.go @@ -0,0 +1,152 @@ +package sentry + +import ( + "context" + "time" +) + +// The version of the SDK. +const SDKVersion = "0.49.0" + +// apiVersion is the minimum version of the Sentry API compatible with the +// sentry-go SDK. +const apiVersion = "7" + +// DefaultFlushTimeout is the default timeout used for flushing events. +const DefaultFlushTimeout = 2 * time.Second + +// Init initializes the SDK with options. The returned error is non-nil if +// options is invalid, for instance if a malformed DSN is provided. +func Init(options ClientOptions) error { + hub := CurrentHub() + client, err := NewClient(options) + if err != nil { + return err + } + hub.BindClient(client) + return nil +} + +// AddBreadcrumb records a new breadcrumb. +// +// The total number of breadcrumbs that can be recorded are limited by the +// configuration on the client. +func AddBreadcrumb(breadcrumb *Breadcrumb) { + hub := CurrentHub() + hub.AddBreadcrumb(breadcrumb, nil) +} + +// CaptureMessage captures an arbitrary message. +func CaptureMessage(message string) *EventID { + hub := CurrentHub() + return hub.CaptureMessage(message) +} + +// CaptureException captures an error. +func CaptureException(exception error) *EventID { + hub := CurrentHub() + return hub.CaptureException(exception) +} + +// CaptureCheckIn captures a (cron) monitor check-in. +func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID { + hub := CurrentHub() + return hub.CaptureCheckIn(checkIn, monitorConfig) +} + +// CaptureEvent captures an event on the currently active client if any. +// +// The event must already be assembled. Typically code would instead use +// the utility methods like CaptureException. The return value is the +// event ID. In case Sentry is disabled or event was dropped, the return value will be nil. +func CaptureEvent(event *Event) *EventID { + hub := CurrentHub() + return hub.CaptureEvent(event) +} + +// Recover captures a panic. +func Recover() *EventID { + if err := recover(); err != nil { + hub := CurrentHub() + return hub.Recover(err) + } + return nil +} + +// RecoverWithContext captures a panic and passes relevant context object. +func RecoverWithContext(ctx context.Context) *EventID { + err := recover() + if err == nil { + return nil + } + + hub := GetHubFromContext(ctx) + if hub == nil { + hub = CurrentHub() + } + + return hub.RecoverWithContext(ctx, err) +} + +// WithScope is a shorthand for CurrentHub().WithScope. +func WithScope(f func(scope *Scope)) { + hub := CurrentHub() + hub.WithScope(f) +} + +// ConfigureScope is a shorthand for CurrentHub().ConfigureScope. +func ConfigureScope(f func(scope *Scope)) { + hub := CurrentHub() + hub.ConfigureScope(f) +} + +// PushScope is a shorthand for CurrentHub().PushScope. +func PushScope() *Scope { + hub := CurrentHub() + return hub.PushScope() +} + +// PopScope is a shorthand for CurrentHub().PopScope. +func PopScope() { + hub := CurrentHub() + hub.PopScope() +} + +// Flush waits until the underlying Transport sends any buffered events to the +// Sentry server, blocking for at most the given timeout. It returns false if +// the timeout was reached. In that case, some events may not have been sent. +// +// Flush should be called before terminating the program to avoid +// unintentionally dropping events. +// +// Do not call Flush indiscriminately after every call to CaptureEvent, +// CaptureException or CaptureMessage. Instead, to have the SDK send events over +// the network synchronously, configure it to use the HTTPSyncTransport in the +// call to Init. +func Flush(timeout time.Duration) bool { + hub := CurrentHub() + return hub.Flush(timeout) +} + +// FlushWithContext waits until the underlying Transport sends any buffered events +// to the Sentry server, blocking for at most the duration specified by the context. +// It returns false if the context is canceled before the events are sent. In such a case, +// some events may not be delivered. +// +// FlushWithContext should be called before terminating the program to ensure no +// events are unintentionally dropped. +// +// Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent, +// CaptureException, or CaptureMessage. To send events synchronously over the network, +// configure the SDK to use HTTPSyncTransport during initialization with Init. + +func FlushWithContext(ctx context.Context) bool { + hub := CurrentHub() + return hub.FlushWithContext(ctx) +} + +// LastEventID returns an ID of last captured event. +func LastEventID() EventID { + hub := CurrentHub() + return hub.LastEventID() +} diff --git a/vendor/github.com/getsentry/sentry-go/span_recorder.go b/vendor/github.com/getsentry/sentry-go/span_recorder.go new file mode 100644 index 0000000..ba04101 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/span_recorder.go @@ -0,0 +1,58 @@ +package sentry + +import ( + "sync" + + "github.com/getsentry/sentry-go/internal/debuglog" +) + +// A spanRecorder stores a span tree that makes up a transaction. Safe for +// concurrent use. It is okay to add child spans from multiple goroutines. +type spanRecorder struct { + mu sync.Mutex + spans []*Span + overflowOnce sync.Once +} + +// record stores a span. The first stored span is assumed to be the root of a +// span tree. +func (r *spanRecorder) record(s *Span) { + maxSpans := defaultMaxSpans + if client := CurrentHub().Client(); client != nil { + maxSpans = client.options.MaxSpans + } + r.mu.Lock() + defer r.mu.Unlock() + if len(r.spans) >= maxSpans { + r.overflowOnce.Do(func() { + root := r.spans[0] + debuglog.Printf("Too many spans: dropping spans from transaction with TraceID=%s SpanID=%s limit=%d", + root.TraceID, root.SpanID, maxSpans) + }) + // TODO(tracing): mark the transaction event in some way to + // communicate that spans were dropped. + return + } + r.spans = append(r.spans, s) +} + +// root returns the first recorded span. Returns nil if none have been recorded. +func (r *spanRecorder) root() *Span { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.spans) == 0 { + return nil + } + return r.spans[0] +} + +// children returns a list of all recorded spans, except the root. Returns nil +// if there are no children. +func (r *spanRecorder) children() []*Span { + r.mu.Lock() + defer r.mu.Unlock() + if len(r.spans) < 2 { + return nil + } + return r.spans[1:] +} diff --git a/vendor/github.com/getsentry/sentry-go/stacktrace.go b/vendor/github.com/getsentry/sentry-go/stacktrace.go new file mode 100644 index 0000000..405599a --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/stacktrace.go @@ -0,0 +1,423 @@ +package sentry + +import ( + "go/build" + "reflect" + "runtime" + "slices" + "strings" +) + +const unknown string = "unknown" + +// The module download is split into two parts: downloading the go.mod and downloading the actual code. +// If you have dependencies only needed for tests, then they will show up in your go.mod, +// and go get will download their go.mods, but it will not download their code. +// The test-only dependencies get downloaded only when you need it, such as the first time you run go test. +// +// https://github.com/golang/go/issues/26913#issuecomment-411976222 + +// Stacktrace holds information about the frames of the stack. +type Stacktrace struct { + Frames []Frame `json:"frames,omitempty"` + FramesOmitted []uint `json:"frames_omitted,omitempty"` +} + +// NewStacktrace creates a stacktrace using runtime.Callers. +func NewStacktrace() *Stacktrace { + pcs := make([]uintptr, 100) + n := runtime.Callers(1, pcs) + + if n == 0 { + return nil + } + + runtimeFrames := extractFrames(pcs[:n]) + runtimeFrames = trimPanicFrames(runtimeFrames) + frames := createFrames(runtimeFrames) + + stacktrace := Stacktrace{ + Frames: frames, + } + + return &stacktrace +} + +// TODO: Make it configurable so that anyone can provide their own implementation? +// Use of reflection allows us to not have a hard dependency on any given +// package, so we don't have to import it. + +// ExtractStacktrace creates a new Stacktrace based on the given error. +func ExtractStacktrace(err error) *Stacktrace { + method := extractReflectedStacktraceMethod(err) + + var pcs []uintptr + + if method.IsValid() { + pcs = extractPcs(method) + } else { + pcs = extractXErrorsPC(err) + } + + if len(pcs) == 0 { + return nil + } + + runtimeFrames := extractFrames(pcs) + frames := createFrames(runtimeFrames) + + stacktrace := Stacktrace{ + Frames: frames, + } + + return &stacktrace +} + +func extractReflectedStacktraceMethod(err error) reflect.Value { + errValue := reflect.ValueOf(err) + + // https://github.com/go-errors/errors + methodStackFrames := errValue.MethodByName("StackFrames") + if methodStackFrames.IsValid() { + return methodStackFrames + } + + // https://github.com/pkg/errors + methodStackTrace := errValue.MethodByName("StackTrace") + if methodStackTrace.IsValid() { + return methodStackTrace + } + + // https://github.com/pingcap/errors + methodGetStackTracer := errValue.MethodByName("GetStackTracer") + if methodGetStackTracer.IsValid() { + stacktracer := methodGetStackTracer.Call(nil)[0] + stacktracerStackTrace := reflect.ValueOf(stacktracer).MethodByName("StackTrace") + + if stacktracerStackTrace.IsValid() { + return stacktracerStackTrace + } + } + + return reflect.Value{} +} + +func extractPcs(method reflect.Value) []uintptr { + var pcs []uintptr + + stacktrace := method.Call(nil)[0] + + if stacktrace.Kind() != reflect.Slice { + return nil + } + + for i := 0; i < stacktrace.Len(); i++ { + pc := stacktrace.Index(i) + + switch pc.Kind() { + case reflect.Uintptr: + pcs = append(pcs, uintptr(pc.Uint())) + case reflect.Struct: + for _, fieldName := range []string{"ProgramCounter", "PC"} { + field := pc.FieldByName(fieldName) + if !field.IsValid() { + continue + } + if field.Kind() == reflect.Uintptr { + pcs = append(pcs, uintptr(field.Uint())) + break + } + } + } + } + + return pcs +} + +// extractXErrorsPC extracts program counters from error values compatible with +// the error types from golang.org/x/xerrors. +// +// It returns nil if err is not compatible with errors from that package or if +// no program counters are stored in err. +func extractXErrorsPC(err error) []uintptr { + // This implementation uses the reflect package to avoid a hard dependency + // on third-party packages. + + // We don't know if err matches the expected type. For simplicity, instead + // of trying to account for all possible ways things can go wrong, some + // assumptions are made and if they are violated the code will panic. We + // recover from any panic and ignore it, returning nil. + //nolint: errcheck + defer func() { recover() }() + + field := reflect.ValueOf(err).Elem().FieldByName("frame") // type Frame struct{ frames [3]uintptr } + field = field.FieldByName("frames") + field = field.Slice(1, field.Len()) // drop first pc pointing to xerrors.New + pc := make([]uintptr, field.Len()) + for i := 0; i < field.Len(); i++ { + pc[i] = uintptr(field.Index(i).Uint()) + } + return pc +} + +// Frame represents a function call and it's metadata. Frames are associated +// with a Stacktrace. +type Frame struct { + Function string `json:"function,omitempty"` + Symbol string `json:"symbol,omitempty"` + // Module is, despite the name, the Sentry protocol equivalent of a Go + // package's import path. + Module string `json:"module,omitempty"` + Filename string `json:"filename,omitempty"` + AbsPath string `json:"abs_path,omitempty"` + Lineno int `json:"lineno,omitempty"` + Colno int `json:"colno,omitempty"` + PreContext []string `json:"pre_context,omitempty"` + ContextLine string `json:"context_line,omitempty"` + PostContext []string `json:"post_context,omitempty"` + InApp bool `json:"in_app"` + Vars map[string]interface{} `json:"vars,omitempty"` + // Package and the below are not used for Go stack trace frames. In + // other platforms it refers to a container where the Module can be + // found. For example, a Java JAR, a .NET Assembly, or a native + // dynamic library. They exists for completeness, allowing the + // construction and reporting of custom event payloads. + Package string `json:"package,omitempty"` + InstructionAddr string `json:"instruction_addr,omitempty"` + AddrMode string `json:"addr_mode,omitempty"` + SymbolAddr string `json:"symbol_addr,omitempty"` + ImageAddr string `json:"image_addr,omitempty"` + Platform string `json:"platform,omitempty"` + StackStart bool `json:"stack_start,omitempty"` +} + +// NewFrame assembles a stacktrace frame out of runtime.Frame. +func NewFrame(f runtime.Frame) Frame { + function := f.Function + var pkg string + + if function != "" { + pkg, function = splitQualifiedFunctionName(function) + } + + return newFrame(pkg, function, f.File, f.Line) +} + +// Like filepath.IsAbs() but doesn't care what platform you run this on. +// I.e. it also recognizies `/path/to/file` when run on Windows. +func isAbsPath(path string) bool { + if len(path) == 0 { + return false + } + + // If the volume name starts with a double slash, this is an absolute path. + if len(path) >= 1 && (path[0] == '/' || path[0] == '\\') { + return true + } + + // Windows absolute path, see https://learn.microsoft.com/en-us/dotnet/standard/io/file-path-formats + if len(path) >= 3 && path[1] == ':' && (path[2] == '/' || path[2] == '\\') { + return true + } + + return false +} + +func newFrame(module string, function string, file string, line int) Frame { + frame := Frame{ + Lineno: line, + Module: module, + Function: function, + } + + switch { + case len(file) == 0: + frame.Filename = unknown + // Leave abspath as the empty string to be omitted when serializing event as JSON. + case isAbsPath(file): + frame.AbsPath = file + // TODO: in the general case, it is not trivial to come up with a + // "project relative" path with the data we have in run time. + // We shall not use filepath.Base because it creates ambiguous paths and + // affects the "Suspect Commits" feature. + // For now, leave relpath empty to be omitted when serializing the event + // as JSON. Improve this later. + default: + // f.File is a relative path. This may happen when the binary is built + // with the -trimpath flag. + frame.Filename = file + // Omit abspath when serializing the event as JSON. + } + + setInAppFrame(&frame) + + return frame +} + +// splitQualifiedFunctionName splits a package path-qualified function name into +// package name and function name. Such qualified names are found in +// runtime.Frame.Function values. +func splitQualifiedFunctionName(name string) (pkg string, fun string) { + pkg = packageName(name) + if len(pkg) > 0 { + fun = name[len(pkg)+1:] + } + return +} + +func extractFrames(pcs []uintptr) []runtime.Frame { + var frames = make([]runtime.Frame, 0, len(pcs)) + callersFrames := runtime.CallersFrames(pcs) + + for { + callerFrame, more := callersFrames.Next() + + frames = append(frames, callerFrame) + + if !more { + break + } + } + + slices.Reverse(frames) + 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 { + if len(frames) == 0 { + return nil + } + + result := make([]Frame, 0, len(frames)) + + for _, frame := range frames { + function := frame.Function + var pkg string + if function != "" { + pkg, function = splitQualifiedFunctionName(function) + } + + if !shouldSkipFrame(pkg) { + result = append(result, newFrame(pkg, function, frame.File, frame.Line)) + } + } + + // Fix issues grouping errors with the new fully qualified function names + // introduced from Go 1.21 + result = cleanupFunctionNamePrefix(result) + return result +} + +// TODO ID: why do we want to do this? +// I'm not aware of other SDKs skipping all Sentry frames, regardless of their position in the stactrace. +// For example, in the .NET SDK, only the first frames are skipped until the call to the SDK. +// As is, this will also hide any intermediate frames in the stack and make debugging issues harder. +func shouldSkipFrame(module string) bool { + // Skip Go internal frames. + if module == "runtime" || module == "testing" { + return true + } + + // Skip Sentry internal frames, except for frames in _test packages (for testing). + if strings.HasPrefix(module, "github.com/getsentry/sentry-go") && + !strings.HasSuffix(module, "_test") { + return true + } + + return false +} + +// On Windows, GOROOT has backslashes, but we want forward slashes. +var goRoot = strings.ReplaceAll(build.Default.GOROOT, "\\", "/") + +func setInAppFrame(frame *Frame) { + frame.InApp = true + if strings.HasPrefix(frame.AbsPath, goRoot) || strings.Contains(frame.Module, "vendor") || + strings.Contains(frame.Module, "third_party") { + frame.InApp = false + } +} + +func callerFunctionName() string { + pcs := make([]uintptr, 1) + runtime.Callers(3, pcs) + callersFrames := runtime.CallersFrames(pcs) + callerFrame, _ := callersFrames.Next() + return baseName(callerFrame.Function) +} + +// packageName returns the package part of the symbol name, or the empty string +// if there is none. +// It replicates https://golang.org/pkg/debug/gosym/#Sym.PackageName, avoiding a +// dependency on debug/gosym. +func packageName(name string) string { + if isCompilerGeneratedSymbol(name) { + return "" + } + + pathend := strings.LastIndex(name, "/") + if pathend < 0 { + pathend = 0 + } + + if i := strings.Index(name[pathend:], "."); i != -1 { + return name[:pathend+i] + } + return "" +} + +// baseName returns the symbol name without the package or receiver name. +// It replicates https://golang.org/pkg/debug/gosym/#Sym.BaseName, avoiding a +// dependency on debug/gosym. +func baseName(name string) string { + if i := strings.LastIndex(name, "."); i != -1 { + return name[i+1:] + } + return name +} + +func isCompilerGeneratedSymbol(name string) bool { + // In versions of Go 1.20 and above a prefix of "type:" and "go:" is a + // compiler-generated symbol that doesn't belong to any package. + // See variable reservedimports in cmd/compile/internal/gc/subr.go + if strings.HasPrefix(name, "go:") || strings.HasPrefix(name, "type:") { + return true + } + return false +} + +// Walk backwards through the results and for the current function name +// remove it's parent function's prefix, leaving only it's actual name. This +// fixes issues grouping errors with the new fully qualified function names +// introduced from Go 1.21. +func cleanupFunctionNamePrefix(f []Frame) []Frame { + for i := len(f) - 1; i > 0; i-- { + name := f[i].Function + parentName := f[i-1].Function + "." + + if !strings.HasPrefix(name, parentName) { + continue + } + + f[i].Function = name[len(parentName):] + } + + return f +} diff --git a/vendor/github.com/getsentry/sentry-go/traces_sampler.go b/vendor/github.com/getsentry/sentry-go/traces_sampler.go new file mode 100644 index 0000000..5775db4 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/traces_sampler.go @@ -0,0 +1,26 @@ +package sentry + +// A SamplingContext is passed to a TracesSampler to determine a sampling +// decision. +// +// TODO(tracing): possibly expand SamplingContext to include custom / +// user-provided data. +type SamplingContext struct { + Span *Span // The current span, always non-nil. + Parent *Span // The local parent span, non-nil only when the parent exists in the same process. + // ParentSampled is the sampling decision of the parent span. + // + // For a remote span, Parent is nil but ParentSampled reflects the upstream decision. + // For a local span, ParentSampled mirrors Parent.Sampled. + ParentSampled Sampled + // ParentSampleRate is the sample rate used by the parent transaction. + ParentSampleRate *float64 +} + +// The TracesSample type is an adapter to allow the use of ordinary +// functions as a TracesSampler. +type TracesSampler func(ctx SamplingContext) float64 + +func (f TracesSampler) Sample(ctx SamplingContext) float64 { + return f(ctx) +} diff --git a/vendor/github.com/getsentry/sentry-go/tracing.go b/vendor/github.com/getsentry/sentry-go/tracing.go new file mode 100644 index 0000000..475a8a4 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/tracing.go @@ -0,0 +1,1234 @@ +package sentry + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "maps" + "net/http" + "regexp" + "strconv" + "strings" + "sync" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/report" +) + +const ( + SentryTraceHeader = "sentry-trace" + SentryBaggageHeader = "baggage" + TraceparentHeader = "traceparent" +) + +// SpanOrigin indicates what created a trace or a span. See: https://develop.sentry.dev/sdk/performance/trace-origin/ +type SpanOrigin string + +const ( + SpanOriginManual = "manual" + SpanOriginEcho = "auto.http.echo" + SpanOriginFastHTTP = "auto.http.fasthttp" + SpanOriginFiber = "auto.http.fiber" + SpanOriginGin = "auto.http.gin" + SpanOriginStdLib = "auto.http.stdlib" + SpanOriginIris = "auto.http.iris" + SpanOriginNegroni = "auto.http.negroni" + SpanOriginGrpc = "auto.rpc.grpc" +) + +// A Span is the building block of a Sentry transaction. Spans build up a tree +// structure of timed operations. The span tree makes up a transaction event +// that is sent to Sentry when the root span is finished. +// +// Spans must be started with either StartSpan or Span.StartChild. +type Span struct { //nolint: maligned // prefer readability over optimal memory layout (see note below *) + TraceID TraceID `json:"trace_id"` + SpanID SpanID `json:"span_id"` + ParentSpanID SpanID `json:"parent_span_id,omitzero"` + Name string `json:"name,omitempty"` + Op string `json:"op,omitempty"` + Description string `json:"description,omitempty"` + Status SpanStatus `json:"status,omitempty"` + Tags map[string]string `json:"tags,omitempty"` + StartTime time.Time `json:"start_timestamp,omitzero"` + EndTime time.Time `json:"timestamp,omitzero"` + Data map[string]interface{} `json:"data,omitempty"` + Sampled Sampled `json:"-"` + Source TransactionSource `json:"-"` + Origin SpanOrigin `json:"origin,omitempty"` + + // mu protects concurrent writes to map fields + mu sync.RWMutex + // sample rate the span was sampled with. + sampleRate float64 + // ctx is the context where the span was started. Always non-nil. + ctx context.Context + // Dynamic Sampling context + dynamicSamplingContext DynamicSamplingContext + // parent refers to the immediate local parent span. A remote parent span is + // only referenced by setting ParentSpanID. + parent *Span + // recorder stores all spans in a transaction. Guaranteed to be non-nil. + recorder *spanRecorder + // span context, can only be set on transactions + contexts map[string]Context + // a Once instance to make sure that Finish() is only called once. + finishOnce sync.Once + // explicitSampled is a flag for configuring sampling by using `WithSpanSampled` option. + explicitSampled Sampled + // Pre-serialized copies of mutable fields, set by MakeSerializationSafe. + serializedTags json.RawMessage + serializedData json.RawMessage + serializationSafe bool +} + +// TraceParentContext describes the context of a (remote) parent span. +// +// The context is normally extracted from a received "sentry-trace" header and +// used to initialize a new transaction. +// +// Note: the name might be not the best one. It was taken mostly to stay aligned +// with other SDKs, and it alludes to W3C "traceparent" header (https://www.w3.org/TR/trace-context/), +// which serves a similar purpose to "sentry-trace". We should eventually consider +// making this type internal-only and give it a better name. +type TraceParentContext struct { + TraceID TraceID + ParentSpanID SpanID + Sampled Sampled +} + +// (*) Note on maligned: +// +// We prefer readability over optimal memory layout. If we ever decide to +// reorder fields, we can use a tool: +// +// go run honnef.co/go/tools/cmd/structlayout -json . Span | go run honnef.co/go/tools/cmd/structlayout-optimize +// +// Other structs would deserve reordering as well, for example Event. + +// TODO: make Span.Tags and Span.Data opaque types (struct{unexported []slice}). +// An opaque type allows us to add methods and make it more convenient to use +// than maps, because maps require careful nil checks to use properly or rely on +// explicit initialization for every span, even when there might be no +// tags/data. For Span.Data, must gracefully handle values that cannot be +// marshaled into JSON (see transport.go:getRequestBodyFromEvent). + +// StartSpan starts a new span to describe an operation. The new span will be a +// child of the last span stored in ctx, if any. +// +// One or more options can be used to modify the span properties. Typically one +// option as a function literal is enough. Combining multiple options can be +// useful to define and reuse specific properties with named functions. +// +// Caller should call the Finish method on the span to mark its end. Finishing a +// root span sends the span and all of its children, recursively, as a +// transaction to Sentry. +func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Span { + parent, hasParent := ctx.Value(spanContextKey{}).(*Span) + var span Span + span = Span{ + // defaults + Op: operation, + StartTime: time.Now(), + Sampled: SampledUndefined, + + ctx: context.WithValue(ctx, spanContextKey{}, &span), + parent: parent, + } + + _, err := rand.Read(span.SpanID[:]) + if err != nil { + panic(err) + } + + if hasParent { + span.TraceID = parent.TraceID + span.ParentSpanID = parent.SpanID + span.Origin = parent.Origin + } else { + // Only set the Source if this is a transaction + span.Source = SourceCustom + span.Origin = SpanOriginManual + + // Implementation note: + // + // While math/rand is ~2x faster than crypto/rand (exact + // difference depends on hardware / OS), crypto/rand is probably + // fast enough and a safer choice. + // + // For reference, OpenTelemetry [1] uses crypto/rand to seed + // math/rand. AFAICT this approach does not preserve the + // properties from crypto/rand that make it suitable for + // cryptography. While it might be debatable whether those + // properties are important for us here, again, we're taking the + // safer path. + // + // See [2a] & [2b] for a discussion of some of the properties we + // obtain by using crypto/rand and [3a] & [3b] for why we avoid + // math/rand. + // + // Because the math/rand seed has only 64 bits (int64), if the + // first thing we do after seeding an RNG is to read in a random + // TraceID, there are only 2^64 possible values. Compared to + // UUID v4 that have 122 random bits, there is a much greater + // chance of collision [4a] & [4b]. + // + // [1]: https://github.com/open-telemetry/opentelemetry-go/blob/958041ddf619a128/sdk/trace/trace.go#L25-L31 + // [2a]: https://security.stackexchange.com/q/120352/246345 + // [2b]: https://security.stackexchange.com/a/120365/246345 + // [3a]: https://github.com/golang/go/issues/11871#issuecomment-126333686 + // [3b]: https://github.com/golang/go/issues/11871#issuecomment-126357889 + // [4a]: https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions + // [4b]: https://www.wolframalpha.com/input/?i=sqrt%282*2%5E64*ln%281%2F%281-0.5%29%29%29 + _, err := rand.Read(span.TraceID[:]) + if err != nil { + panic(err) + } + } + + // Apply options to override defaults. + for _, option := range options { + option(&span) + } + + span.Sampled = span.sample() + + span.recorder = &spanRecorder{} + if hasParent { + span.recorder = parent.spanRecorder() + } + + span.recorder.record(&span) + + clientOptions := span.clientOptions() + if clientOptions.EnableTracing { + hub := hubFromContext(ctx) + hub.Scope().SetSpan(&span) + } + + return &span +} + +// Finish sets the span's end time, unless already set. If the span is the root +// of a span tree, Finish sends the span tree to Sentry as a transaction. +// +// The logic is executed at most once per span, so that (incorrectly) calling it twice +// never double sends to Sentry. +func (s *Span) Finish() { + s.finishOnce.Do(s.doFinish) +} + +// Context returns the context containing the span. +func (s *Span) Context() context.Context { return s.ctx } + +// StartChild starts a new child span. +// +// The call span.StartChild(operation, options...) is a shortcut for +// StartSpan(span.Context(), operation, options...). +func (s *Span) StartChild(operation string, options ...SpanOption) *Span { + return StartSpan(s.Context(), operation, options...) +} + +// makeSerializationSafe pre-serializes user mutable fields. +func (s *Span) makeSerializationSafe() { + s.mu.Lock() + defer s.mu.Unlock() + + if len(s.Tags) > 0 { + if b, err := json.Marshal(s.Tags); err == nil { + s.serializedTags = b + } + } + if len(s.Data) > 0 { + if b, err := json.Marshal(s.Data); err == nil { + s.serializedData = b + } + } + + s.serializationSafe = true +} + +// MarshalJSON emits the span using pre-serialized fields if available. +func (s *Span) MarshalJSON() ([]byte, error) { + s.mu.RLock() + serializationSafe := s.serializationSafe + serializedTags := s.serializedTags + serializedData := s.serializedData + s.mu.RUnlock() + + if !serializationSafe { + type span Span + return json.Marshal((*span)(s)) + } + + type span Span + type safeSpan struct { + *span + Tags json.RawMessage `json:"tags,omitempty"` + Data json.RawMessage `json:"data,omitempty"` + } + return json.Marshal(safeSpan{ + span: (*span)(s), + Tags: serializedTags, + Data: serializedData, + }) +} + +// SetTag sets a tag on the span. It is recommended to use SetTag instead of +// accessing the tags map directly as SetTag takes care of initializing the map +// when necessary. +func (s *Span) SetTag(name, value string) { + s.mu.Lock() + defer s.mu.Unlock() + + if s.Tags == nil { + s.Tags = make(map[string]string) + } + s.Tags[name] = value +} + +// SetData sets a data on the span. It is recommended to use SetData instead of +// accessing the data map directly as SetData takes care of initializing the map +// when necessary. +func (s *Span) SetData(name string, value interface{}) { + if value == nil { + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + if s.Data == nil { + s.Data = make(map[string]interface{}) + } + s.Data[name] = value +} + +// SetContext sets a context on the span. It is recommended to use SetContext instead of +// accessing the contexts map directly as SetContext takes care of initializing the map +// when necessary. +func (s *Span) SetContext(key string, value Context) { + s.mu.Lock() + defer s.mu.Unlock() + + if s.contexts == nil { + s.contexts = make(map[string]Context) + } + s.contexts[key] = value +} + +// IsTransaction checks if the given span is a transaction. +func (s *Span) IsTransaction() bool { + return s.parent == nil +} + +// GetTransaction returns the transaction that contains this span. +// +// For transaction spans it returns itself. For spans that were created manually +// the method returns "nil". +func (s *Span) GetTransaction() *Span { + spanRecorder := s.spanRecorder() + if spanRecorder == nil { + // This probably means that the Span was created manually (not via + // StartTransaction/StartSpan or StartChild). + // Return "nil" to indicate that it's not a normal situation. + return nil + } + recorderRoot := spanRecorder.root() + if recorderRoot == nil { + // Same as above: manually created Span. + return nil + } + return recorderRoot +} + +// TODO(tracing): maybe add shortcuts to get/set transaction name. Right now the +// transaction name is in the Scope, as it has existed there historically, prior +// to tracing. +// +// See Scope.Transaction() and Scope.SetTransaction(). +// +// func (s *Span) TransactionName() string +// func (s *Span) SetTransactionName(name string) + +// ToSentryTrace returns the serialized TraceParentContext from a transaction/span. +// Use this function to propagate the TraceParentContext to a downstream SDK, +// either as the value of the "sentry-trace" HTTP header, or as an html "sentry-trace" meta tag. +func (s *Span) ToSentryTrace() string { + // TODO(tracing): add instrumentation for outgoing HTTP requests using + // ToSentryTrace. + var b strings.Builder + fmt.Fprintf(&b, "%s-%s", s.TraceID.Hex(), s.SpanID.Hex()) + switch s.Sampled { + case SampledTrue: + b.WriteString("-1") + case SampledFalse: + b.WriteString("-0") + } + return b.String() +} + +// ToTraceparent returns the W3C traceparent header value for the span. +func (s *Span) ToTraceparent() string { + traceFlags := "00" + if s.Sampled == SampledTrue { + traceFlags = "01" + } + return fmt.Sprintf("00-%s-%s-%s", s.TraceID.String(), s.SpanID.String(), traceFlags) +} + +// ToBaggage returns the serialized DynamicSamplingContext from a transaction. +// Use this function to propagate the DynamicSamplingContext to a downstream SDK, +// either as the value of the "baggage" HTTP header, or as an html "baggage" meta tag. +func (s *Span) ToBaggage() string { + t := s.GetTransaction() + if t == nil { + return "" + } + + // In case there is currently no frozen DynamicSamplingContext attached to the transaction, + // create one from the properties of the transaction. + if !s.dynamicSamplingContext.IsFrozen() { + // This will return a frozen DynamicSamplingContext. + if dsc := DynamicSamplingContextFromTransaction(t); dsc.HasEntries() { + t.dynamicSamplingContext = dsc + } + } + + return t.dynamicSamplingContext.String() +} + +// SetDynamicSamplingContext sets the given dynamic sampling context on the +// current transaction. +func (s *Span) SetDynamicSamplingContext(dsc DynamicSamplingContext) { + if s.IsTransaction() { + s.dynamicSamplingContext = dsc + } +} + +// shouldIgnoreStatusCode checks if the transaction should be ignored based on HTTP status code. +func (s *Span) shouldIgnoreStatusCode() bool { + if !s.IsTransaction() { + return false + } + + ignoreStatusCodes := s.clientOptions().TraceIgnoreStatusCodes + if len(ignoreStatusCodes) == 0 { + return false + } + + s.mu.Lock() + statusCodeData, exists := s.Data["http.response.status_code"] + s.mu.Unlock() + + if !exists { + return false + } + + statusCode, ok := statusCodeData.(int) + if !ok { + return false + } + + for _, ignoredRange := range ignoreStatusCodes { + switch len(ignoredRange) { + case 1: + // Single status code + if statusCode == ignoredRange[0] { + s.mu.Lock() + s.Sampled = SampledFalse + s.mu.Unlock() + debuglog.Printf("dropping transaction with status code %v: found in TraceIgnoreStatusCodes", statusCode) + return true + } + case 2: + // Range of status codes [min, max] + if ignoredRange[0] <= statusCode && statusCode <= ignoredRange[1] { + s.mu.Lock() + s.Sampled = SampledFalse + s.mu.Unlock() + debuglog.Printf("dropping transaction with status code %v: found in TraceIgnoreStatusCodes range [%d, %d]", statusCode, ignoredRange[0], ignoredRange[1]) + return true + } + default: + debuglog.Printf("incorrect TraceIgnoreStatusCodes format: %v", ignoredRange) + } + } + + return false +} + +// doFinish runs the actual Span.Finish() logic. +func (s *Span) doFinish() { + if s.EndTime.IsZero() { + s.EndTime = monotonicTimeSince(s.StartTime) + } + + hub := hubFromContext(s.ctx) + if !s.IsTransaction() { + if s.parent != nil { + hub.Scope().SetSpan(s.parent) + } + } + + if s.shouldIgnoreStatusCode() { + return + } + + if !s.Sampled.Bool() { + c := hub.Client() + if c != nil { + if !s.IsTransaction() { + // we count the sampled spans from the transaction root. it is guaranteed that the whole transaction + // would be sampled + return + } + children := s.recorder.children() + c.reportRecorder.RecordOne(report.ReasonSampleRate, ratelimit.CategoryTransaction) + c.reportRecorder.Record(report.ReasonSampleRate, ratelimit.CategorySpan, int64(len(children)+1)) + } + return + } + event := s.toEvent() + if event == nil { + return + } + + // TODO(tracing): add breadcrumbs + // (see https://github.com/getsentry/sentry-python/blob/f6f3525f8812f609/sentry_sdk/tracing.py#L372) + + hub.CaptureEvent(event) +} + +// sentryTracePattern matches either +// +// TRACE_ID - SPAN_ID +// [[:xdigit:]]{32}-[[:xdigit:]]{16} +// +// or +// +// TRACE_ID - SPAN_ID - SAMPLED +// [[:xdigit:]]{32}-[[:xdigit:]]{16}-[01] +var sentryTracePattern = regexp.MustCompile(`^([[:xdigit:]]{32})-([[:xdigit:]]{16})(?:-([01]))?$`) + +// updateFromSentryTrace parses a sentry-trace HTTP header (as returned by +// ToSentryTrace) and updates fields of the span. If the header cannot be +// recognized as valid, the span is left unchanged. The returned value indicates +// whether the span was updated. +func (s *Span) updateFromSentryTrace(header []byte) (updated bool) { + m := sentryTracePattern.FindSubmatch(header) + if m == nil { + // no match + return false + } + _, _ = hex.Decode(s.TraceID[:], m[1]) + _, _ = hex.Decode(s.ParentSpanID[:], m[2]) + if len(m[3]) != 0 { + switch m[3][0] { + case '0': + s.Sampled = SampledFalse + case '1': + s.Sampled = SampledTrue + } + } + return true +} + +func (s *Span) updateFromBaggage(header []byte) { + if s.IsTransaction() { + dsc, err := DynamicSamplingContextFromHeader(header) + if err != nil { + return + } + + s.dynamicSamplingContext = dsc + } +} + +func (s *Span) clientOptions() *ClientOptions { + client := hubFromContext(s.ctx).Client() + if client != nil { + return &client.options + } + return &ClientOptions{} +} + +func (s *Span) sample() Sampled { + clientOptions := s.clientOptions() + // https://develop.sentry.dev/sdk/performance/#sampling + // #1 tracing is not enabled. + if !clientOptions.EnableTracing { + debuglog.Printf("Dropping transaction: EnableTracing is set to %t", clientOptions.EnableTracing) + s.sampleRate = 0.0 + return SampledFalse + } + + // #2 explicit sampling decision via StartSpan/StartTransaction options. + if s.explicitSampled != SampledUndefined { + debuglog.Printf("Using explicit sampling decision from StartSpan/StartTransaction: %v", s.explicitSampled) + switch s.explicitSampled { + case SampledTrue: + s.sampleRate = 1.0 + case SampledFalse: + s.sampleRate = 0.0 + } + return s.explicitSampled + } + + // Variant for non-transaction spans: they inherit the parent decision. + // Note: non-transaction should always have a parent, but we check both + // conditions anyway -- the first for semantic meaning, the second to + // avoid a nil pointer dereference. + if !s.IsTransaction() && s.parent != nil { + return s.parent.Sampled + } + + // #3 use TracesSampler from ClientOptions. + sampler := clientOptions.TracesSampler + parentSampled := SampledUndefined + if s.parent != nil { + parentSampled = s.parent.Sampled + } else if s.ParentSpanID != zeroSpanID { + parentSampled = s.Sampled + } + var parentSampleRate *float64 + if rateStr, ok := s.dynamicSamplingContext.Entries["sample_rate"]; ok { + if rate, err := strconv.ParseFloat(rateStr, 64); err == nil { + parentSampleRate = &rate + } + } + samplingContext := SamplingContext{ + Span: s, + Parent: s.parent, + ParentSampled: parentSampled, + ParentSampleRate: parentSampleRate, + } + + if sampler != nil { + tracesSamplerSampleRate := sampler.Sample(samplingContext) + s.sampleRate = tracesSamplerSampleRate + // tracesSampler can update the sample_rate on frozen DSC + if s.dynamicSamplingContext.HasEntries() { + s.dynamicSamplingContext.Entries["sample_rate"] = strconv.FormatFloat(tracesSamplerSampleRate, 'f', -1, 64) + } + if tracesSamplerSampleRate < 0.0 || tracesSamplerSampleRate > 1.0 { + debuglog.Printf("Dropping transaction: Returned TracesSampler rate is out of range [0.0, 1.0]: %f", tracesSamplerSampleRate) + return SampledFalse + } + if tracesSamplerSampleRate == 0.0 { + debuglog.Printf("Dropping transaction: Returned TracesSampler rate is: %f", tracesSamplerSampleRate) + return SampledFalse + } + + if rng.Float64() < tracesSamplerSampleRate { + return SampledTrue + } + debuglog.Printf("Dropping transaction: TracesSampler returned rate: %f", tracesSamplerSampleRate) + + return SampledFalse + } + + // #4 inherit parent decision. + if s.Sampled != SampledUndefined { + debuglog.Printf("Using sampling decision from parent: %v", s.Sampled) + switch s.Sampled { + case SampledTrue: + s.sampleRate = 1.0 + case SampledFalse: + s.sampleRate = 0.0 + } + return s.Sampled + } + + // #5 use TracesSampleRate from ClientOptions. + sampleRate := clientOptions.TracesSampleRate + s.sampleRate = sampleRate + // tracesSampleRate can update the sample_rate on frozen DSC + if s.dynamicSamplingContext.HasEntries() { + s.dynamicSamplingContext.Entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64) + } + if sampleRate < 0.0 || sampleRate > 1.0 { + debuglog.Printf("Dropping transaction: TracesSampleRate out of range [0.0, 1.0]: %f", sampleRate) + return SampledFalse + } + if sampleRate == 0.0 { + debuglog.Printf("Dropping transaction: TracesSampleRate rate is: %f", sampleRate) + return SampledFalse + } + + if rng.Float64() < sampleRate { + return SampledTrue + } + + return SampledFalse +} + +func (s *Span) toEvent() *Event { + s.mu.Lock() + defer s.mu.Unlock() + + if !s.IsTransaction() { + return nil // only transactions can be transformed into events + } + + children := s.recorder.children() + finished := make([]*Span, 0, len(children)) + for _, child := range children { + if child.EndTime.IsZero() { + debuglog.Printf("Dropped unfinished span: Op=%q TraceID=%s SpanID=%s", child.Op, child.TraceID, child.SpanID) + continue + } + finished = append(finished, child) + } + + // Create and attach a DynamicSamplingContext to the transaction. + // If the DynamicSamplingContext is not frozen at this point, we can assume being head of trace. + if !s.dynamicSamplingContext.IsFrozen() { + s.dynamicSamplingContext = DynamicSamplingContextFromTransaction(s) + } + + contexts := make(map[string]Context, len(s.contexts)+1) + for k, v := range s.contexts { + contexts[k] = cloneContext(v) + } + contexts["trace"] = s.traceContextLockFree().Map() + + // Make sure that the transaction source is valid + transactionSource := s.Source + if !transactionSource.isValid() { + transactionSource = SourceCustom + } + + return &Event{ + Type: transactionType, + Transaction: s.Name, + Contexts: contexts, + Tags: maps.Clone(s.Tags), + Timestamp: s.EndTime, + StartTime: s.StartTime, + Spans: finished, + TransactionInfo: &TransactionInfo{ + Source: transactionSource, + }, + sdkMetaData: SDKMetaData{ + dsc: s.dynamicSamplingContext, + }, + } +} + +// traceContext returns a TraceContext snapshot for an active span. +// +// It needs to clone span Data to avoid holding any user mutable state. +func (s *Span) traceContext() *TraceContext { + s.mu.RLock() + defer s.mu.RUnlock() + return &TraceContext{ + TraceID: s.TraceID, + SpanID: s.SpanID, + ParentSpanID: s.ParentSpanID, + Op: s.Op, + Data: maps.Clone(s.Data), + Description: s.Description, + Status: s.Status, + } +} + +// traceContextLockFree is the lock-free variant of traceContext. +// +// This is supposed to be used only when span Finish() was already called. +func (s *Span) traceContextLockFree() *TraceContext { + return &TraceContext{ + TraceID: s.TraceID, + SpanID: s.SpanID, + ParentSpanID: s.ParentSpanID, + Op: s.Op, + Data: s.Data, + Description: s.Description, + Status: s.Status, + } +} + +// spanRecorder stores the span tree. Guaranteed to be non-nil. +func (s *Span) spanRecorder() *spanRecorder { return s.recorder } + +// ParseTraceParentContext parses a sentry-trace header and builds a TraceParentContext from the +// parsed values. If the header was parsed correctly, the second returned argument +// ("valid") will be set to true, otherwise (e.g., empty or malformed header) it will +// be false. +func ParseTraceParentContext(header []byte) (traceParentContext TraceParentContext, valid bool) { + s := Span{} + updated := s.updateFromSentryTrace(header) + if !updated { + return TraceParentContext{}, false + } + return TraceParentContext{ + TraceID: s.TraceID, + ParentSpanID: s.ParentSpanID, + Sampled: s.Sampled, + }, true +} + +// TraceID identifies a trace. +type TraceID [16]byte + +func (id TraceID) Hex() []byte { + b := make([]byte, hex.EncodedLen(len(id))) + hex.Encode(b, id[:]) + return b +} + +func (id TraceID) String() string { + return string(id.Hex()) +} + +func (id TraceID) MarshalText() ([]byte, error) { + return id.Hex(), nil +} + +// SpanID identifies a span. +type SpanID [8]byte + +func (id SpanID) Hex() []byte { + b := make([]byte, hex.EncodedLen(len(id))) + hex.Encode(b, id[:]) + return b +} + +func (id SpanID) String() string { + return string(id.Hex()) +} + +func (id SpanID) MarshalText() ([]byte, error) { + return id.Hex(), nil +} + +// Zero values of TraceID and SpanID used for comparisons. +var ( + zeroTraceID TraceID + zeroSpanID SpanID +) + +// Contains information about how the name of the transaction was determined. +type TransactionSource string + +const ( + SourceCustom TransactionSource = "custom" + SourceURL TransactionSource = "url" + SourceRoute TransactionSource = "route" + SourceView TransactionSource = "view" + SourceComponent TransactionSource = "component" + SourceTask TransactionSource = "task" +) + +// A set of all valid transaction sources. +var allTransactionSources = map[TransactionSource]struct{}{ + SourceCustom: {}, + SourceURL: {}, + SourceRoute: {}, + SourceView: {}, + SourceComponent: {}, + SourceTask: {}, +} + +// isValid returns 'true' if the given transaction source is a valid +// source as recognized by the envelope protocol: +// https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations +func (ts TransactionSource) isValid() bool { + _, found := allTransactionSources[ts] + return found +} + +// SpanStatus is the status of a span. +type SpanStatus uint8 + +// Implementation note: +// +// In Relay (ingestion), the SpanStatus type is an enum used as +// Annotated when embedded in structs, making it effectively +// Option. It means the status is either null or one of the known +// string values. +// +// In Snuba (search), the SpanStatus is stored as an uint8 and defaulted to 2 +// ("unknown") when not set. It means that Discover searches for +// `transaction.status:unknown` return both transactions/spans with status +// `null` or `"unknown"`. Searches for `transaction.status:""` return nothing. +// +// With that in mind, the Go SDK default is SpanStatusUndefined, which is +// null/omitted when serializing to JSON, but integrations may update the status +// automatically based on contextual information. + +const ( + SpanStatusUndefined SpanStatus = iota + SpanStatusOK + SpanStatusCanceled + SpanStatusUnknown + SpanStatusInvalidArgument + SpanStatusDeadlineExceeded + SpanStatusNotFound + SpanStatusAlreadyExists + SpanStatusPermissionDenied + SpanStatusResourceExhausted + SpanStatusFailedPrecondition + SpanStatusAborted + SpanStatusOutOfRange + SpanStatusUnimplemented + SpanStatusInternalError + SpanStatusUnavailable + SpanStatusDataLoss + SpanStatusUnauthenticated + maxSpanStatus +) + +var spanStatuses = [maxSpanStatus]string{ + "", + "ok", + "cancelled", // [sic] + "unknown", + "invalid_argument", + "deadline_exceeded", + "not_found", + "already_exists", + "permission_denied", + "resource_exhausted", + "failed_precondition", + "aborted", + "out_of_range", + "unimplemented", + "internal_error", + "unavailable", + "data_loss", + "unauthenticated", +} + +func (ss SpanStatus) String() string { + if ss >= maxSpanStatus { + return "" + } + return spanStatuses[ss] +} + +func (ss SpanStatus) MarshalJSON() ([]byte, error) { + s := ss.String() + if s == "" { + return []byte("null"), nil + } + return json.Marshal(s) +} + +// A TraceContext carries information about an ongoing trace and is meant to be +// stored in Event.Contexts (as *TraceContext). +type TraceContext struct { + TraceID TraceID `json:"trace_id"` + SpanID SpanID `json:"span_id"` + ParentSpanID SpanID `json:"parent_span_id,omitzero"` + Op string `json:"op,omitempty"` + Description string `json:"description,omitempty"` + Status SpanStatus `json:"status,omitempty"` + Data map[string]interface{} `json:"data,omitempty"` +} + +func (tc TraceContext) Map() map[string]interface{} { + m := map[string]interface{}{ + "trace_id": tc.TraceID, + "span_id": tc.SpanID, + } + + if tc.ParentSpanID != [8]byte{} { + m["parent_span_id"] = tc.ParentSpanID + } + + if tc.Op != "" { + m["op"] = tc.Op + } + + if tc.Description != "" { + m["description"] = tc.Description + } + + if tc.Status > 0 && tc.Status < maxSpanStatus { + m["status"] = tc.Status + } + + if len(tc.Data) > 0 { + m["data"] = tc.Data + } + + return m +} + +// Sampled signifies a sampling decision. +type Sampled int8 + +// The possible trace sampling decisions are: SampledFalse, SampledUndefined +// (default) and SampledTrue. +const ( + SampledFalse Sampled = -1 + SampledUndefined Sampled = 0 + SampledTrue Sampled = 1 +) + +func (s Sampled) String() string { + switch s { + case SampledFalse: + return "SampledFalse" + case SampledUndefined: + return "SampledUndefined" + case SampledTrue: + return "SampledTrue" + default: + return fmt.Sprintf("SampledInvalid(%d)", s) + } +} + +// Bool returns true if the sample decision is SampledTrue, false otherwise. +func (s Sampled) Bool() bool { + return s == SampledTrue +} + +// A SpanOption is a function that can modify the properties of a span. +type SpanOption func(s *Span) + +// WithTransactionName option sets the name of the current transaction. +// +// A span tree has a single transaction name, therefore using this option when +// starting a span affects the span tree as a whole, potentially overwriting a +// name set previously. +func WithTransactionName(name string) SpanOption { + return func(s *Span) { + s.Name = name + } +} + +// WithDescription sets the description of a span. +func WithDescription(description string) SpanOption { + return func(s *Span) { + s.Description = description + } +} + +// WithOpName sets the operation name for a given span. +func WithOpName(name string) SpanOption { + return func(s *Span) { + s.Op = name + } +} + +// WithTransactionSource sets the source of the transaction name. +// +// Note: if the transaction source is not a valid source (as described +// by the spec https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations), +// it will be corrected to "custom" eventually, before the transaction is sent. +func WithTransactionSource(source TransactionSource) SpanOption { + return func(s *Span) { + s.Source = source + } +} + +// WithSpanSampled updates the sampling flag for a given span. +func WithSpanSampled(sampled Sampled) SpanOption { + return func(s *Span) { + s.explicitSampled = sampled + } +} + +// WithSpanOrigin sets the origin of the span. +func WithSpanOrigin(origin SpanOrigin) SpanOption { + return func(s *Span) { + s.Origin = origin + } +} + +// ContinueTrace continues a trace based on traceparent and baggage values. +// If the SDK is configured with tracing enabled, +// this function returns populated SpanOption. +// In any other cases, it populates the propagation context on the scope. +func ContinueTrace(hub *Hub, traceparent, baggage string) SpanOption { + scope := hub.Scope() + propagationContext, _ := PropagationContextFromHeaders(traceparent, baggage) + client := hub.Client() + + if !shouldContinueTrace(client, propagationContext.DynamicSamplingContext) { + propagationContext = NewPropagationContext() + traceparent = "" + baggage = "" + } + + scope.SetPropagationContext(propagationContext) + return ContinueFromHeaders(traceparent, baggage) +} + +// ContinueFromRequest returns a span option that updates the span to continue +// an existing trace. If it cannot detect an existing trace in the request, the +// span will be left unchanged. +// +// ContinueFromRequest is an alias for: +// +// ContinueFromHeaders(r.Header.Get(SentryTraceHeader), r.Header.Get(SentryBaggageHeader)). +func ContinueFromRequest(r *http.Request) SpanOption { + return ContinueFromHeaders(r.Header.Get(SentryTraceHeader), r.Header.Get(SentryBaggageHeader)) +} + +// ContinueFromHeaders returns a span option that updates the span to continue +// an existing TraceID and propagates the Dynamic Sampling context. +func ContinueFromHeaders(trace, baggage string) SpanOption { + return func(s *Span) { + if trace == "" { + return + } + + // Parse baggage first to get org_id for comparison + var dsc DynamicSamplingContext + if baggage != "" { + parsed, err := DynamicSamplingContextFromHeader([]byte(baggage)) + if err == nil { + dsc = parsed + } + } + + client := hubFromContext(s.ctx).Client() + if !shouldContinueTrace(client, dsc) { + return // leave span unchanged → behaves as head of trace + } + + s.updateFromSentryTrace([]byte(trace)) + + if baggage != "" { + s.updateFromBaggage([]byte(baggage)) + } + + // In case a sentry-trace header is present but there are no sentry-related + // values in the baggage, create an empty, frozen DynamicSamplingContext. + if !s.dynamicSamplingContext.HasEntries() { + s.dynamicSamplingContext = DynamicSamplingContext{ + Frozen: true, + } + } + } +} + +// ContinueFromTrace returns a span option that updates the span to continue +// an existing TraceID. +func ContinueFromTrace(trace string) SpanOption { + return func(s *Span) { + if trace == "" { + return + } + client := hubFromContext(s.ctx).Client() + if !shouldContinueTrace(client, DynamicSamplingContext{}) { + return + } + s.updateFromSentryTrace([]byte(trace)) + } +} + +// spanContextKey is used to store span values in contexts. +type spanContextKey struct{} + +// TransactionFromContext returns the root span of the current transaction. It +// returns nil if no transaction is tracked in the context. +func TransactionFromContext(ctx context.Context) *Span { + if span, ok := ctx.Value(spanContextKey{}).(*Span); ok { + return span.recorder.root() + } + return nil +} + +// SpanFromContext returns the last span stored in the context, or nil if no span +// is set on the context. +func SpanFromContext(ctx context.Context) *Span { + if span, ok := ctx.Value(spanContextKey{}).(*Span); ok { + return span + } + return nil +} + +// StartTransaction will create a transaction (root span) if there's no existing +// transaction in the context otherwise, it will return the existing transaction. +func StartTransaction(ctx context.Context, name string, options ...SpanOption) *Span { + currentTransaction, exists := ctx.Value(spanContextKey{}).(*Span) + if exists { + currentTransaction.ctx = ctx + return currentTransaction + } + + options = append(options, WithTransactionName(name)) + return StartSpan( + ctx, + "", + options..., + ) +} + +// HTTPtoSpanStatus converts an HTTP status code to a SpanStatus. +func HTTPtoSpanStatus(code int) SpanStatus { + if code < http.StatusBadRequest { + return SpanStatusOK + } + if http.StatusBadRequest <= code && code < http.StatusInternalServerError { + switch code { + case http.StatusForbidden: + return SpanStatusPermissionDenied + case http.StatusNotFound: + return SpanStatusNotFound + case http.StatusTooManyRequests: + return SpanStatusResourceExhausted + case http.StatusRequestEntityTooLarge: + return SpanStatusFailedPrecondition + case http.StatusUnauthorized: + return SpanStatusUnauthenticated + case http.StatusConflict: + return SpanStatusAlreadyExists + default: + return SpanStatusInvalidArgument + } + } + if http.StatusInternalServerError <= code && code < 600 { + switch code { + case http.StatusGatewayTimeout: + return SpanStatusDeadlineExceeded + case http.StatusNotImplemented: + return SpanStatusUnimplemented + case http.StatusServiceUnavailable: + return SpanStatusUnavailable + default: + return SpanStatusInternalError + } + } + return SpanStatusUnknown +} + +func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool { + if client == nil { + return true + } + + var sdkOrgID uint64 + if client.dsn != nil { + sdkOrgID = client.dsn.GetOrgID() + } + + baggageOrgStr := dsc.Entries["org_id"] + baggageOrgID := uint64(0) + if baggageOrgStr != "" { + baggageOrgID, _ = strconv.ParseUint(baggageOrgStr, 10, 64) + } + + // we reject non-matching orgs regardless of strict mode + if sdkOrgID != 0 && baggageOrgID != 0 && sdkOrgID != baggageOrgID { + return false + } + + // If strict mode is on, both must be present and match + if client.options.StrictTraceContinuation { + if sdkOrgID == 0 && baggageOrgID == 0 { + return true + } + return sdkOrgID == baggageOrgID + } + + return true +} diff --git a/vendor/github.com/getsentry/sentry-go/transport.go b/vendor/github.com/getsentry/sentry-go/transport.go new file mode 100644 index 0000000..4d487d9 --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/transport.go @@ -0,0 +1,964 @@ +package sentry + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "sync" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + httpinternal "github.com/getsentry/sentry-go/internal/http" + "github.com/getsentry/sentry-go/internal/protocol" + "github.com/getsentry/sentry-go/internal/ratelimit" + "github.com/getsentry/sentry-go/internal/util" + "github.com/getsentry/sentry-go/report" +) + +const ( + defaultBufferSize = 1000 + defaultTimeout = time.Second * 30 + defaultClientReportsTick = time.Second * 30 +) + +// Transport is used by the Client to deliver events to remote server. +type Transport interface { + Flush(timeout time.Duration) bool + FlushWithContext(ctx context.Context) bool + Configure(options ClientOptions) + SendEvent(event *Event) + Close() +} + +func getProxyConfig(options ClientOptions) func(*http.Request) (*url.URL, error) { + if options.HTTPSProxy != "" { + return func(*http.Request) (*url.URL, error) { + return url.Parse(options.HTTPSProxy) + } + } + + if options.HTTPProxy != "" { + return func(*http.Request) (*url.URL, error) { + return url.Parse(options.HTTPProxy) + } + } + + return http.ProxyFromEnvironment +} + +func getTLSConfig(options ClientOptions) *tls.Config { + if options.CaCerts != nil { + // #nosec G402 -- We should be using `MinVersion: tls.VersionTLS12`, + // but we don't want to break peoples code without the major bump. + return &tls.Config{ + RootCAs: options.CaCerts, + } + } + + return nil +} + +// eventDebugContext returns a panic-safe summary of an event for debug logging. +// It only touches scalar fields and len() of collections, which do not trigger +// the runtime concurrent-map-access fatal nor invoke user-defined Stringers. +func eventDebugContext(event *Event) string { + return fmt.Sprintf( + "event=%s type=%s level=%s "+ + "breadcrumbs=%d exceptions=%d tags=%d contexts=%d attachments=%d", + event.EventID, event.Type, event.Level, + len(event.Breadcrumbs), len(event.Exception), + len(event.Tags), len(event.Contexts), len(event.Attachments), + ) +} + +func getRequestBodyFromEvent(event *Event) []byte { + body, err := json.Marshal(event) + if err != nil { + debuglog.Printf("Could not encode event as JSON, skipping delivery. %s: %v", eventDebugContext(event), err) + return nil + } + return body +} + +func encodeAttachment(enc *json.Encoder, b io.Writer, attachment *Attachment) error { + // Attachment header + err := enc.Encode(struct { + Type string `json:"type"` + Length int `json:"length"` + Filename string `json:"filename"` + ContentType string `json:"content_type,omitempty"` + }{ + Type: "attachment", + Length: len(attachment.Payload), + Filename: attachment.Filename, + ContentType: attachment.ContentType, + }) + if err != nil { + return err + } + + // Attachment payload + if _, err = b.Write(attachment.Payload); err != nil { + return err + } + + // "Envelopes should be terminated with a trailing newline." + // + // [1]: https://develop.sentry.dev/sdk/envelopes/#envelopes + if _, err := b.Write([]byte("\n")); err != nil { + return err + } + + return nil +} + +func encodeClientReport(enc *json.Encoder, cr *report.ClientReport) error { + payload, err := json.Marshal(cr) + if err != nil { + return err + } + err = encodeEnvelopeItem(enc, string(protocol.EnvelopeItemTypeClientReport), payload) + if err != nil { + return err + } + + return nil +} + +func encodeEnvelopeItem(enc *json.Encoder, itemType string, body json.RawMessage) error { + // Item header + err := enc.Encode(struct { + Type string `json:"type"` + Length int `json:"length"` + }{ + Type: itemType, + Length: len(body), + }) + if err == nil { + // payload + err = enc.Encode(body) + } + return err +} + +func encodeEnvelopeLogs(enc *json.Encoder, count int, body json.RawMessage) error { + err := enc.Encode( + struct { + Type string `json:"type"` + ItemCount int `json:"item_count"` + ContentType string `json:"content_type"` + }{ + Type: logEvent.Type, + ItemCount: count, + ContentType: logEvent.ContentType, + }) + if err == nil { + err = enc.Encode(body) + } + return err +} + +func encodeEnvelopeMetrics(enc *json.Encoder, count int, body json.RawMessage) error { + err := enc.Encode( + struct { + Type string `json:"type"` + ItemCount int `json:"item_count"` + ContentType string `json:"content_type"` + }{ + Type: traceMetricEvent.Type, + ItemCount: count, + ContentType: traceMetricEvent.ContentType, + }) + if err == nil { + err = enc.Encode(body) + } + return err +} + +func recordForEvent(recorder report.ClientReportRecorder, reason report.DiscardReason, event *Event) { + category := event.toCategory() + switch event.Type { + case transactionType: + recorder.RecordOne(reason, category) + if count := event.GetSpanCount(); count > 0 { + recorder.Record(reason, ratelimit.CategorySpan, int64(count)) + } + case logEvent.Type: + if count := len(event.Logs); count > 0 { + recorder.Record(reason, ratelimit.CategoryLog, int64(count)) + } + if size := event.GetLogByteSize(); size > 0 { + recorder.Record(reason, ratelimit.CategoryLogByte, int64(size)) + } + default: + recorder.RecordOne(reason, category) + } +} + +func recordForBatchItem(recorder report.ClientReportRecorder, reason report.DiscardReason, item *batchItem) { + switch { + case item.logItemCount > 0: + recorder.Record(reason, ratelimit.CategoryLog, int64(item.logItemCount)) + if item.logByteSize > 0 { + recorder.Record(reason, ratelimit.CategoryLogByte, int64(item.logByteSize)) + } + default: + recorder.RecordOne(reason, item.category) + if item.spanCount > 0 { + recorder.Record(reason, ratelimit.CategorySpan, int64(item.spanCount)) + } + } +} + +// envelopeHeader represents the header of a Sentry envelope. +type envelopeHeader struct { + EventID EventID `json:"event_id,omitempty"` + SentAt time.Time `json:"sent_at"` + Dsn *Dsn `json:"dsn,omitempty"` + Sdk map[string]string `json:"sdk,omitempty"` + Trace map[string]string `json:"trace,omitempty"` +} + +func encodeEnvelopeHeader(enc *json.Encoder, header *envelopeHeader) error { + return enc.Encode(header) +} + +func envelopeFromBody(event *Event, dsn *Dsn, sentAt time.Time, body json.RawMessage) (*bytes.Buffer, error) { + var b bytes.Buffer + enc := json.NewEncoder(&b) + + // Construct the trace envelope header + var trace = map[string]string{} + if dsc := event.sdkMetaData.dsc; dsc.HasEntries() { + for k, v := range dsc.Entries { + trace[k] = v + } + } + + // Envelope header + err := encodeEnvelopeHeader(enc, &envelopeHeader{ + EventID: event.EventID, + SentAt: sentAt, + Trace: trace, + Dsn: dsn, + Sdk: map[string]string{ + "name": event.Sdk.Name, + "version": event.Sdk.Version, + }, + }) + if err != nil { + return nil, err + } + + switch event.Type { + case transactionType, checkInType: + err = encodeEnvelopeItem(enc, event.Type, body) + case logEvent.Type: + err = encodeEnvelopeLogs(enc, len(event.Logs), body) + case traceMetricEvent.Type: + err = encodeEnvelopeMetrics(enc, len(event.Metrics), body) + default: + err = encodeEnvelopeItem(enc, eventType, body) + } + + if err != nil { + return nil, err + } + + // Attachments + for _, attachment := range event.Attachments { + if err := encodeAttachment(enc, &b, attachment); err != nil { + return nil, err + } + } + + return &b, nil +} + +// getRequestFromEnvelope creates an HTTP request from a pre-built envelope. +// sdkName and sdkVersion are used for User-Agent and authentication headers. +func getRequestFromEnvelope(ctx context.Context, dsn *Dsn, envelope *bytes.Buffer, sdkName, sdkVersion string) (*http.Request, error) { + if ctx == nil { + ctx = context.Background() + } + + request, err := http.NewRequestWithContext( + ctx, + http.MethodPost, + dsn.GetAPIURL().String(), + envelope, + ) + if err != nil { + return nil, err + } + + request.Header.Set("User-Agent", fmt.Sprintf("%s/%s", sdkName, sdkVersion)) + request.Header.Set("Content-Type", "application/x-sentry-envelope") + + auth := fmt.Sprintf("Sentry sentry_version=%s, "+ + "sentry_client=%s/%s, sentry_key=%s", apiVersion, sdkName, sdkVersion, dsn.GetPublicKey()) + + // The key sentry_secret is effectively deprecated and no longer needs to be set. + // However, since it was required in older self-hosted versions, + // it should still be passed through to Sentry if set. + if dsn.GetSecretKey() != "" { + auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.GetSecretKey()) + } + + request.Header.Set("X-Sentry-Auth", auth) + + return request, nil +} + +// ================================ +// HTTPTransport +// ================================ + +// A batch groups items that are processed sequentially. +type batch struct { + items chan batchItem + started chan struct{} // closed to signal items started to be worked on + done chan struct{} // closed to signal completion of all items +} + +type batchItem struct { + ctx context.Context + envelope *bytes.Buffer + sdkName string + sdkVersion string + category ratelimit.Category + eventIdentifier string + spanCount int + logItemCount int + logByteSize int +} + +// HTTPTransport is the default, non-blocking, implementation of Transport. +// +// Clients using this transport will enqueue requests in a buffer and return to +// the caller before any network communication has happened. Requests are sent +// to Sentry sequentially from a background goroutine. +type HTTPTransport struct { + dsn *Dsn + client *http.Client + transport http.RoundTripper + recorder report.ClientReportRecorder + provider report.ClientReportProvider + + // buffer is a channel of batches. Calling Flush terminates work on the + // current in-flight items and starts a new batch for subsequent events. + buffer chan batch + + startOnce sync.Once + closeOnce sync.Once + + // Size of the transport buffer. Defaults to 30. + BufferSize int + // HTTP Client request timeout. Defaults to 30 seconds. + Timeout time.Duration + + mu sync.RWMutex + limits ratelimit.Map + + // receiving signal will terminate worker. + done chan struct{} +} + +// NewHTTPTransport returns a new pre-configured instance of HTTPTransport. +func NewHTTPTransport() *HTTPTransport { + transport := HTTPTransport{ + BufferSize: defaultBufferSize, + Timeout: defaultTimeout, + done: make(chan struct{}), + limits: make(ratelimit.Map), + } + return &transport +} + +// Configure is called by the Client itself, providing its own ClientOptions. +func (t *HTTPTransport) Configure(options ClientOptions) { + dsn, err := NewDsn(options.Dsn) + if err != nil { + debuglog.Printf("%v\n", err) + return + } + t.dsn = dsn + + if t.recorder == nil { + t.recorder = report.NoopRecorder() + } + if t.provider == nil { + t.provider = report.NoopProvider() + } + + // A buffered channel with capacity 1 works like a mutex, ensuring only one + // goroutine can access the current batch at a given time. Access is + // synchronized by reading from and writing to the channel. + t.buffer = make(chan batch, 1) + t.buffer <- batch{ + items: make(chan batchItem, t.BufferSize), + started: make(chan struct{}), + done: make(chan struct{}), + } + + if options.HTTPTransport != nil { + t.transport = options.HTTPTransport + } else { + t.transport = &http.Transport{ + Proxy: getProxyConfig(options), + TLSClientConfig: getTLSConfig(options), + } + } + + if options.HTTPClient != nil { + t.client = options.HTTPClient + } else { + t.client = &http.Client{ + Transport: t.transport, + Timeout: t.Timeout, + } + } + + t.startOnce.Do(func() { + go t.worker() + }) +} + +// SendEvent assembles a new packet out of Event and sends it to the remote server. +func (t *HTTPTransport) SendEvent(event *Event) { + t.SendEventWithContext(context.Background(), event) +} + +// SendEventWithContext assembles a new packet out of Event and sends it to the remote server. +func (t *HTTPTransport) SendEventWithContext(ctx context.Context, event *Event) { + if t.dsn == nil { + return + } + + category := event.toCategory() + + if t.disabled(category) { + recordForEvent(t.recorder, report.ReasonRateLimitBackoff, event) + return + } + + body := getRequestBodyFromEvent(event) + if body == nil { + recordForEvent(t.recorder, report.ReasonInternalError, event) + return + } + envelope, err := envelopeFromBody(event, t.dsn, time.Now(), body) + if err != nil { + debuglog.Printf("Failed to build envelope, skipping delivery. %s: %v", eventDebugContext(event), err) + recordForEvent(t.recorder, report.ReasonInternalError, event) + return + } + + // <-t.buffer is equivalent to acquiring a lock to access the current batch. + // A few lines below, t.buffer <- b releases the lock. + // + // The lock must be held during the select block below to guarantee that + // b.items is not closed while trying to send to it. Remember that sending + // on a closed channel panics. + // + // Note that the select block takes a bounded amount of CPU time because of + // the default case that is executed if sending on b.items would block. That + // is, the event is dropped if it cannot be sent immediately to the b.items + // channel (used as a queue). + b := <-t.buffer + + identifier := eventIdentifier(event) + + select { + case b.items <- batchItem{ + ctx: ctx, + envelope: envelope, + sdkName: event.Sdk.Name, + sdkVersion: event.Sdk.Version, + category: category, + eventIdentifier: identifier, + spanCount: event.GetSpanCount(), + logItemCount: len(event.Logs), + logByteSize: event.GetLogByteSize(), + }: + debuglog.Printf( + "Sending %s to %s project: %s", + identifier, + t.dsn.GetHost(), + t.dsn.GetProjectID(), + ) + default: + debuglog.Printf("Event dropped due to transport buffer being full. %s", eventDebugContext(event)) + recordForEvent(t.recorder, report.ReasonQueueOverflow, event) + } + + t.buffer <- b +} + +// Flush waits until any buffered events are sent to the Sentry server, blocking +// for at most the given timeout. It returns false if the timeout was reached. +// In that case, some events may not have been sent. +// +// Flush should be called before terminating the program to avoid +// unintentionally dropping events. +// +// Do not call Flush indiscriminately after every call to SendEvent. Instead, to +// have the SDK send events over the network synchronously, configure it to use +// the HTTPSyncTransport in the call to Init. +func (t *HTTPTransport) Flush(timeout time.Duration) bool { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return t.FlushWithContext(ctx) +} + +// FlushWithContext works like Flush, but it accepts a context.Context instead of a timeout. +func (t *HTTPTransport) FlushWithContext(ctx context.Context) bool { + return t.flushInternal(ctx.Done()) +} + +func (t *HTTPTransport) flushInternal(timeout <-chan struct{}) bool { + // Wait until processing the current batch has started or the timeout. + // + // We must wait until the worker has seen the current batch, because it is + // the only way b.done will be closed. If we do not wait, there is a + // possible execution flow in which b.done is never closed, and the only way + // out of Flush would be waiting for the timeout, which is undesired. + var b batch + + for { + select { + case b = <-t.buffer: + select { + case <-b.started: + goto started + default: + t.buffer <- b + } + case <-timeout: + goto fail + } + } + +started: + // Signal that there won't be any more items in this batch, so that the + // worker inner loop can end. + close(b.items) + // Start a new batch for subsequent events. + t.buffer <- batch{ + items: make(chan batchItem, t.BufferSize), + started: make(chan struct{}), + done: make(chan struct{}), + } + + // Wait until the current batch is done or the timeout. + select { + case <-b.done: + debuglog.Println("Buffer flushed successfully.") + return true + case <-timeout: + goto fail + } + +fail: + debuglog.Println("Buffer flushing was canceled or timed out.") + return false +} + +// Close will terminate events sending loop. +// It useful to prevent goroutines leak in case of multiple HTTPTransport instances initiated. +// +// Close should be called after Flush and before terminating the program +// otherwise some events may be lost. +func (t *HTTPTransport) Close() { + t.closeOnce.Do(func() { + close(t.done) + }) +} + +func (t *HTTPTransport) worker() { + crTicker := time.NewTicker(defaultClientReportsTick) + defer crTicker.Stop() + for b := range t.buffer { + // Signal that processing of the current batch has started. + close(b.started) + + // Return the batch to the buffer so that other goroutines can use it. + // Equivalent to releasing a lock. + t.buffer <- b + + // Process all batch items. + loop: + for { + select { + case <-t.done: + return + case <-crTicker.C: + r := t.provider.TakeReport() + if r != nil { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + if err := encodeEnvelopeHeader(enc, &envelopeHeader{ + SentAt: time.Now(), + Dsn: t.dsn, + Sdk: map[string]string{ + "name": sdkIdentifier, + "version": SDKVersion, + }, + }); err != nil { + continue + } + if err := encodeClientReport(enc, r); err != nil { + continue + } + req, err := getRequestFromEnvelope(context.Background(), t.dsn, &buf, sdkIdentifier, SDKVersion) + if err != nil { + debuglog.Printf("There was an issue when creating the request: %v", err) + continue + } + result, err := util.DoSendRequest(t.client, req, "client report") + if err != nil { + debuglog.Printf("There was an issue with sending an event: %v", err) + continue + } + t.mu.Lock() + t.limits.Merge(result.Limits) + t.mu.Unlock() + } + case item, open := <-b.items: + if !open { + break loop + } + if t.disabled(item.category) { + recordForBatchItem(t.recorder, report.ReasonRateLimitBackoff, &item) + continue + } + + // Attach accumulated client report inside the worker to avoid background queue overflows. + t.attachClientReport(item.envelope) + request, err := getRequestFromEnvelope(item.ctx, t.dsn, item.envelope, item.sdkName, item.sdkVersion) + if err != nil { + debuglog.Printf("There was an issue when creating the request: %v", err) + recordForBatchItem(t.recorder, report.ReasonInternalError, &item) + continue + } + + result, err := util.DoSendRequest(t.client, request, item.eventIdentifier) + if err != nil { + debuglog.Printf("There was an issue with sending an event: %v", err) + recordForBatchItem(t.recorder, report.ReasonNetworkError, &item) + continue + } + if result.IsSendError() { + recordForBatchItem(t.recorder, report.ReasonSendError, &item) + } + + t.mu.Lock() + t.limits.Merge(result.Limits) + t.mu.Unlock() + } + } + + // Signal that processing of the batch is done. + close(b.done) + } +} + +// attachClientReport takes any pending client report from the provider and +// appends it to the envelope buffer. +func (t *HTTPTransport) attachClientReport(buf *bytes.Buffer) { + r := t.provider.TakeReport() + if r == nil { + return + } + enc := json.NewEncoder(buf) + if err := encodeClientReport(enc, r); err != nil { + debuglog.Printf("Failed to encode client report: %v", err) + } +} + +func (t *HTTPTransport) disabled(c ratelimit.Category) bool { + t.mu.RLock() + defer t.mu.RUnlock() + disabled := t.limits.IsRateLimited(c) + if disabled { + debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) + } + return disabled +} + +// ================================ +// HTTPSyncTransport +// ================================ + +// HTTPSyncTransport is a blocking implementation of Transport. +// +// Clients using this transport will send requests to Sentry sequentially and +// block until a response is returned. +// +// The blocking behavior is useful in a limited set of use cases. For example, +// use it when deploying code to a Function as a Service ("Serverless") +// platform, where any work happening in a background goroutine is not +// guaranteed to execute. +// +// For most cases, prefer HTTPTransport. +type HTTPSyncTransport struct { + dsn *Dsn + client *http.Client + transport http.RoundTripper + recorder report.ClientReportRecorder + provider report.ClientReportProvider + + mu sync.Mutex + limits ratelimit.Map + + // HTTP Client request timeout. Defaults to 30 seconds. + Timeout time.Duration +} + +// NewHTTPSyncTransport returns a new pre-configured instance of HTTPSyncTransport. +func NewHTTPSyncTransport() *HTTPSyncTransport { + transport := HTTPSyncTransport{ + Timeout: defaultTimeout, + limits: make(ratelimit.Map), + } + + return &transport +} + +// Configure is called by the Client itself, providing its own ClientOptions. +func (t *HTTPSyncTransport) Configure(options ClientOptions) { + dsn, err := NewDsn(options.Dsn) + if err != nil { + debuglog.Printf("%v\n", err) + return + } + t.dsn = dsn + + if t.recorder == nil { + t.recorder = report.NoopRecorder() + } + if t.provider == nil { + t.provider = report.NoopProvider() + } + + if options.HTTPTransport != nil { + t.transport = options.HTTPTransport + } else { + t.transport = &http.Transport{ + Proxy: getProxyConfig(options), + TLSClientConfig: getTLSConfig(options), + } + } + + if options.HTTPClient != nil { + t.client = options.HTTPClient + } else { + t.client = &http.Client{ + Transport: t.transport, + Timeout: t.Timeout, + } + } +} + +// SendEvent assembles a new packet out of Event and sends it to the remote server. +func (t *HTTPSyncTransport) SendEvent(event *Event) { + t.SendEventWithContext(context.Background(), event) +} + +func (t *HTTPSyncTransport) Close() {} + +// SendEventWithContext assembles a new packet out of Event and sends it to the remote server. +func (t *HTTPSyncTransport) SendEventWithContext(ctx context.Context, event *Event) { + if t.dsn == nil { + return + } + + category := event.toCategory() + if t.disabled(category) { + recordForEvent(t.recorder, report.ReasonRateLimitBackoff, event) + return + } + + body := getRequestBodyFromEvent(event) + if body == nil { + recordForEvent(t.recorder, report.ReasonInternalError, event) + return + } + + envelope, err := envelopeFromBody(event, t.dsn, time.Now(), body) + if err != nil { + debuglog.Printf("Failed to build envelope, skipping delivery. %s: %v", eventDebugContext(event), err) + recordForEvent(t.recorder, report.ReasonInternalError, event) + return + } + + if r := t.provider.TakeReport(); r != nil { + enc := json.NewEncoder(envelope) + if err := encodeClientReport(enc, r); err != nil { + debuglog.Printf("Failed to encode client report: %v", err) + } + } + + request, err := getRequestFromEnvelope(ctx, t.dsn, envelope, event.Sdk.Name, event.Sdk.Version) + if err != nil { + recordForEvent(t.recorder, report.ReasonInternalError, event) + return + } + + identifier := eventIdentifier(event) + debuglog.Printf( + "Sending %s to %s project: %s", + identifier, + t.dsn.GetHost(), + t.dsn.GetProjectID(), + ) + + result, err := util.DoSendRequest(t.client, request, identifier) + if err != nil { + debuglog.Printf("There was an issue with sending an event: %v", err) + recordForEvent(t.recorder, report.ReasonNetworkError, event) + return + } + if result.IsSendError() { + recordForEvent(t.recorder, report.ReasonSendError, event) + } + + t.mu.Lock() + t.limits.Merge(result.Limits) + t.mu.Unlock() +} + +// Flush is a no-op for HTTPSyncTransport. It always returns true immediately. +func (t *HTTPSyncTransport) Flush(_ time.Duration) bool { + return true +} + +// FlushWithContext is a no-op for HTTPSyncTransport. It always returns true immediately. +func (t *HTTPSyncTransport) FlushWithContext(_ context.Context) bool { + return true +} + +func (t *HTTPSyncTransport) disabled(c ratelimit.Category) bool { + t.mu.Lock() + defer t.mu.Unlock() + disabled := t.limits.IsRateLimited(c) + if disabled { + debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c)) + } + return disabled +} + +// ================================ +// noopTransport +// ================================ + +// noopTransport is an implementation of Transport interface which drops all the events. +// Only used internally when an empty DSN is provided, which effectively disables the SDK. +type noopTransport struct{} + +var _ Transport = noopTransport{} + +func (noopTransport) Configure(ClientOptions) { + debuglog.Println("Sentry client initialized with an empty DSN. Using noopTransport. No events will be delivered.") +} + +func (noopTransport) SendEvent(*Event) { + debuglog.Println("Event dropped due to noopTransport usage.") +} + +func (noopTransport) Flush(time.Duration) bool { + return true +} + +func (noopTransport) FlushWithContext(context.Context) bool { + return true +} + +func (noopTransport) Close() {} + +// ================================ +// Internal Transport Adapters +// ================================ + +// newInternalAsyncTransport creates a new AsyncTransport from internal/http +// wrapped to satisfy the Transport interface. +// +// This is not yet exposed in the public API and is for internal experimentation. +func newInternalAsyncTransport() Transport { + return &internalAsyncTransportAdapter{} +} + +// internalAsyncTransportAdapter wraps the internal AsyncTransport to implement +// the root-level Transport interface. +type internalAsyncTransportAdapter struct { + transport protocol.TelemetryTransport + dsn *protocol.Dsn + recorder report.ClientReportRecorder + provider report.ClientReportProvider +} + +func (a *internalAsyncTransportAdapter) Configure(options ClientOptions) { + transportOptions := httpinternal.TransportOptions{ + Dsn: options.Dsn, + HTTPClient: options.HTTPClient, + HTTPTransport: options.HTTPTransport, + HTTPProxy: options.HTTPProxy, + HTTPSProxy: options.HTTPSProxy, + CaCerts: options.CaCerts, + Recorder: a.recorder, + Provider: a.provider, + SdkInfo: func() *protocol.SdkInfo { + return &protocol.SdkInfo{ + Name: sdkIdentifier, + Version: SDKVersion, + } + }, + } + + a.transport = httpinternal.NewAsyncTransport(transportOptions) + + if options.Dsn != "" { + dsn, err := protocol.NewDsn(options.Dsn) + if err != nil { + debuglog.Printf("Failed to parse DSN in adapter: %v\n", err) + } else { + a.dsn = dsn + } + } +} + +func (a *internalAsyncTransportAdapter) SendEvent(event *Event) { + header := &protocol.EnvelopeHeader{EventID: string(event.EventID), SentAt: time.Now(), Dsn: a.dsn, Sdk: &protocol.SdkInfo{Name: event.Sdk.Name, Version: event.Sdk.Version}} + if header.EventID == "" { + header.EventID = protocol.GenerateEventID() + } + envelope, err := event.ToEnvelope(header) + if err != nil { + debuglog.Printf("Failed to convert event to envelope, skipping delivery. %s: %v", eventDebugContext(event), err) + if a.recorder != nil { + recordForEvent(a.recorder, report.ReasonInternalError, event) + } + return + } + + if err := a.transport.SendEnvelope(envelope); err != nil { + debuglog.Printf("Error sending envelope: %v", err) + } +} + +func (a *internalAsyncTransportAdapter) Flush(timeout time.Duration) bool { + return a.transport.Flush(timeout) +} + +func (a *internalAsyncTransportAdapter) FlushWithContext(ctx context.Context) bool { + return a.transport.FlushWithContext(ctx) +} + +func (a *internalAsyncTransportAdapter) Close() { + a.transport.Close() +} diff --git a/vendor/github.com/getsentry/sentry-go/util.go b/vendor/github.com/getsentry/sentry-go/util.go new file mode 100644 index 0000000..f81ef1d --- /dev/null +++ b/vendor/github.com/getsentry/sentry-go/util.go @@ -0,0 +1,133 @@ +package sentry + +import ( + "encoding/json" + "fmt" + "os" + "runtime/debug" + "strings" + "time" + + "github.com/getsentry/sentry-go/internal/debuglog" + "github.com/getsentry/sentry-go/internal/protocol" + exec "golang.org/x/sys/execabs" +) + +func uuid() string { + return protocol.GenerateEventID() +} + +func fileExists(fileName string) bool { + _, err := os.Stat(fileName) + return err == nil +} + +// monotonicTimeSince replaces uses of time.Now() to take into account the +// monotonic clock reading stored in start, such that duration = end - start is +// unaffected by changes in the system wall clock. +func monotonicTimeSince(start time.Time) (end time.Time) { + return start.Add(time.Since(start)) +} + +// nolint: unused +func prettyPrint(data interface{}) { + dbg, _ := json.MarshalIndent(data, "", " ") + fmt.Println(string(dbg)) +} + +// defaultRelease attempts to guess a default release for the currently running +// program. +func defaultRelease() (release string) { + // Return first non-empty environment variable known to hold release info, if any. + envs := []string{ + "SENTRY_RELEASE", + "HEROKU_BUILD_COMMIT", + "HEROKU_SLUG_COMMIT", // Deprecated, kept for backwards compatibility + "SOURCE_VERSION", + "CODEBUILD_RESOLVED_SOURCE_VERSION", + "CIRCLE_SHA1", + "GAE_DEPLOYMENT_ID", + "GITHUB_SHA", // GitHub Actions - https://help.github.com/en/actions + "COMMIT_REF", // Netlify - https://docs.netlify.com/ + "VERCEL_GIT_COMMIT_SHA", // Vercel - https://vercel.com/ + "ZEIT_GITHUB_COMMIT_SHA", // Zeit (now known as Vercel) + "ZEIT_GITLAB_COMMIT_SHA", + "ZEIT_BITBUCKET_COMMIT_SHA", + } + for _, e := range envs { + if release = os.Getenv(e); release != "" { + debuglog.Printf("Using release from environment variable %s: %s", e, release) + return release + } + } + + if info, ok := debug.ReadBuildInfo(); ok { + buildInfoVcsRevision := revisionFromBuildInfo(info) + if len(buildInfoVcsRevision) > 0 { + return buildInfoVcsRevision + } + } + + // Derive a version string from Git. Example outputs: + // v1.0.1-0-g9de4 + // v2.0-8-g77df-dirty + // 4f72d7 + if _, err := exec.LookPath("git"); err == nil { + cmd := exec.Command("git", "describe", "--long", "--always", "--dirty") + b, err := cmd.Output() + if err != nil { + // Either Git is not available or the current directory is not a + // Git repository. + var s strings.Builder + fmt.Fprintf(&s, "Release detection failed: %v", err) + if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 { + fmt.Fprintf(&s, ": %s", err.Stderr) + } + debuglog.Print(s.String()) + } else { + release = strings.TrimSpace(string(b)) + debuglog.Printf("Using release from Git: %s", release) + return release + } + } + + debuglog.Print("Some Sentry features will not be available. See https://docs.sentry.io/product/releases/.") + debuglog.Print("To stop seeing this message, pass a Release to sentry.Init or set the SENTRY_RELEASE environment variable.") + return "" +} + +func revisionFromBuildInfo(info *debug.BuildInfo) string { + for _, setting := range info.Settings { + if setting.Key == "vcs.revision" && setting.Value != "" { + debuglog.Printf("Using release from debug info: %s", setting.Value) + return setting.Value + } + } + + return "" +} + +func Pointer[T any](v T) *T { + return &v +} + +// eventIdentifier returns a human-readable identifier for the event to be used in log messages. +// Format: " []". +func eventIdentifier(event *Event) string { + var description string + switch event.Type { + case errorType: + description = "error" + case transactionType: + description = "transaction" + case checkInType: + description = "check-in" + case logEvent.Type: + description = fmt.Sprintf("%d log events", len(event.Logs)) + case traceMetricEvent.Type: + description = fmt.Sprintf("%d metric events", len(event.Metrics)) + default: + description = fmt.Sprintf("%s event", event.Type) + } + return fmt.Sprintf("%s [%s]", description, event.EventID) +} diff --git a/vendor/github.com/go-faker/faker/v4/.gitignore b/vendor/github.com/go-faker/faker/v4/.gitignore new file mode 100644 index 0000000..b36ea1d --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/.gitignore @@ -0,0 +1,23 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out +cover.html +.vscode/ + +# generated file for Jetbrains Goland IDE +.idea + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ +faker +vendor/ +coverage.txt +bin/ \ No newline at end of file diff --git a/vendor/github.com/go-faker/faker/v4/.golangci.bck.yaml b/vendor/github.com/go-faker/faker/v4/.golangci.bck.yaml new file mode 100644 index 0000000..e15388b --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/.golangci.bck.yaml @@ -0,0 +1,53 @@ +linters-settings: + govet: + settings: + printf: + funcs: + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + gocyclo: + min-complexity: 70 + dupl: + threshold: 100 + goconst: + min-len: 2 + min-occurrences: 5 + misspell: + locale: US + +linters: + # please, do not use `enable-all`: it's deprecated and will be removed soon. + # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint + disable-all: true + enable: + # - deadcode + - errcheck + - goconst + - gocyclo + - revive + - gosimple + - govet + - ineffassign + - misspell + - staticcheck + # - structcheck + - typecheck + - unconvert + - unparam + - unused + # - varcheck + +issues: + exclude-rules: + - path: person.go # since in the person.go there are so many names that may detected as misspell + linters: + - misspell + - path: datetime.go + linters: + - misspell + - path: . + text: "parameter 'v' seems to be unused" +run: + timeout: 5m diff --git a/vendor/github.com/go-faker/faker/v4/.golangci.yaml b/vendor/github.com/go-faker/faker/v4/.golangci.yaml new file mode 100644 index 0000000..6ff5c54 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/.golangci.yaml @@ -0,0 +1,63 @@ +version: "2" +linters: + default: none + enable: + - errcheck + - goconst + - gocyclo + - govet + - ineffassign + - misspell + - revive + - staticcheck + - unconvert + - unparam + - unused + settings: + dupl: + threshold: 100 + goconst: + min-len: 2 + min-occurrences: 5 + gocyclo: + min-complexity: 70 + govet: + settings: + printf: + funcs: + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + misspell: + locale: US + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + rules: + - linters: + - goconst + path: lorem.go + - linters: + - misspell + path: person.go + - linters: + - misspell + path: datetime.go + - path: . + text: parameter 'v' seems to be unused + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/vendor/github.com/go-faker/faker/v4/LICENSE b/vendor/github.com/go-faker/faker/v4/LICENSE new file mode 100644 index 0000000..9e00dcd --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Iman Tumorang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/go-faker/faker/v4/Makefile b/vendor/github.com/go-faker/faker/v4/Makefile new file mode 100644 index 0000000..176b5a8 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/Makefile @@ -0,0 +1,44 @@ + +# Exporting bin folder to the path for makefile +export PATH := $(PWD)/bin:$(PATH) +# Default Shell +export SHELL := bash +# Type of OS: Linux or Darwin. +export OSTYPE := $(shell uname -s) + +ifeq ($(OSTYPE),Darwin) + export MallocNanoZone=0 +endif + +include ./misc/makefile/tools.Makefile + +build: test + @go build ./... + +install-deps: gotestsum tparse ## Install Development Dependencies (localy). +deps: $(GOTESTSUM) $(TPARSE) ## Checks for Global Development Dependencies. +deps: + @echo "Required Tools Are Available" + +TESTS_ARGS := --format testname --jsonfile gotestsum.json.out +TESTS_ARGS += --max-fails 2 +TESTS_ARGS += -- ./... +TESTS_ARGS += -test.parallel 2 +TESTS_ARGS += -test.count 1 +TESTS_ARGS += -test.failfast +TESTS_ARGS += -test.coverprofile coverage.out +TESTS_ARGS += -test.timeout 60s +TESTS_ARGS += -race +run-tests: $(GOTESTSUM) + @ gotestsum $(TESTS_ARGS) -short + +test: run-tests $(TPARSE) ## Run Tests & parse details + @cat gotestsum.json.out | $(TPARSE) -all -notests + + +lint: $(GOLANGCI) ## Runs golangci-lint with predefined configuration + @echo "Applying linter" + golangci-lint version + golangci-lint run -c .golangci.yaml ./... + +.PHONY: lint lint-prepare clean build unittest \ No newline at end of file diff --git a/vendor/github.com/go-faker/faker/v4/README.md b/vendor/github.com/go-faker/faker/v4/README.md new file mode 100644 index 0000000..88d5a97 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/README.md @@ -0,0 +1,113 @@ +# Docs + +## [faker](#) + +Struct Data Fake Generator + +Faker will generate you a fake data based on your Struct. + +[![Go Test](https://github.com/go-faker/faker/actions/workflows/go.yml/badge.svg)](https://github.com/go-faker/faker/actions/workflows/go.yml) +[![codecov](https://codecov.io/gh/go-faker/faker/branch/main/graph/badge.svg)](https://codecov.io/gh/go-faker/faker) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-faker/faker/v4)](https://goreportcard.com/report/github.com/go-faker/faker/v4) +[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/go-faker/faker/blob/master/LICENSE) +[![Go.Dev](https://img.shields.io/badge/go.dev-reference-007d9c?logo=go&logoColor=white)](https://pkg.go.dev/github.com/go-faker/faker/v4?tab=doc) + +## Index + +- [Support](#support) +- [Getting Started](#getting-started) +- [Example](#example) +- [Limitation](#limitation) +- [Contribution](#contribution) + +## Support + +You can file an [Issue](https://github.com/go-faker/faker/issues/new). +See documentation in [Go.Dev](https://pkg.go.dev/github.com/go-faker/faker/v4?tab=doc) + +## Getting Started + +#### Download + +```shell +go get -u github.com/go-faker/faker/v4 +``` + +# Example + +--- + +- Using Struct's tag: + - [basic tags: example_with_tags_test.go](/example_with_tags_test.go) + - [length and bounds: example_with_tags_lenbounds_test.go](/example_with_tags_lenbounds_test.go) + - [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) +- custom struct type providers : [example_custom_struct_test.go](/example_custom_struct_test.go) +- large nested (& circular) struct with map & slice size limits & depth limitations : [example_with_limits_test.go](/example_with_limits_test.go) + +## DEMO + +--- + +![Example to use Faker](https://cdn-images-1.medium.com/max/800/1*AkMbxngg7zfvtWiuvFb4Mg.gif) + +## Benchmark + +--- + +Bench To Generate Fake Data + +#### Without Tag + +```bash +BenchmarkFakerDataNOTTagged-4 500000 3049 ns/op 488 B/op 20 allocs/op +``` + +#### Using Tag + +```bash + BenchmarkFakerDataTagged-4 100000 17470 ns/op 380 B/op 26 allocs/op +``` + +### MUST KNOW + +--- + +The Struct Field must be PUBLIC.
+Support For : + +- pointer fields of any type +- `int`, `int8`, `int16`, `int32` & `int64` +- `uint`, `uint8`, `uint16`, `uint32` & `uint64` +- `bool` +- `string` +- `float32`, `float64` +- struct & nested struct +- `slice` / `array` of any type +- `map` of any key/value of supported types +- custom struct types by registering a `StructTypeProvider` & implementing your own generator function. This can be used for redefined time, big.Rat, etc. See [example](faker_test.go#L2655) for usage. + - default `time.Time` provider is registered, you can override it by registering your own provider. + +## Limitation + +--- + +Unfortunately this library has some limitation + +- It does not support private fields. Make sure your structs fields you intend to generate fake data for are public, it would otherwise trigger a panic. You can however omit fields using a tag skip `faker:"-"` on your private fields. +- It does not support the `any` (empty interface) data type. How could we generate anything without knowing its data type? +- 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 + +--- + +To contrib to this project, you can open a PR or an issue. diff --git a/vendor/github.com/go-faker/faker/v4/address.go b/vendor/github.com/go-faker/faker/v4/address.go new file mode 100644 index 0000000..59962b3 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/address.go @@ -0,0 +1,149 @@ +package faker + +import ( + _ "embed" + "encoding/json" + "reflect" + + "github.com/go-faker/faker/v4/pkg/options" +) + +var ( + //go:embed misc/addresses-us-1000.min.json + addressesUSBytes []byte + addressesUS []RealAddress + + //go:embed misc/country_info.json + countriesBytes []byte + countries []CountryInfo +) + +func init() { + data := struct { + Addresses []RealAddress `json:"addresses"` + Countries []CountryInfo `json:"countries"` + }{} + if err := json.Unmarshal(addressesUSBytes, &data); err != nil { + panic(err) + } + addressesUS = data.Addresses + + if err := json.Unmarshal(countriesBytes, &data); err != nil { + panic(err) + } + countries = data.Countries +} + +// GetAddress returns a new Addresser interface of Address +func GetAddress() Addresser { + address := &Address{} + return address +} + +// Addresser is logical layer for Address +type Addresser interface { + Latitude(v reflect.Value) (any, error) + Longitude(v reflect.Value) (any, error) + RealWorld(v reflect.Value) (any, error) + CountryInfo(v reflect.Value) (any, error) +} + +// Address struct +type Address struct{} + +func (i Address) latitude() float32 { + return (rand.Float32() * 180) - 90 +} + +// Latitude sets latitude of the address +func (i Address) Latitude(v reflect.Value) (any, error) { + kind := v.Kind() + val := i.latitude() + if kind == reflect.Float32 { + return val, nil + } + return float64(val), nil +} + +func (i Address) longitude() float32 { + return (rand.Float32() * 360) - 180 +} + +// Longitude sets longitude of the address +func (i Address) Longitude(v reflect.Value) (any, error) { + kind := v.Kind() + val := i.longitude() + if kind == reflect.Float32 { + return val, nil + } + return float64(val), nil +} + +func (i Address) realWorld() RealAddress { + return addressesUS[rand.Intn(len(addressesUS))] +} + +func (i Address) countryInfo() CountryInfo { + return countries[rand.Intn(len(countries))] +} + +func (i Address) CountryInfo(_ reflect.Value) (any, error) { + return i.countryInfo(), nil +} + +// RealWorld sets real world address +func (i Address) RealWorld(_ reflect.Value) (any, error) { + return i.realWorld(), nil +} + +// Longitude get fake longitude randomly +func Longitude(opts ...options.OptionFunc) float64 { + return singleFakeData(LONGITUDE, func() any { + address := Address{} + return float64(address.longitude()) + }, opts...).(float64) +} + +// Latitude get fake latitude randomly +func Latitude(opts ...options.OptionFunc) float64 { + return singleFakeData(LATITUDE, func() any { + address := Address{} + return float64(address.latitude()) + }, opts...).(float64) +} + +type RealCoordinates struct { + Latitude float64 `json:"lat"` + Longitude float64 `json:"lng"` +} + +type RealAddress struct { + Address string `json:"address1"` + City string `json:"city"` + State string `json:"state"` + PostalCode string `json:"postalCode"` + Coordinates RealCoordinates `json:"coordinates"` +} + +// GetRealAddress get real world address randomly +func GetRealAddress(opts ...options.OptionFunc) RealAddress { + return singleFakeData(RealAddressTag, func() any { + address := Address{} + return address.realWorld() + }, opts...).(RealAddress) +} + +type CountryInfo struct { + Abbr string `json:"abbr"` + Name string `json:"name"` + Capital string `json:"capital"` + Population string `json:"population"` + Continent string `json:"continent"` +} + +func GetCountryInfo(opts ...options.OptionFunc) CountryInfo { + return singleFakeData(CountryInfoTag, func() any { + address := Address{} + return address.countryInfo() + }, opts...).(CountryInfo) +} diff --git a/vendor/github.com/go-faker/faker/v4/blood.go b/vendor/github.com/go-faker/faker/v4/blood.go new file mode 100644 index 0000000..5e4dbea --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/blood.go @@ -0,0 +1,54 @@ +package faker + +import ( + "fmt" + "reflect" + + "github.com/go-faker/faker/v4/pkg/options" +) + +var bloodTypes = []string{"O", "A", "B", "AB"} +var bloodRhFactors = []string{"+", "-"} + +func GetBlood(opts ...options.OptionFunc) Blooder { + opt := options.BuildOptions(opts) + db := &Blood{ + fakerOption: *opt, + } + return db +} + +type Blooder interface { + BloodType(v reflect.Value) (any, error) + BloodRHFactor(v reflect.Value) (any, error) + BloodGroup(v reflect.Value) (any, error) +} + +// Internet struct +type Blood struct { + fakerOption options.Options +} + +func (b Blood) bloodType() string { + return randomElementFromSliceString(bloodTypes) +} + +func (b Blood) BloodType(v reflect.Value) (any, error) { + return b.bloodType(), nil +} + +func (b Blood) bloodRhFactor() string { + return randomElementFromSliceString(bloodRhFactors) +} + +func (b Blood) BloodRHFactor(v reflect.Value) (any, error) { + return b.bloodRhFactor(), nil +} + +func (b Blood) bloodGroup() string { + return fmt.Sprintf("%s%s", b.bloodType(), b.bloodRhFactor()) +} + +func (b Blood) BloodGroup(v reflect.Value) (any, error) { + return b.bloodGroup(), nil +} diff --git a/vendor/github.com/go-faker/faker/v4/datetime.go b/vendor/github.com/go-faker/faker/v4/datetime.go new file mode 100644 index 0000000..b548a5c --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/datetime.go @@ -0,0 +1,830 @@ +package faker + +import ( + "fmt" + "reflect" + "time" + + "github.com/go-faker/faker/v4/pkg/options" +) + +var century = []string{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI"} +var timezones = []string{ + "Australia/Adelaide", + "Australia/Broken_Hill", + "Australia/South", + "Australia/Yancowinna", + "Australia/Darwin", + "Australia/North", + "America/Eirunepe", + "America/Porto_Acre", + "America/Rio_Branco", + "Brazil/Acre", + "Australia/Eucla", + "Australia/ACT", + "Australia/Canberra", + "Australia/Currie", + "Australia/Hobart", + "Australia/Melbourne", + "Australia/NSW", + "Australia/Sydney", + "Australia/Tasmania", + "Australia/Victoria", + "Australia/Brisbane", + "Australia/Lindeman", + "Australia/Queensland", + "Asia/Kabul", + "America/Anchorage", + "America/Juneau", + "America/Nome", + "America/Sitka", + "America/Yakutat", + "US/Alaska", + "Asia/Almaty", + "America/Boa_Vista", + "America/Campo_Grande", + "America/Cuiaba", + "America/Manaus", + "America/Porto_Velho", + "Asia/Yerevan", + "Brazil/West", + "Asia/Anadyr", + "Asia/Aqtau", + "Asia/Aqtobe", + "America/Argentina/Buenos_Aires", + "America/Argentina/Catamarca", + "America/Argentina/ComodRivadavia", + "America/Argentina/Cordoba", + "America/Argentina/Jujuy", + "America/Argentina/La_Rioja", + "America/Argentina/Mendoza", + "America/Argentina/Rio_Gallegos", + "America/Argentina/Salta", + "America/Argentina/San_Juan", + "America/Argentina/San_Luis", + "America/Argentina/Tucuman", + "America/Argentina/Ushuaia", + "America/Buenos_Aires", + "America/Catamarca", + "America/Cordoba", + "America/Jujuy", + "America/Mendoza", + "America/Rosario", + "America/Anguilla", + "America/Antigua", + "America/Aruba", + "America/Barbados", + "America/Blanc-Sablon", + "America/Curacao", + "America/Dominica", + "America/Glace_Bay", + "America/Goose_Bay", + "America/Grand_Turk", + "America/Grenada", + "America/Guadeloupe", + "America/Halifax", + "America/Kralendijk", + "America/Lower_Princes", + "America/Marigot", + "America/Martinique", + "America/Moncton", + "America/Montserrat", + "America/Port_of_Spain", + "America/Puerto_Rico", + "America/Santo_Domingo", + "America/St_Barthelemy", + "America/St_Kitts", + "America/St_Lucia", + "America/St_Thomas", + "America/St_Vincent", + "America/Thule", + "America/Tortola", + "America/Virgin", + "Asia/Aden", + "Asia/Baghdad", + "Asia/Bahrain", + "Asia/Kuwait", + "Asia/Qatar", + "Asia/Riyadh", + "Atlantic/Bermuda", + "Canada/Atlantic", + "Antarctica/Casey", + "Australia/Perth", + "Australia/West", + "Atlantic/Azores", + "Asia/Baku", + "Asia/Dacca", + "Asia/Dhaka", + "Asia/Brunei", + "America/La_Paz", + "America/Araguaina", + "America/Bahia", + "America/Belem", + "America/Fortaleza", + "America/Maceio", + "America/Recife", + "America/Santarem", + "America/Sao_Paulo", + "Brazil/East", + "Pacific/Bougainville", + "Asia/Thimbu", + "Asia/Thimphu", + "Africa/Blantyre", + "Africa/Bujumbura", + "Africa/Gaborone", + "Africa/Harare", + "Africa/Kigali", + "Africa/Lubumbashi", + "Africa/Lusaka", + "Africa/Maputo", + "Indian/Cocos", + "Africa/Algiers", + "Africa/Ceuta", + "Africa/Tunis", + "Arctic/Longyearbyen", + "Atlantic/Jan_Mayen", + "CET", + "Europe/Amsterdam", + "Europe/Andorra", + "Europe/Belgrade", + "Europe/Berlin", + "Europe/Bratislava", + "Europe/Brussels", + "Europe/Budapest", + "Europe/Busingen", + "Europe/Copenhagen", + "Europe/Gibraltar", + "Europe/Ljubljana", + "Europe/Luxembourg", + "Europe/Madrid", + "Europe/Malta", + "Europe/Monaco", + "Europe/Oslo", + "Europe/Paris", + "Europe/Podgorica", + "Europe/Prague", + "Europe/Rome", + "Europe/San_Marino", + "Europe/Sarajevo", + "Europe/Skopje", + "Europe/Stockholm", + "Europe/Tirane", + "Europe/Vaduz", + "Europe/Vatican", + "Europe/Vienna", + "Europe/Warsaw", + "Europe/Zagreb", + "Europe/Zurich", + "Poland", + "NZ-CHAT", + "Pacific/Chatham", + "Asia/Choibalsan", + "Pacific/Chuuk", + "Pacific/Truk", + "Pacific/Yap", + "Pacific/Rarotonga", + "America/Santiago", + "Antarctica/Palmer", + "Chile/Continental", + "America/Bogota", + "America/Bahia_Banderas", + "America/Belize", + "America/Chicago", + "America/Costa_Rica", + "America/El_Salvador", + "America/Guatemala", + "America/Havana", + "America/Indiana/Knox", + "America/Indiana/Tell_City", + "America/Knox_IN", + "America/Managua", + "America/Matamoros", + "America/Menominee", + "America/Merida", + "America/Mexico_City", + "America/Monterrey", + "America/North_Dakota/Beulah", + "America/North_Dakota/Center", + "America/North_Dakota/New_Salem", + "America/Rainy_River", + "America/Rankin_Inlet", + "America/Regina", + "America/Resolute", + "America/Swift_Current", + "America/Tegucigalpa", + "America/Winnipeg", + "Asia/Chongqing", + "Asia/Chungking", + "Asia/Harbin", + "Asia/Macao", + "Asia/Macau", + "Asia/Shanghai", + "Asia/Taipei", + "CST6CDT", + "Canada/Central", + "Canada/Saskatchewan", + "Cuba", + "Mexico/General", + "PRC", + "ROC", + "US/Central", + "US/Indiana-Starke", + "Atlantic/Cape_Verde", + "Indian/Christmas", + "Pacific/Guam", + "Pacific/Saipan", + "Antarctica/Davis", + "Antarctica/DumontDUrville", + "Chile/EasterIsland", + "Pacific/Easter", + "Africa/Asmara", + "Africa/Asmera", + "Africa/Dar_es_Salaam", + "Africa/Djibouti", + "Africa/Juba", + "Africa/Kampala", + "Africa/Khartoum", + "Africa/Mogadishu", + "Africa/Nairobi", + "Indian/Antananarivo", + "Indian/Comoro", + "Indian/Mayotte", + "America/Guayaquil", + "Africa/Cairo", + "Africa/Tripoli", + "Asia/Amman", + "Asia/Beirut", + "Asia/Damascus", + "Asia/Gaza", + "Asia/Hebron", + "Asia/Istanbul", + "Asia/Nicosia", + "EET", + "Egypt", + "Europe/Athens", + "Europe/Bucharest", + "Europe/Chisinau", + "Europe/Helsinki", + "Europe/Istanbul", + "Europe/Kaliningrad", + "Europe/Kiev", + "Europe/Mariehamn", + "Europe/Nicosia", + "Europe/Riga", + "Europe/Sofia", + "Europe/Tallinn", + "Europe/Tiraspol", + "Europe/Uzhgorod", + "Europe/Vilnius", + "Europe/Zaporozhye", + "Libya", + "Turkey", + "America/Scoresbysund", + "America/Atikokan", + "America/Cancun", + "America/Cayman", + "America/Coral_Harbour", + "America/Detroit", + "America/Fort_Wayne", + "America/Indiana/Indianapolis", + "America/Indiana/Marengo", + "America/Indiana/Petersburg", + "America/Indiana/Vevay", + "America/Indiana/Vincennes", + "America/Indiana/Winamac", + "America/Indianapolis", + "America/Iqaluit", + "America/Jamaica", + "America/Kentucky/Louisville", + "America/Kentucky/Monticello", + "America/Louisville", + "America/Montreal", + "America/Nassau", + "America/New_York", + "America/Nipigon", + "America/Panama", + "America/Pangnirtung", + "America/Port-au-Prince", + "America/Thunder_Bay", + "America/Toronto", + "Canada/Eastern", + "EST", + "EST5EDT", + "Jamaica", + "US/East-Indiana", + "US/Eastern", + "US/Michigan", + "Pacific/Fiji", + "Atlantic/Stanley", + "America/Noronha", + "Brazil/DeNoronha", + "Pacific/Galapagos", + "Pacific/Gambier", + "Asia/Tbilisi", + "America/Cayenne", + "Pacific/Tarawa", + "Africa/Abidjan", + "Africa/Accra", + "Africa/Bamako", + "Africa/Banjul", + "Africa/Bissau", + "Africa/Conakry", + "Africa/Dakar", + "Africa/Freetown", + "Africa/Lome", + "Africa/Monrovia", + "Africa/Nouakchott", + "Africa/Ouagadougou", + "Africa/Sao_Tome", + "Africa/Timbuktu", + "America/Danmarkshavn", + "Atlantic/Reykjavik", + "Atlantic/St_Helena", + "Eire", + "Etc/GMT", + "Etc/GMT+0", + "Etc/GMT-0", + "Etc/GMT0", + "Etc/Greenwich", + "Europe/Belfast", + "Europe/Dublin", + "Europe/Guernsey", + "Europe/Isle_of_Man", + "Europe/Jersey", + "Europe/London", + "GB", + "GB-Eire", + "GMT", + "GMT+0", + "GMT-0", + "GMT0", + "Greenwich", + "Iceland", + "Etc/GMT+1", + "Etc/GMT+10", + "Etc/GMT+11", + "Etc/GMT+12", + "Etc/GMT+2", + "Etc/GMT+3", + "Etc/GMT+4", + "Etc/GMT+5", + "Etc/GMT+6", + "Etc/GMT+7", + "Etc/GMT+8", + "Etc/GMT+9", + "Etc/GMT-1", + "Etc/GMT-10", + "Etc/GMT-11", + "Etc/GMT-12", + "Etc/GMT-13", + "Etc/GMT-14", + "Etc/GMT-2", + "Etc/GMT-3", + "Etc/GMT-4", + "Etc/GMT-5", + "Etc/GMT-6", + "Etc/GMT-7", + "Etc/GMT-8", + "Etc/GMT-9", + "Asia/Dubai", + "Asia/Muscat", + "Atlantic/South_Georgia", + "America/Guyana", + "Asia/Hong_Kong", + "Hongkong", + "Asia/Hovd", + "America/Adak", + "America/Atka", + "HST", + "Pacific/Honolulu", + "Pacific/Johnston", + "US/Aleutian", + "US/Hawaii", + "Asia/Bangkok", + "Asia/Ho_Chi_Minh", + "Asia/Phnom_Penh", + "Asia/Saigon", + "Asia/Vientiane", + "Indian/Chagos", + "Asia/Chita", + "Asia/Irkutsk", + "Asia/Tehran", + "Iran", + "Asia/Calcutta", + "Asia/Colombo", + "Asia/Jerusalem", + "Asia/Kolkata", + "Asia/Tel_Aviv", + "Israel", + "Asia/Tokyo", + "Japan", + "Asia/Bishkek", + "Pacific/Kosrae", + "Asia/Krasnoyarsk", + "Asia/Novokuznetsk", + "Asia/Pyongyang", + "Asia/Seoul", + "ROK", + "Australia/LHI", + "Australia/Lord_Howe", + "Pacific/Kiritimati", + "Asia/Magadan", + "Pacific/Marquesas", + "Antarctica/Mawson", + "MET", + "Kwajalein", + "Pacific/Kwajalein", + "Pacific/Majuro", + "Antarctica/Macquarie", + "Asia/Rangoon", + "Europe/Minsk", + "Europe/Moscow", + "Europe/Simferopol", + "Europe/Volgograd", + "W-SU", + "America/Boise", + "America/Cambridge_Bay", + "America/Chihuahua", + "America/Creston", + "America/Dawson_Creek", + "America/Denver", + "America/Edmonton", + "America/Fort_Nelson", + "America/Hermosillo", + "America/Inuvik", + "America/Mazatlan", + "America/Ojinaga", + "America/Phoenix", + "America/Shiprock", + "America/Yellowknife", + "Canada/Mountain", + "MST", + "MST7MDT", + "Mexico/BajaSur", + "Navajo", + "US/Arizona", + "US/Mountain", + "Indian/Mauritius", + "Indian/Maldives", + "Asia/Kuala_Lumpur", + "Asia/Kuching", + "Pacific/Noumea", + "Pacific/Norfolk", + "Asia/Novosibirsk", + "Asia/Kathmandu", + "Asia/Katmandu", + "Pacific/Nauru", + "America/St_Johns", + "Canada/Newfoundland", + "Pacific/Niue", + "Antarctica/McMurdo", + "Antarctica/South_Pole", + "NZ", + "Pacific/Auckland", + "Asia/Omsk", + "Asia/Oral", + "America/Lima", + "Asia/Kamchatka", + "Pacific/Port_Moresby", + "Pacific/Enderbury", + "Asia/Manila", + "Asia/Karachi", + "America/Miquelon", + "Pacific/Pohnpei", + "Pacific/Ponape", + "America/Dawson", + "America/Ensenada", + "America/Los_Angeles", + "America/Metlakatla", + "America/Santa_Isabel", + "America/Tijuana", + "America/Vancouver", + "America/Whitehorse", + "Canada/Pacific", + "Canada/Yukon", + "Mexico/BajaNorte", + "PST8PDT", + "Pacific/Pitcairn", + "US/Pacific", + "Pacific/Palau", + "America/Asuncion", + "Asia/Qyzylorda", + "Indian/Reunion", + "Antarctica/Rothera", + "Asia/Sakhalin", + "Europe/Samara", + "Africa/Johannesburg", + "Africa/Maseru", + "Africa/Mbabane", + "Pacific/Guadalcanal", + "Indian/Mahe", + "Asia/Singapore", + "Singapore", + "Asia/Srednekolymsk", + "America/Paramaribo", + "Pacific/Midway", + "Pacific/Pago_Pago", + "Pacific/Samoa", + "US/Samoa", + "Antarctica/Syowa", + "Pacific/Tahiti", + "Indian/Kerguelen", + "Asia/Dushanbe", + "Pacific/Fakaofo", + "Asia/Dili", + "Asia/Ashgabat", + "Asia/Ashkhabad", + "Pacific/Tongatapu", + "Pacific/Funafuti", + "Etc/UCT", + "UCT", + "Asia/Ulaanbaatar", + "Asia/Ulan_Bator", + "Antarctica/Troll", + "Etc/UTC", + "Etc/Universal", + "Etc/Zulu", + "UTC", + "Universal", + "Zulu", + "America/Montevideo", + "Asia/Samarkand", + "Asia/Tashkent", + "America/Caracas", + "Asia/Ust-Nera", + "Asia/Vladivostok", + "Antarctica/Vostok", + "Pacific/Efate", + "Pacific/Wake", + "Africa/Windhoek", + "Africa/Bangui", + "Africa/Brazzaville", + "Africa/Douala", + "Africa/Kinshasa", + "Africa/Lagos", + "Africa/Libreville", + "Africa/Luanda", + "Africa/Malabo", + "Africa/Ndjamena", + "Africa/Niamey", + "Africa/Porto-Novo", + "Africa/Casablanca", + "Africa/El_Aaiun", + "Atlantic/Canary", + "Atlantic/Faeroe", + "Atlantic/Faroe", + "Atlantic/Madeira", + "Europe/Lisbon", + "Portugal", + "WET", + "Pacific/Wallis", + "America/Godthab", + "Asia/Jakarta", + "Asia/Pontianak", + "Asia/Jayapura", + "Asia/Makassar", + "Asia/Ujung_Pandang", + "Pacific/Apia", + "Asia/Kashgar", + "Asia/Urumqi", + "Asia/Khandyga", + "Asia/Yakutsk", + "Asia/Yekaterinburg", +} + +// These example values must use the reference time "Mon Jan 2 15:04:05 MST 2006" +// as described at https://gobyexample.com/time-formatting-parsing +const ( + BaseDateFormat = "2006-01-02" + TimeFormat = "15:04:05" + MonthFormat = "January" + YearFormat = "2006" + DayFormat = "Monday" + DayOfMonthFormat = "_2" + TimePeriodFormat = "PM" +) + +// A DateTimer contains random Time generators, returning time string in certain particular format +type DateTimer interface { + UnixTime(v reflect.Value) (any, error) + Date(v reflect.Value) (any, error) + Time(v reflect.Value) (any, error) + MonthName(v reflect.Value) (any, error) + Year(v reflect.Value) (any, error) + DayOfWeek(v reflect.Value) (any, error) + DayOfMonth(v reflect.Value) (any, error) + Timestamp(v reflect.Value) (any, error) + Century(v reflect.Value) (any, error) + TimeZone(v reflect.Value) (any, error) + TimePeriod(v reflect.Value) (any, error) +} + +// GetDateTimer returns a new DateTimer interface of DateTime +func GetDateTimer() DateTimer { + date := &DateTime{} + return date +} + +// DateTime struct +type DateTime struct { +} + +func (d DateTime) unixtime() int64 { + return RandomUnixTime() +} + +// UnixTime get unix time +func (d DateTime) UnixTime(v reflect.Value) (any, error) { + kind := v.Kind() + var val int64 + if kind == reflect.Int64 { + val = d.unixtime() + } else { + val = 0 + } + + return val, nil +} + +// UnixTime get unix time randomly +func UnixTime(opts ...options.OptionFunc) int64 { + return singleFakeData(UnixTimeTag, func() any { + datetime := DateTime{} + return datetime.unixtime() + }, opts...).(int64) +} + +func (d DateTime) date() string { + return time.Unix(RandomUnixTime(), 0).Format(BaseDateFormat) +} + +// Date formats DateTime using example BaseDateFormat const +func (d DateTime) Date(v reflect.Value) (any, error) { + return d.date(), nil +} + +// Date get fake date in string randomly +func Date(opts ...options.OptionFunc) string { + return singleFakeData(DATE, func() any { + datetime := DateTime{} + return datetime.date() + }, opts...).(string) +} + +func (d DateTime) time() string { + return time.Unix(RandomUnixTime(), 0).Format(TimeFormat) +} + +// Time formats DateTime using example Time const +func (d DateTime) Time(v reflect.Value) (any, error) { + return d.time(), nil +} + +// TimeString get time randomly in string format +func TimeString(opts ...options.OptionFunc) string { + return singleFakeData(TIME, func() any { + datetime := DateTime{} + return datetime.time() + }, opts...).(string) +} + +func (d DateTime) monthName() string { + return time.Unix(RandomUnixTime(), 0).Format(MonthFormat) +} + +// MonthName formats DateTime using example Month const +func (d DateTime) MonthName(v reflect.Value) (any, error) { + return d.monthName(), nil +} + +// MonthName get month name randomly in string format +func MonthName(opts ...options.OptionFunc) string { + return singleFakeData(MonthNameTag, func() any { + datetime := DateTime{} + return datetime.monthName() + }, opts...).(string) +} + +func (d DateTime) year() string { + return time.Unix(RandomUnixTime(), 0).Format(YearFormat) +} + +// Year formats DateTime using example Year const +func (d DateTime) Year(v reflect.Value) (any, error) { + return d.year(), nil +} + +// YearString get year randomly in string format +func YearString(opts ...options.OptionFunc) string { + return singleFakeData(YEAR, func() any { + datetime := DateTime{} + return datetime.year() + }, opts...).(string) +} + +func (d DateTime) dayOfWeek() string { + return time.Unix(RandomUnixTime(), 0).Format(DayFormat) +} + +// DayOfWeek formats DateTime using example Day const +func (d DateTime) DayOfWeek(v reflect.Value) (any, error) { + return d.dayOfWeek(), nil +} + +// DayOfWeek get day of week randomly in string format +func DayOfWeek(opts ...options.OptionFunc) string { + return singleFakeData(DayOfWeekTag, func() any { + datetime := DateTime{} + return datetime.dayOfWeek() + }, opts...).(string) +} + +func (d DateTime) dayOfMonth() string { + return time.Unix(RandomUnixTime(), 0).Format(DayOfMonthFormat) +} + +// DayOfMonth formats DateTime using example DayOfMonth const +func (d DateTime) DayOfMonth(v reflect.Value) (any, error) { + return d.dayOfMonth(), nil +} + +// DayOfMonth get month randomly in string format +func DayOfMonth(opts ...options.OptionFunc) string { + return singleFakeData(DayOfMonthTag, func() any { + datetime := DateTime{} + return datetime.dayOfMonth() + }, opts...).(string) +} + +func (d DateTime) timestamp() string { + return time.Unix(RandomUnixTime(), 0).Format(fmt.Sprintf("%s %s", BaseDateFormat, TimeFormat)) +} + +// Timestamp formats DateTime using example Timestamp const +func (d DateTime) Timestamp(v reflect.Value) (any, error) { + return d.timestamp(), nil +} + +// Timestamp get timestamp randomly in string format: 2006-01-02 15:04:05 +func Timestamp(opts ...options.OptionFunc) string { + return singleFakeData(TIMESTAMP, func() any { + datetime := DateTime{} + return datetime.timestamp() + }, opts...).(string) +} + +func (d DateTime) century() string { + return randomElementFromSliceString(century) +} + +// Century returns a random century +func (d DateTime) Century(v reflect.Value) (any, error) { + return d.century(), nil +} + +// Century get century randomly in string +func Century(opts ...options.OptionFunc) string { + return singleFakeData(CENTURY, func() any { + datetime := DateTime{} + return datetime.century() + }, opts...).(string) +} + +func (d DateTime) timezone() string { + return randomElementFromSliceString(timezones) +} + +// TimeZone returns a random timezone +func (d DateTime) TimeZone(v reflect.Value) (any, error) { + return d.timezone(), nil +} + +// Timezone get timezone randomly in string +func Timezone(opts ...options.OptionFunc) string { + return singleFakeData(TIMEZONE, func() any { + datetime := DateTime{} + return datetime.timezone() + }, opts...).(string) +} + +func (d DateTime) period() string { + return time.Unix(RandomUnixTime(), 0).Format(TimePeriodFormat) +} + +// TimePeriod formats DateTime using example TimePeriod const +func (d DateTime) TimePeriod(v reflect.Value) (any, error) { + return d.period(), nil +} + +// Timeperiod get timeperiod randomly in string (AM/PM) +func Timeperiod(opts ...options.OptionFunc) string { + return singleFakeData(TimePeriodTag, func() any { + datetime := DateTime{} + return datetime.period() + }, opts...).(string) +} + +// RandomUnixTime is a helper function returning random Unix time +func RandomUnixTime() int64 { + return rand.Int63n(time.Now().Unix()) +} diff --git a/vendor/github.com/go-faker/faker/v4/faker.go b/vendor/github.com/go-faker/faker/v4/faker.go new file mode 100644 index 0000000..c0fe47b --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/faker.go @@ -0,0 +1,1520 @@ +package faker + +// Faker is a simple fake data generator for your own struct. +// Save your time, and Fake your data for your testing now. +import ( + cryptorand "crypto/rand" + "errors" + "fmt" + mathrand "math/rand" + "reflect" + "regexp" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + fakerErrors "github.com/go-faker/faker/v4/pkg/errors" + "github.com/go-faker/faker/v4/pkg/interfaces" + "github.com/go-faker/faker/v4/pkg/options" + "github.com/go-faker/faker/v4/pkg/slice" +) + +var ( + // Unique values are kept in memory so the generator retries if the value already exists + uniqueValues = &sync.Map{} +) + +// Supported tags +const ( + letterIdxBits = 6 // 6 bits to represent a letter index + letterIdxMask = 1< 0 + return reflect.ValueOf(val), nil + + case reflect.Uint: + return reflect.ValueOf(uint(randomInteger(opts))), nil + + case reflect.Uint8: + return reflect.ValueOf(uint8(randomInteger(opts))), nil + + case reflect.Uint16: + return reflect.ValueOf(uint16(randomInteger(opts))), nil + + case reflect.Uint32: + return reflect.ValueOf(uint32(randomInteger(opts))), nil + + case reflect.Uint64: + return reflect.ValueOf(uint64(randomInteger(opts))), nil + + case reflect.Map: + length := randomSliceAndMapSize(*opts) + if opts.SetSliceMapNilIfLenZero && length == 0 { + return reflect.Zero(t), nil + } + v := reflect.MakeMap(t) + innerOpts := opts.Nested() + for range length { + keyInstance := reflect.New(t.Key()).Elem().Interface() + key, err := getFakedValue(keyInstance, &innerOpts) + if err != nil { + return reflect.Value{}, err + } + + valueInstance := reflect.New(t.Elem()).Elem().Interface() + val, err := getFakedValue(valueInstance, &innerOpts) + if err != nil { + return reflect.Value{}, err + } + + keyIsZero := reflect.ValueOf(key).IsZero() + valIsZero := reflect.ValueOf(val).IsZero() + + if keyIsZero || valIsZero { + continue + } + key = key.Convert(t.Key()) + val = val.Convert(v.Type().Elem()) + v.SetMapIndex(key, val) + } + return v, nil + default: + err := fmt.Errorf("no support for kind %+v", t) + return reflect.Value{}, err + } + +} + +func getFakedValueForStruct(item any, t reflect.Type, opts *options.Options) (reflect.Value, error) { + if structTypeProvider, f := opts.StructTypeProviders[t]; f { + ft, err := structTypeProvider() + return reflect.ValueOf(ft), err + } + 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 { + opts.MaxFieldDepthOption-- + defer func() { opts.MaxFieldDepthOption++ }() + } + retry := 0 // error if cannot generate unique value after maxRetry tries + for i := 0; i < v.NumField(); i++ { + if !v.Field(i).CanSet() { + continue // to avoid panic to set on unexported field in struct + } + + if _, ok := opts.IgnoreFields[t.Field(i).Name]; ok { + continue + } + + if opts.OnlyZeroFields && !originalDataVal.Field(i).IsZero() { + v.Field(i).Set(originalDataVal.Field(i)) + continue + } + + if p, ok := opts.FieldProviders[t.Field(i).Name]; ok { + val, err := p() + if err != nil { + return reflect.Value{}, fmt.Errorf("custom provider for field %s: %w", t.Field(i).Name, err) + } + v.Field(i).Set(reflect.ValueOf(val)) + continue + } + + 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)) + if err != nil { + return reflect.Value{}, err + } + if zero { + err := setDataWithTag(v.Field(i).Addr(), tags.fieldType, *opts) + if err != nil { + return reflect.Value{}, err + } + continue + } + v.Field(i).Set(reflect.ValueOf(item).Field(i)) + case tags.fieldType == "": + val, err := getFakedValue(v.Field(i).Interface(), opts) + if err != nil { + return reflect.Value{}, err + } + + if v.Field(i).CanSet() { + if !reflect.ValueOf(val).IsZero() && val.CanConvert(v.Field(i).Type()) { + val = val.Convert(v.Field(i).Type()) + v.Field(i).Set(val) + } + + } + case tags.fieldType == SKIP: + data := originalDataVal.Field(i).Interface() + if v.CanSet() && data != nil { + v.Field(i).Set(reflect.ValueOf(data)) + } + default: + err := setDataWithTag(v.Field(i).Addr(), tags.fieldType, *opts) + if err != nil { + return reflect.Value{}, err + } + } + + if tags.unique { + if retry >= maxRetry { + return reflect.Value{}, fmt.Errorf(fakerErrors.ErrUniqueFailure, reflect.TypeOf(item).Field(i).Name) + } + value := v.Field(i).Interface() + uniqueVal, _ := uniqueValues.Load(tags.fieldType) + uniqueValArr, _ := uniqueVal.([]any) + if slice.ContainsValue(uniqueValArr, value) { // Retry if unique value already found + i-- + retry++ + continue + } + retry = 0 + uniqueValues.Store(tags.fieldType, append(uniqueValArr, value)) + } else { + retry = 0 + } + + } + // 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 +} + +func isZero(field reflect.Value) (bool, error) { + if field.Kind() == reflect.Map { + return field.Len() == 0, nil + } + + for _, kind := range []reflect.Kind{reflect.Struct, reflect.Slice, reflect.Array} { + if kind == field.Kind() { + return false, fmt.Errorf("keep not allowed on struct") + } + } + return reflect.Zero(field.Type()).Interface() == field.Interface(), nil +} + +func decodeTags(typ reflect.Type, i int, tagName string) structTag { + tagField := typ.Field(i).Tag.Get(tagName) + tags := strings.Split(tagField, ",") + + keepOriginal := false + 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 + continue + } else if tag == unique { + 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 { + if ptag == ONEOF { + res = append(res, tags...) + } else { + res = append(res, tag) + } + delete(pMap, ptag) + } + } + // custom,keep,unique + if len(res) < 1 { + if !keepOriginal && !uni { + res = append(res, tags...) + } + } + + return structTag{ + fieldType: strings.Join(res, ","), + unique: uni, + keepOriginal: keepOriginal, + } +} + +type structTag struct { + 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 { + if v.Kind() != reflect.Pointer { + return errors.New(fakerErrors.ErrValueNotPtr) + } + v = reflect.Indirect(v) + switch v.Kind() { + case reflect.Pointer: + if _, exist := mapperTag.Load(tag); !exist { + newv := reflect.New(v.Type().Elem()) + if err := setDataWithTag(newv, tag, opt); err != nil { + return err + } + v.Set(newv) + return nil + } + if _, def := defaultTag.Load(tag); !def { + tagFunc, ok := mapperTag.Load(tag) + if !ok { + return fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + res, err := tagFunc(v) + if err != nil { + return err + } + v.Set(reflect.ValueOf(res)) + return nil + } + + t := v.Type() + newv := reflect.New(t.Elem()) + tagFunc, ok := mapperTag.Load(tag) + if !ok { + return fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + res, err := tagFunc(newv.Elem()) + if err != nil { + return err + } + rval := reflect.ValueOf(res) + newv.Elem().Set(rval) + v.Set(newv) + return nil + case reflect.String: + return userDefinedString(v, tag, opt) + case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8, + reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: + return userDefinedNumber(v, tag) + case reflect.Slice, reflect.Array: + return userDefinedArray(v, tag, opt) + case reflect.Map: + return userDefinedMap(v, tag, opt) + default: + tagFunc, ok := mapperTag.Load(tag) + if !ok { + return fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + res, err := tagFunc(v) + if err != nil { + return err + } + v.Set(reflect.ValueOf(res)) + } + return nil +} + +func userDefinedMap(v reflect.Value, tag string, opt options.Options) error { + if tagFunc, ok := mapperTag.Load(tag); ok { + res, err := tagFunc(v) + if err != nil { + return err + } + + v.Set(reflect.ValueOf(res)) + return nil + } + + length := randomSliceAndMapSize(opt) + if opt.SetSliceMapNilIfLenZero && length == 0 { + v.Set(reflect.Zero(v.Type())) + return nil + } + innerOpt := opt.Nested() + definedMap := reflect.MakeMap(v.Type()) + for range length { + key, err := getValueWithTag(v.Type().Key(), tag, innerOpt) + if err != nil { + return err + } + val, err := getValueWithTag(v.Type().Elem(), tag, innerOpt) + if err != nil { + return err + } + definedMap.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(val)) + } + v.Set(definedMap) + return nil +} + +func getValueWithTag(t reflect.Type, tag string, opt options.Options) (any, error) { + switch t.Kind() { + case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8, + reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: + res, err := extractNumberFromTag(tag, t) + if err != nil { + return nil, err + } + return res, nil + case reflect.String: + res, err := extractStringFromTag(tag, opt) + if err != nil { + return nil, err + } + return res, nil + default: + return 0, errors.New(fakerErrors.ErrUnknownType) + } +} + +func getNumberWithBoundary(t reflect.Type, boundary interfaces.RandomIntegerBoundary) (any, error) { + switch t.Kind() { + case reflect.Uint: + return uint(randomIntegerWithBoundary(boundary)), nil + case reflect.Uint8: + return uint8(randomIntegerWithBoundary(boundary)), nil + case reflect.Uint16: + return uint16(randomIntegerWithBoundary(boundary)), nil + case reflect.Uint32: + return uint32(randomIntegerWithBoundary(boundary)), nil + case reflect.Uint64: + return uint64(randomIntegerWithBoundary(boundary)), nil + case reflect.Int: + return randomIntegerWithBoundary(boundary), nil + case reflect.Int8: + return int8(randomIntegerWithBoundary(boundary)), nil + case reflect.Int16: + return int16(randomIntegerWithBoundary(boundary)), nil + case reflect.Int32: + return int32(randomIntegerWithBoundary(boundary)), nil + case reflect.Int64: + return int64(randomIntegerWithBoundary(boundary)), nil + default: + return nil, errors.New(fakerErrors.ErrNotSupportedTypeForTag) + } +} + +func getValueWithNoTag(t reflect.Type, opt options.Options) (any, error) { + switch t.Kind() { + case reflect.Int, reflect.Int32, reflect.Int64, reflect.Int8, reflect.Int16, reflect.Uint, reflect.Uint8, + reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: + boundary := interfaces.RandomIntegerBoundary{ + Start: opt.RandomIntegerBoundary.Start, + End: opt.RandomIntegerBoundary.End} + res, err := getNumberWithBoundary(t, boundary) + if err != nil { + return nil, err + } + return res, nil + case reflect.String: + res, err := randomString(opt.RandomStringLength, opt) + if err != nil { + return nil, err + } + return res, nil + default: + return 0, errors.New(fakerErrors.ErrUnknownType) + } +} + +func userDefinedArray(v reflect.Value, tag string, opt options.Options) error { + tagFunc, tagExists := mapperTag.Load(tag) + if tagExists { + res, err := tagFunc(v) + if err != nil { + return err + } + v.Set(reflect.ValueOf(res)) + return nil + } + sliceLen, err := extractSliceLengthFromTag(tag, opt) + if err != nil { + return err + } + + if opt.SetSliceMapNilIfLenZero && sliceLen == 0 { + v.Set(reflect.Zero(v.Type())) + return nil + } + //remove slice_len from tag string to avoid extra logic in downstream function + tag = findSliceLenReg.ReplaceAllString(tag, "") + array := reflect.MakeSlice(v.Type(), sliceLen, sliceLen) + innerOpt := opt.Nested() + for i := 0; i < array.Len(); i++ { + k := v.Type().Elem().Kind() + if k == reflect.Pointer || k == reflect.Struct { + res, err := getFakedValue(array.Index(i).Interface(), &innerOpt) + if err != nil { + return err + } + if res.Kind() == reflect.Invalid { + return fmt.Errorf("got invalid reflect value") + } + array.Index(i).Set(res) + continue + } + if tag == "" { + res, err := getValueWithNoTag(v.Type().Elem(), innerOpt) + if err != nil { + return err + } + array.Index(i).Set(reflect.ValueOf(res)) + continue + } + + res, err := getValueWithTag(v.Type().Elem(), tag, innerOpt) + if err != nil { + return err + } + array.Index(i).Set(reflect.ValueOf(res)) + } + v.Set(array) + return nil +} + +func userDefinedString(v reflect.Value, tag string, opt options.Options) error { + var res any + var err error + + if tagFunc, ok := mapperTag.Load(tag); ok { + res, err = tagFunc(v) + if err != nil { + return err + } + } else { + res, err = extractStringFromTag(tag, opt) + if err != nil { + return err + } + } + if res == nil { + return fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + val, _ := res.(string) + v.SetString(val) + return nil +} + +func userDefinedNumber(v reflect.Value, tag string) error { + var res any + var err error + + if tagFunc, ok := mapperTag.Load(tag); ok { + res, err = tagFunc(v) + if err != nil { + return err + } + } else { + res, err = extractNumberFromTag(tag, v.Type()) + if err != nil { + return err + } + } + if res == nil { + return fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + + if v.CanSet() && v.CanConvert(v.Type()) { + v.Set(reflect.ValueOf(res).Convert(v.Type())) + } + return nil +} + +// extractSliceLengthFromTag checks if the sliceLength tag 'slice_len' is set, if so, returns its value, else return a random length +func extractSliceLengthFromTag(tag string, opt options.Options) (int, error) { + if strings.Contains(tag, SliceLength) { + lenParts := strings.Split(findSliceLenReg.FindString(tag), Equals) + if len(lenParts) != 2 { + return 0, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, tag) + } + sliceLen, err := strconv.Atoi(lenParts[1]) + if err != nil { + return 0, fmt.Errorf("the given sliceLength has to be numeric, tag: %s", tag) + } + if sliceLen < 0 { + return 0, fmt.Errorf("slice length can not be negative, tag: %s", tag) + } + return sliceLen, nil + } + + return randomSliceAndMapSize(opt), nil //Returns random slice length if the sliceLength tag isn't set +} + +func extractStringFromTag(tag string, opts options.Options) (any, error) { + var err error + strlen := opts.RandomStringLength + strlng := opts.StringLanguage + isOneOfTag := strings.Contains(tag, ONEOF) + if !strings.Contains(tag, Length) && !strings.Contains(tag, Language) && !isOneOfTag { + return nil, fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + if strings.Contains(tag, Length) { + lenParts := strings.Split(findLenReg.FindString(tag), Equals) + if len(lenParts) != 2 { + return nil, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, tag) + } + strlen, _ = strconv.Atoi(lenParts[1]) + } + if strings.Contains(tag, Language) { + strlng, err = extractLangFromTag(tag) + if err != nil { + return nil, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, tag) + } + } + if isOneOfTag { + var args []string + args, err = fetchOneOfArgsFromTag(tag) + if err != nil { + return nil, err + } + toRet := args[rand.Intn(len(args))] + return strings.TrimSpace(toRet), nil + } + + copyOption := opts + copyOption.StringLanguage = strlng + res, err := randomString(strlen, copyOption) + return res, err +} + +func extractLangFromTag(tag string) (*interfaces.LangRuneBoundary, error) { + text := findLangReg.FindString(tag) + texts := strings.Split(text, Equals) + if len(texts) != 2 { + return nil, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, text) + } + switch strings.ToLower(texts[1]) { + case "eng": + return &interfaces.LangENG, nil + case "rus": + return &interfaces.LangRUS, nil + case "chi": + return &interfaces.LangCHI, nil + case "jpn": + return &interfaces.LangJPN, nil + case "kor": + return &interfaces.LangKOR, nil + case "emj": + return &interfaces.EmotEMJ, nil + default: + return &interfaces.LangENG, nil + } +} + +func extractNumberFromTag(tag string, t reflect.Type) (any, error) { + hasOneOf := strings.Contains(tag, ONEOF) + hasBoundaryStart := strings.Contains(tag, BoundaryStart) + hasBoundaryEnd := strings.Contains(tag, BoundaryEnd) + usingOneOfTag := hasOneOf && (!hasBoundaryStart && !hasBoundaryEnd) + usingBoundariesTags := !hasOneOf && (hasBoundaryStart && hasBoundaryEnd) + if !usingOneOfTag && !usingBoundariesTags { + return nil, fmt.Errorf(fakerErrors.ErrTagNotSupported, tag) + } + + // handling oneof tag + if usingOneOfTag { + args, err := fetchOneOfArgsFromTag(tag) + if err != nil { + return nil, err + } + switch t.Kind() { + case reflect.Float64: + { + toRet, err := extractFloat64FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(float64), nil + } + case reflect.Float32: + { + toRet, err := extractFloat32FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(float32), nil + } + case reflect.Int64: + { + toRet, err := extractInt64FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(int64), nil + } + case reflect.Int32: + { + toRet, err := extractInt32FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(int32), nil + } + case reflect.Int16: + { + toRet, err := extractInt16FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(int16), nil + } + case reflect.Int8: + { + toRet, err := extractInt8FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(int8), nil + } + case reflect.Int: + { + toRet, err := extractIntFromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(int), nil + } + case reflect.Uint64: + { + toRet, err := extractUint64FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(uint64), nil + } + case reflect.Uint32: + { + toRet, err := extractUint32FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(uint32), nil + } + case reflect.Uint16: + { + toRet, err := extractUint16FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(uint16), nil + } + case reflect.Uint8: + { + toRet, err := extractUint8FromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(uint8), nil + } + case reflect.Uint: + { + toRet, err := extractUintFromTagArgs(args) + if err != nil { + return nil, err + } + return toRet.(uint), nil + } + default: + { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedNumberType) + } + } + } + + // handling boundary tags + valuesStr := strings.Split(tag, comma) + if len(valuesStr) != 2 { + return nil, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, tag) + } + + // TODO(Xaspy): When Golang provides generics, we will be able to make this method simpler and more beautiful. + if t.Kind() == reflect.Float64 || t.Kind() == reflect.Float32 { + startBoundary, err := extractFloatFromText(valuesStr[0]) + if err != nil { + return nil, err + } + endBoundary, err := extractFloatFromText(valuesStr[1]) + if err != nil { + return nil, err + } + boundary := interfaces.RandomFloatBoundary{Start: startBoundary, End: endBoundary} + switch t.Kind() { + case reflect.Float32: + return float32(randomFloatWithBoundary(boundary)), nil + case reflect.Float64: + return randomFloatWithBoundary(boundary), nil + } + } + + startBoundary, err := extractIntFromText(valuesStr[0]) + if err != nil { + return nil, err + } + endBoundary, err := extractIntFromText(valuesStr[1]) + if err != nil { + return nil, err + } + boundary := interfaces.RandomIntegerBoundary{Start: startBoundary, End: endBoundary} + return getNumberWithBoundary(t, boundary) +} + +func extractIntFromText(text string) (int, error) { + text = strings.TrimSpace(text) + texts := strings.Split(text, Equals) + if len(texts) != 2 { + return 0, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, text) + } + return strconv.Atoi(texts[1]) +} + +func extractFloatFromText(text string) (float64, error) { + text = strings.TrimSpace(text) + texts := strings.Split(text, Equals) + if len(texts) != 2 { + return 0, fmt.Errorf(fakerErrors.ErrWrongFormattedTag, text) + } + return strconv.ParseFloat(texts[1], 64) +} + +func fetchOneOfArgsFromTag(tag string) ([]string, error) { + items := strings.Split(tag, colon) + argsList := items[1:] + if len(argsList) != 1 { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + if strings.Contains(argsList[0], ",,") { + return nil, fmt.Errorf("%s", fakerErrors.ErrDuplicateSeparator) + } + if argsList[0] == "" { + return nil, fmt.Errorf("%s", fakerErrors.ErrNotEnoughTagArguments) + } + args := strings.Split(argsList[0], comma) + if len(args) < 1 { + return nil, fmt.Errorf("%s", fakerErrors.ErrNotEnoughTagArguments) + } + return args, nil +} + +func randomString(n int, fakerOpt options.Options) (string, error) { + b := make([]rune, 0) + set := make(map[rune]struct{}) + if fakerOpt.StringLanguage.Exclude != nil { + for _, s := range fakerOpt.StringLanguage.Exclude { + set[s] = struct{}{} + } + } + + counter := 0 + for i := 0; i < n; { + randRune := rune(rand.Intn(int(fakerOpt.StringLanguage.End-fakerOpt.StringLanguage.Start)) + int(fakerOpt.StringLanguage.Start)) + for slice.ContainsRune(set, randRune) { + if counter++; counter >= fakerOpt.MaxGenerateStringRetries { + return "", errors.New("max number of string generation retries exhausted") + } + randRune = rune(rand.Intn(int(fakerOpt.StringLanguage.End-fakerOpt.StringLanguage.Start)) + int(fakerOpt.StringLanguage.Start)) + _, ok := set[randRune] + if !ok { + break + } + } + b = append(b, randRune) + i++ + } + + k := string(b) + return k, nil +} + +// randomIntegerWithBoundary returns a random integer between input start and end boundary. [start, end) +func randomIntegerWithBoundary(boundary interfaces.RandomIntegerBoundary) int { + span := boundary.End - boundary.Start + if span <= 0 { + return boundary.Start + } + return rand.Intn(span) + boundary.Start +} + +// randomFloatWithBoundary returns a random float between input start and end boundary. [start, end) +func randomFloatWithBoundary(boundary interfaces.RandomFloatBoundary) float64 { + span := boundary.End - boundary.Start + if span <= 0 { + return boundary.Start + } + return boundary.Start + rand.Float64()*span +} + +// randomInteger returns a random integer between start and end boundary. [start, end) +func randomInteger(opt *options.Options) int { + if opt == nil { + opt = options.DefaultOption() + } + + return randomIntegerWithBoundary(*opt.RandomIntegerBoundary) +} + +// randomFloat returns a random float between start and end boundary. [start, end) +func randomFloat(opt *options.Options) float64 { + if opt == nil { + opt = options.DefaultOption() + } + + return randomFloatWithBoundary(*opt.RandomFloatBoundary) +} + +// randomSliceAndMapSize returns a random integer between [min,max). If testRandZero is set, returns 0. +// When SliceDepth > 0 and RandomNestedMaxSliceSize is configured, the nested sizes are used instead +// to prevent exponential memory growth from large outer sizes propagating to all nested slices. +func randomSliceAndMapSize(opt options.Options) int { + if opt.SetSliceMapRandomToZero { + return 0 + } + maxSize := opt.RandomMaxSliceSize + minSize := opt.RandomMinSliceSize + if opt.IsNested() && opt.RandomNestedMaxSliceSize > 0 { + maxSize = opt.RandomNestedMaxSliceSize + minSize = opt.RandomNestedMinSliceSize + } + r := max(maxSize-minSize, 1) + return minSize + rand.Intn(r) +} + +func randomElementFromSliceString(s []string) string { + return s[rand.Int()%len(s)] +} +func randomStringNumber(n int) string { + b := make([]byte, n) + for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; { + if remain == 0 { + cache, remain = rand.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(numberBytes) { + b[i] = numberBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + + return string(b) +} + +// RandomInt Get three parameters , only first mandatory and the rest are optional +// (minimum_int, maximum_int, count) +// +// If only set one parameter : An integer greater than minimum_int will be returned +// If only set two parameters : All integers between minimum_int and maximum_int will be returned, in a random order. +// If three parameters: `count` integers between minimum_int and maximum_int will be returned. +func RandomInt(parameters ...int) (p []int, err error) { + switch len(parameters) { + case 1: + minInt := parameters[0] + p = rand.Perm(minInt) + for i := range p { + p[i] += minInt + } + case 2: + minInt, maxInt := parameters[0], parameters[1] + p = rand.Perm(maxInt - minInt + 1) + + for i := range p { + p[i] += minInt + } + case 3: + minInt, maxInt := parameters[0], parameters[1] + count := parameters[2] + p = rand.Perm(maxInt - minInt + 1) + + for i := range p { + p[i] += minInt + } + if len(p) > count { + p = p[0:count] + } + default: + err = fmt.Errorf(fakerErrors.ErrMoreArguments, len(parameters)) + } + return p, err +} + +func generateUnique(dataType string, fn func() any) (any, error) { + for range maxRetry { + value := fn() + uniqueVal, _ := uniqueValues.Load(dataType) + uniqueValArr, _ := uniqueVal.([]any) + if !slice.ContainsValue(uniqueValArr, value) { // Retry if unique value already found + uniqueValues.Store(dataType, append(uniqueValArr, value)) + return value, nil + } + } + return reflect.Value{}, fmt.Errorf(fakerErrors.ErrUniqueFailure, dataType) +} + +func singleFakeData(dataType string, fn func() any, opts ...options.OptionFunc) any { + ops := initOption(opts...) + if ops.GenerateUniqueValues { + v, err := generateUnique(dataType, fn) + if err != nil { + panic(err) + } + return v + } + return fn() +} diff --git a/vendor/github.com/go-faker/faker/v4/internet.go b/vendor/github.com/go-faker/faker/v4/internet.go new file mode 100644 index 0000000..9f4357a --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/internet.go @@ -0,0 +1,302 @@ +package faker + +import ( + "fmt" + "net" + "reflect" + "strings" + + "github.com/go-faker/faker/v4/pkg/options" +) + +var tld = []string{"com", "biz", "info", "net", "org", "ru", "edu", "top"} +var urlFormats = []string{ + "http://www.%s/", + "https://www.%s/", + "http://%s/", + "https://%s/", + "http://www.%s/%s", + "https://www.%s/%s", + "http://%s/%s", + "https://%s/%s", + "http://%s/%s.html", + "https://%s/%s.html", + "http://%s/%s.php", + "https://%s/%s.php", + "http://%s/%s.jpg", + "https://%s/%s.jpg", + "http://%s/%s.webp", + "https://%s/%s.webp", + "http://%s/%s.js", + "https://%s/%s.js", + "http://%s/%s.css", + "https://%s/%s.css", + "http://%s/%s.svg", + "https://%s/%s.svg", +} + +// GetNetworker returns a new Networker interface of Internet +func GetNetworker(opts ...options.OptionFunc) Networker { + opt := options.BuildOptions(opts) + internet := &Internet{ + fakerOption: *opt, + } + return internet +} + +// Networker is logical layer for Internet +type Networker interface { + Email(v reflect.Value) (any, error) + MacAddress(v reflect.Value) (any, error) + DomainName(v reflect.Value) (any, error) + URL(v reflect.Value) (any, error) + UserName(v reflect.Value) (any, error) + IPv4(v reflect.Value) (any, error) + IPv6(v reflect.Value) (any, error) + Password(v reflect.Value) (any, error) + Jwt(v reflect.Value) (any, error) +} + +// Internet struct +type Internet struct { + fakerOption options.Options +} + +func (internet Internet) email() (string, error) { + var err error + var emailName, emailDomain string + if emailName, err = randomString(7, internet.fakerOption); err != nil { + return "", err + } + + if internet.fakerOption.CustomDomain != nil { + emailDomain = *internet.fakerOption.CustomDomain + } else { + randDomain, err := randomString(7, internet.fakerOption) + if err != nil { + return "", err + } + + emailDomain = randDomain + "." + randomElementFromSliceString(tld) + } + + return (emailName + "@" + emailDomain), nil +} + +// Email generates random email id +func (internet Internet) Email(v reflect.Value) (any, error) { + return internet.email() +} + +// Email get email randomly in string +func Email(opts ...options.OptionFunc) string { + return singleFakeData(EmailTag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + r, err := i.email() + if err != nil { + panic(err.Error()) + } + return r + }, opts...).(string) +} + +func (internet Internet) macAddress() string { + ip := make([]byte, 6) + for i := range 6 { + ip[i] = byte(rand.Intn(256)) + } + return net.HardwareAddr(ip).String() +} + +// MacAddress generates random MacAddress +func (internet Internet) MacAddress(v reflect.Value) (any, error) { + return internet.macAddress(), nil +} + +// MacAddress get mac address randomly in string +func MacAddress(opts ...options.OptionFunc) string { + return singleFakeData(MacAddressTag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + return i.macAddress() + }, opts...).(string) +} + +func (internet Internet) domainName() (string, error) { + domainPart, err := randomString(7, internet.fakerOption) + if err != nil { + return "", err + } + return (strings.ToLower(domainPart) + "." + randomElementFromSliceString(tld)), nil +} + +// DomainName generates random domain name +func (internet Internet) DomainName(v reflect.Value) (any, error) { + return internet.domainName() +} + +// DomainName get email domain name in string +func DomainName(opts ...options.OptionFunc) string { + return singleFakeData(DomainNameTag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + d, err := i.domainName() + if err != nil { + panic(err.Error()) + } + return d + }, opts...).(string) +} + +func (internet Internet) url() (string, error) { + format := randomElementFromSliceString(urlFormats) + countVerbs := strings.Count(format, "%s") + d, err := internet.domainName() + if err != nil { + return "", nil + } + if countVerbs == 1 { + return fmt.Sprintf(format, d), nil + } + u, err := internet.username() + if err != nil { + return "", err + } + return fmt.Sprintf(format, d, u), nil +} + +// URL generates random URL standardized in urlFormats const +func (internet Internet) URL(v reflect.Value) (any, error) { + return internet.url() +} + +// URL get Url randomly in string +func URL(opts ...options.OptionFunc) string { + return singleFakeData(URLTag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + u, err := i.url() + if err != nil { + panic(err.Error()) + } + return u + }, opts...).(string) +} + +func (internet Internet) username() (string, error) { + return randomString(7, internet.fakerOption) +} + +// UserName generates random username +func (internet Internet) UserName(v reflect.Value) (any, error) { + return internet.username() +} + +// Username get username randomly in string +func Username(opts ...options.OptionFunc) string { + return singleFakeData(UserNameTag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + u, err := i.username() + if err != nil { + panic(err.Error()) + } + return u + }, opts...).(string) +} + +func (internet Internet) ipv4() string { + size := 4 + ip := make([]byte, size) + for i := range size { + ip[i] = byte(rand.Intn(256)) + } + return net.IP(ip).To4().String() +} + +// IPv4 generates random IPv4 address +func (internet Internet) IPv4(v reflect.Value) (any, error) { + return internet.ipv4(), nil +} + +// IPv4 get IPv4 randomly in string +func IPv4(opts ...options.OptionFunc) string { + return singleFakeData(IPV4Tag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + return i.ipv4() + }, opts...).(string) +} + +func (internet Internet) ipv6() string { + size := 16 + ip := make([]byte, size) + for i := range size { + ip[i] = byte(rand.Intn(256)) + } + return net.IP(ip).To16().String() +} + +// IPv6 generates random IPv6 address +func (internet Internet) IPv6(v reflect.Value) (any, error) { + return internet.ipv6(), nil +} + +// IPv6 get IPv6 randomly in string +func IPv6(opts ...options.OptionFunc) string { + return singleFakeData(IPV6Tag, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + return i.ipv6() + }, opts...).(string) +} + +func (internet Internet) password() (string, error) { + return randomString(50, internet.fakerOption) +} + +// Password returns a hashed password +func (internet Internet) Password(v reflect.Value) (any, error) { + return internet.password() +} + +// Password get password randomly in string +func Password(opts ...options.OptionFunc) string { + return singleFakeData(PASSWORD, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + p, err := i.password() + if err != nil { + panic(err.Error()) + } + return p + }, opts...).(string) +} + +func (internet Internet) jwt() (string, error) { + element, err := randomString(40, internet.fakerOption) + sl := element[:] + if err != nil { + return "", err + } + return strings.Join([]string{sl, sl, sl}, "."), nil +} + +// Jwt returns a jwt-like random string in xxxx.yyyy.zzzz style +func (internet Internet) Jwt(v reflect.Value) (any, error) { + return internet.jwt() +} + +// Jwt get jwt-like string +func Jwt(opts ...options.OptionFunc) string { + return singleFakeData(JWT, func() any { + opt := options.BuildOptions(opts) + i := Internet{fakerOption: *opt} + p, err := i.jwt() + if err != nil { + panic(err.Error()) + } + return p + }, opts...).(string) +} diff --git a/vendor/github.com/go-faker/faker/v4/lorem.go b/vendor/github.com/go-faker/faker/v4/lorem.go new file mode 100644 index 0000000..a6f7a11 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/lorem.go @@ -0,0 +1,142 @@ +package faker + +import ( + "reflect" + "strings" + + "golang.org/x/text/cases" + "golang.org/x/text/language" + + "github.com/go-faker/faker/v4/pkg/options" +) + +var wordList = []string{ + "alias", "consequatur", "aut", "perferendis", "sit", "voluptatem", + "accusantium", "doloremque", "aperiam", "eaque", "ipsa", "quae", "ab", + "illo", "inventore", "veritatis", "et", "quasi", "architecto", + "beatae", "vitae", "dicta", "sunt", "explicabo", "aspernatur", "aut", + "odit", "aut", "fugit", "sed", "quia", "consequuntur", "magni", + "dolores", "eos", "qui", "ratione", "voluptatem", "sequi", "nesciunt", + "neque", "dolorem", "ipsum", "quia", "dolor", "sit", "amet", + "consectetur", "adipisci", "velit", "sed", "quia", "non", "numquam", + "eius", "modi", "tempora", "incidunt", "ut", "labore", "et", "dolore", + "magnam", "aliquam", "quaerat", "voluptatem", "ut", "enim", "ad", + "minima", "veniam", "quis", "nostrum", "exercitationem", "ullam", + "corporis", "nemo", "enim", "ipsam", "voluptatem", "quia", "voluptas", + "sit", "suscipit", "laboriosam", "nisi", "ut", "aliquid", "ex", "ea", + "commodi", "consequatur", "quis", "autem", "vel", "eum", "iure", + "reprehenderit", "qui", "in", "ea", "voluptate", "velit", "esse", + "quam", "nihil", "molestiae", "et", "iusto", "odio", "dignissimos", + "ducimus", "qui", "blanditiis", "praesentium", "laudantium", "totam", + "rem", "voluptatum", "deleniti", "atque", "corrupti", "quos", + "dolores", "et", "quas", "molestias", "excepturi", "sint", + "occaecati", "cupiditate", "non", "provident", "sed", "ut", + "perspiciatis", "unde", "omnis", "iste", "natus", "error", + "similique", "sunt", "in", "culpa", "qui", "officia", "deserunt", + "mollitia", "animi", "id", "est", "laborum", "et", "dolorum", "fuga", + "et", "harum", "quidem", "rerum", "facilis", "est", "et", "expedita", + "distinctio", "nam", "libero", "tempore", "cum", "soluta", "nobis", + "est", "eligendi", "optio", "cumque", "nihil", "impedit", "quo", + "porro", "quisquam", "est", "qui", "minus", "id", "quod", "maxime", + "placeat", "facere", "possimus", "omnis", "voluptas", "assumenda", + "est", "omnis", "dolor", "repellendus", "temporibus", "autem", + "quibusdam", "et", "aut", "consequatur", "vel", "illum", "qui", + "dolorem", "eum", "fugiat", "quo", "voluptas", "nulla", "pariatur", + "at", "vero", "eos", "et", "accusamus", "officiis", "debitis", "aut", + "rerum", "necessitatibus", "saepe", "eveniet", "ut", "et", + "voluptates", "repudiandae", "sint", "et", "molestiae", "non", + "recusandae", "itaque", "earum", "rerum", "hic", "tenetur", "a", + "sapiente", "delectus", "ut", "aut", "reiciendis", "voluptatibus", + "maiores", "doloribus", "asperiores", "repellat", +} + +// DataFaker generates randomized Words, Sentences and Paragraphs +type DataFaker interface { + Word(v reflect.Value) (any, error) + Sentence(v reflect.Value) (any, error) + Paragraph(v reflect.Value) (any, error) +} + +// GetLorem returns a new DataFaker interface of Lorem struct +func GetLorem() DataFaker { + lorem := &Lorem{} + return lorem +} + +// Lorem struct +type Lorem struct { +} + +func (l Lorem) word() string { + return randomElementFromSliceString(wordList) +} + +// Word returns a word from the wordList const +func (l Lorem) Word(v reflect.Value) (any, error) { + return l.word(), nil +} + +// Word get a word randomly in string +func Word(opts ...options.OptionFunc) string { + i := Lorem{} + return singleFakeData(WORD, func() any { + return i.word() + }, opts...).(string) +} + +func (l Lorem) sentence(sentence *strings.Builder) *strings.Builder { + r, _ := RandomInt(0, len(wordList)-1, 6) + size := len(r) + for key, val := range r { + if key == 0 { + sentence.WriteString(cases.Title(language.Und, cases.NoLower).String(wordList[val])) + } else { + sentence.WriteString(wordList[val]) + } + if key != size-1 { + sentence.WriteString(" ") + } + } + + sentence.WriteString(".") + return sentence +} + +// Sentence returns a sentence using the wordList const +func (l Lorem) Sentence(_ reflect.Value) (any, error) { + sentence := l.sentence(&strings.Builder{}) + return sentence.String(), nil +} + +// Sentence get a sentence randomly in string +func Sentence(opts ...options.OptionFunc) string { + i := Lorem{} + return singleFakeData(SENTENCE, func() any { + return i.sentence(&strings.Builder{}).String() + }, opts...).(string) +} + +func (l Lorem) paragraph() string { + paragraph := &strings.Builder{} + size := rand.Intn(10) + 1 + for i := range size { + l.sentence(paragraph) + if i != size-1 { + paragraph.WriteString(" ") + } + } + return paragraph.String() +} + +// Paragraph returns a series of sentences as a paragraph using the wordList const +func (l Lorem) Paragraph(v reflect.Value) (any, error) { + return l.paragraph(), nil +} + +// Paragraph get a paragraph randomly in string +func Paragraph(opts ...options.OptionFunc) string { + i := Lorem{} + return singleFakeData(PARAGRAPH, func() any { + return i.paragraph() + }, opts...).(string) +} diff --git a/vendor/github.com/go-faker/faker/v4/misc/addresses-us-1000.min.json b/vendor/github.com/go-faker/faker/v4/misc/addresses-us-1000.min.json new file mode 100644 index 0000000..e91bf62 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/misc/addresses-us-1000.min.json @@ -0,0 +1 @@ +{"addresses":[{"address1":"1745 T Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20020","coordinates":{"lat":38.867033,"lng":-76.979235}},{"address1":"6007 Applegate Lane","address2":"","city":"Louisville","state":"KY","postalCode":"40219","coordinates":{"lat":38.1343013,"lng":-85.6498512}},{"address1":"560 Penstock Drive","address2":"","city":"Grass Valley","state":"CA","postalCode":"95945","coordinates":{"lat":39.213076,"lng":-121.077583}},{"address1":"150 Carter Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.76556000000001,"lng":-72.473091}},{"address1":"2721 Lindsay Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40206","coordinates":{"lat":38.263793,"lng":-85.700243}},{"address1":"18 Densmore Drive","address2":"","city":"Essex","state":"VT","postalCode":"05452","coordinates":{"lat":44.492953,"lng":-73.101883}},{"address1":"637 Britannia Drive","address2":"","city":"Vallejo","state":"CA","postalCode":"94591","coordinates":{"lat":38.10476999999999,"lng":-122.193849}},{"address1":"5601 West Crocus Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.6152469,"lng":-112.179737}},{"address1":"5403 Illinois Avenue","address2":"","city":"Nashville","state":"TN","postalCode":"37209","coordinates":{"lat":36.157077,"lng":-86.853827}},{"address1":"8821 West Myrtle Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85305","coordinates":{"lat":33.5404296,"lng":-112.2488391}},{"address1":"2203 7th Street Road","address2":"","city":"Louisville","state":"KY","postalCode":"40208","coordinates":{"lat":38.218107,"lng":-85.779006}},{"address1":"6463 Vrain Street","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.814056,"lng":-105.046913}},{"address1":"87 Horseshoe Drive","address2":"","city":"West Windsor","state":"VT","postalCode":"05037","coordinates":{"lat":43.4731793,"lng":-72.4967532}},{"address1":"60 Desousa Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7409259,"lng":-72.5619104}},{"address1":"4 Old Colony Way","address2":"","city":"Yarmouth","state":"MA","postalCode":"02664","coordinates":{"lat":41.697168,"lng":-70.189992}},{"address1":"314 South 17th Street","address2":"","city":"Nashville","state":"TN","postalCode":"37206","coordinates":{"lat":36.1719075,"lng":-86.740228}},{"address1":"1649 Timberridge Court","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.084563,"lng":-94.206082}},{"address1":"5461 West Shades Valley Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.296422,"lng":-86.34280299999999}},{"address1":"629 Debbie Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37076","coordinates":{"lat":36.208114,"lng":-86.58621199999999}},{"address1":"22572 Toreador Drive","address2":"","city":"Salinas","state":"CA","postalCode":"93908","coordinates":{"lat":36.602449,"lng":-121.699071}},{"address1":"3034 Mica Street","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0807929,"lng":-94.2066449}},{"address1":"3729 East Mission Boulevard","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0919353,"lng":-94.10654219999999}},{"address1":"5114 Greentree Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.0618539,"lng":-86.738508}},{"address1":"3466 Southview Avenue","address2":"","city":"Montgomery","state":"AL","postalCode":"36111","coordinates":{"lat":32.341227,"lng":-86.2846859}},{"address1":"1513 Cathy Street","address2":"","city":"Savannah","state":"GA","postalCode":"31415","coordinates":{"lat":32.067416,"lng":-81.125331}},{"address1":"600 West 19th Avenue","address2":"APT B","city":"Anchorage","state":"AK","postalCode":"99503","coordinates":{"lat":61.203115,"lng":-149.894107}},{"address1":"1208 Elkader Court North","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.080049,"lng":-86.60116099999999}},{"address1":"210 Green Road","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.7909099,"lng":-72.51195129999999}},{"address1":"49548 Road 200","address2":"","city":"O'Neals","state":"CA","postalCode":"93645","coordinates":{"lat":37.153463,"lng":-119.648192}},{"address1":"81 Seaton Place Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.9149499,"lng":-77.01170259999999}},{"address1":"1267 Martin Street","address2":"#203","city":"Nashville","state":"TN","postalCode":"37203","coordinates":{"lat":36.1404897,"lng":-86.7695179}},{"address1":"7431 Candace Way","address2":"#1","city":"Louisville","state":"KY","postalCode":"40214","coordinates":{"lat":38.142768,"lng":-85.7717132}},{"address1":"1407 Walden Court","address2":"","city":"Crofton","state":"MD","postalCode":"21114","coordinates":{"lat":39.019306,"lng":-76.660653}},{"address1":"5906 Milton Avenue","address2":"","city":"Deale","state":"MD","postalCode":"20751","coordinates":{"lat":38.784451,"lng":-76.54125499999999}},{"address1":"74 Springfield Street","address2":"B","city":"Agawam","state":"MA","postalCode":"01001","coordinates":{"lat":42.0894922,"lng":-72.6297558}},{"address1":"2905 Stonebridge Court","address2":"","city":"Norman","state":"OK","postalCode":"73071","coordinates":{"lat":35.183319,"lng":-97.40210499999999}},{"address1":"20930 Todd Valley Road","address2":"","city":"Foresthill","state":"CA","postalCode":"95631","coordinates":{"lat":38.989466,"lng":-120.883108}},{"address1":"5928 West Mauna Loa Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.6204899,"lng":-112.18702}},{"address1":"802 Madison Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.9582381,"lng":-77.0244287}},{"address1":"2811 Battery Place Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20016","coordinates":{"lat":38.9256252,"lng":-77.0982646}},{"address1":"210 Lacross Lane","address2":"","city":"Westmore","state":"VT","postalCode":"05860","coordinates":{"lat":44.771005,"lng":-72.048664}},{"address1":"2010 Rising Hill Drive","address2":"","city":"Norman","state":"OK","postalCode":"73071","coordinates":{"lat":35.177281,"lng":-97.411869}},{"address1":"388 East Main Street","address2":"","city":"Middlebury","state":"VT","postalCode":"05753","coordinates":{"lat":43.9727945,"lng":-73.1023187}},{"address1":"450 Kinhawk Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.030927,"lng":-86.71949099999999}},{"address1":"131 Westerly Street","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.7906813,"lng":-72.53559729999999}},{"address1":"308 Woodleaf Court","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21061","coordinates":{"lat":39.1425931,"lng":-76.6238441}},{"address1":"8502 Madrone Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40258","coordinates":{"lat":38.1286407,"lng":-85.8678042}},{"address1":"23 Sable Run Lane","address2":"","city":"Methuen","state":"MA","postalCode":"01844","coordinates":{"lat":42.759847,"lng":-71.157721}},{"address1":"716 Waller Road","address2":"","city":"Brentwood","state":"TN","postalCode":"37027","coordinates":{"lat":35.998892,"lng":-86.696529}},{"address1":"416 McIver Street","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.10436,"lng":-86.74411599999999}},{"address1":"1508 Massachusetts Avenue Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20003","coordinates":{"lat":38.887255,"lng":-76.98318499999999}},{"address1":"5615 West Villa Maria Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.650988,"lng":-112.180624}},{"address1":"3162 Martin Luther King Junior Boulevard","address2":"#2","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.05233310000001,"lng":-94.2056987}},{"address1":"5306 Ritchie Highway","address2":"","city":"Baltimore","state":"MD","postalCode":"21225","coordinates":{"lat":39.221978,"lng":-76.614183}},{"address1":"109 Summit Street","address2":"","city":"Burlington","state":"VT","postalCode":"05401","coordinates":{"lat":44.4729749,"lng":-73.2026566}},{"address1":"816 West 19th Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99503","coordinates":{"lat":61.203221,"lng":-149.898655}},{"address1":"172 Alburg Springs Road","address2":"","city":"Alburgh","state":"VT","postalCode":"05440","coordinates":{"lat":44.995827,"lng":-73.2201539}},{"address1":"159 Downey Drive","address2":"A","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7800126,"lng":-72.5754309}},{"address1":"125 John Street","address2":"","city":"Santa Cruz","state":"CA","postalCode":"95060","coordinates":{"lat":36.950901,"lng":-122.046881}},{"address1":"1101 Lotus Avenue","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21061","coordinates":{"lat":39.191982,"lng":-76.6525659}},{"address1":"8376 Albacore Drive","address2":"","city":"Pasadena","state":"MD","postalCode":"21122","coordinates":{"lat":39.110409,"lng":-76.46565799999999}},{"address1":"491 Arabian Way","address2":"","city":"Grand Junction","state":"CO","postalCode":"81504","coordinates":{"lat":39.07548999999999,"lng":-108.474785}},{"address1":"12245 West 71st Place","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8267078,"lng":-105.1366798}},{"address1":"80 North East Street","address2":"#4","city":"Holyoke","state":"MA","postalCode":"01040","coordinates":{"lat":42.2041219,"lng":-72.5977704}},{"address1":"4695 East Huntsville Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0471975,"lng":-94.0946286}},{"address1":"310 Timrod Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.756758,"lng":-72.493501}},{"address1":"1364 Capri Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.2207276,"lng":-85.6808795}},{"address1":"132 Laurel Green Court","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":32.0243075,"lng":-81.2468102}},{"address1":"6657 West Rose Garden Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.676018,"lng":-112.201658}},{"address1":"519 West 75th Avenue","address2":"#APT 000003","city":"Anchorage","state":"AK","postalCode":"99518","coordinates":{"lat":61.15288690000001,"lng":-149.889133}},{"address1":"31353 Santa Elena Way","address2":"","city":"Union City","state":"CA","postalCode":"94587","coordinates":{"lat":37.593981,"lng":-122.059762}},{"address1":"8398 West Denton Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85305","coordinates":{"lat":33.515353,"lng":-112.240812}},{"address1":"700 Winston Place","address2":"","city":"Anchorage","state":"AK","postalCode":"99504","coordinates":{"lat":61.215882,"lng":-149.737337}},{"address1":"232 Maine Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.1527033,"lng":-85.63207129999999}},{"address1":"1 Kempf Drive","address2":"","city":"Easton","state":"MA","postalCode":"02375","coordinates":{"lat":42.0505989,"lng":-71.08029379999999}},{"address1":"5811 Crossings Boulevard","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.0370847,"lng":-86.6413728}},{"address1":"5108 Franklin Street","address2":"","city":"Savannah","state":"GA","postalCode":"31405","coordinates":{"lat":32.034987,"lng":-81.121928}},{"address1":"913 Fallview Trail","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.02419100000001,"lng":-86.718305}},{"address1":"270 Chrissy's Court","address2":"","city":"Bristol","state":"VT","postalCode":"05443","coordinates":{"lat":44.1710043,"lng":-73.1065617}},{"address1":"130 Old Route 103","address2":"","city":"Chester","state":"VT","postalCode":"05143","coordinates":{"lat":43.224335,"lng":-72.54227399999999}},{"address1":"10826 Pointe Royal Drive","address2":"","city":"Bakersfield","state":"CA","postalCode":"93311","coordinates":{"lat":35.2930007,"lng":-119.1225908}},{"address1":"74 Ranch Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36109","coordinates":{"lat":32.383322,"lng":-86.235124}},{"address1":"6601 West Ocotillo Road","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.53433,"lng":-112.2011246}},{"address1":"19416 Barclay Road","address2":"","city":"Castro Valley","state":"CA","postalCode":"94546","coordinates":{"lat":37.70382,"lng":-122.091054}},{"address1":"1347 Blackwalnut Court","address2":"","city":"Annapolis","state":"MD","postalCode":"21403","coordinates":{"lat":38.936881,"lng":-76.475823}},{"address1":"1770 Colony Way","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0867,"lng":-94.229754}},{"address1":"165 Saint John Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7762171,"lng":-72.5410548}},{"address1":"2409 Research Boulevard","address2":"","city":"Fort Collins","state":"CO","postalCode":"80526","coordinates":{"lat":40.554586,"lng":-105.087852}},{"address1":"1903 Bashford Manor Lane","address2":"","city":"Louisville","state":"KY","postalCode":"40218","coordinates":{"lat":38.1977059,"lng":-85.675288}},{"address1":"8315 Surf Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32408","coordinates":{"lat":30.163458,"lng":-85.785449}},{"address1":"3301 Old Muldoon Road","address2":"","city":"Anchorage","state":"AK","postalCode":"99504","coordinates":{"lat":61.1908348,"lng":-149.7340096}},{"address1":"8800 Cordell Circle","address2":"#APT 000003","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.1409305,"lng":-149.9437822}},{"address1":"117 East Cook Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.230336,"lng":-149.883795}},{"address1":"6231 North 67th Avenue","address2":"#241","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5279666,"lng":-112.2022551}},{"address1":"8505 Waters Avenue","address2":"#66","city":"Savannah","state":"GA","postalCode":"31406","coordinates":{"lat":31.9901877,"lng":-81.1070672}},{"address1":"7 Underwood Place Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20012","coordinates":{"lat":38.969351,"lng":-77.009722}},{"address1":"21950 Arnold Center Road","address2":"","city":"Carson","state":"CA","postalCode":"90810","coordinates":{"lat":33.8272706,"lng":-118.2302826}},{"address1":"1427 South Carolina Avenue Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20003","coordinates":{"lat":38.886615,"lng":-76.9845349}},{"address1":"1420 Turtleback Trail","address2":"","city":"Panama City","state":"FL","postalCode":"32413","coordinates":{"lat":30.281084,"lng":-85.9677169}},{"address1":"6990 Pierson Street","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.824425,"lng":-105.122103}},{"address1":"376 North Williams Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.067997,"lng":-94.142563}},{"address1":"3617 Menlo Court","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.307397,"lng":-86.26001099999999}},{"address1":"711 Parker Street","address2":"","city":"East Longmeadow","state":"MA","postalCode":"01028","coordinates":{"lat":42.082262,"lng":-72.488113}},{"address1":"8521 Crystal Street","address2":"","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.143426,"lng":-149.94665}},{"address1":"1622 Edgar D Nixon Avenue","address2":"","city":"Montgomery","state":"AL","postalCode":"36104","coordinates":{"lat":32.356384,"lng":-86.3128909}},{"address1":"1608 Gales Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.8985542,"lng":-76.9813444}},{"address1":"122 East Hayes Street","address2":"","city":"Norman","state":"OK","postalCode":"73069","coordinates":{"lat":35.232121,"lng":-97.445053}},{"address1":"5144 Cattail Court","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.041153,"lng":-94.087419}},{"address1":"131 Kent Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.803084,"lng":-72.492786}},{"address1":"2313 Vegas Avenue","address2":"","city":"Castro Valley","state":"CA","postalCode":"94546","coordinates":{"lat":37.689189,"lng":-122.076775}},{"address1":"5420 Sunset Avenue","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32408","coordinates":{"lat":30.145603,"lng":-85.755095}},{"address1":"242 North Ash Street","address2":"","city":"Fruita","state":"CO","postalCode":"81521","coordinates":{"lat":39.161544,"lng":-108.725378}},{"address1":"38676 Greenwich Circle","address2":"","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.562256,"lng":-121.976451}},{"address1":"2426 East Onyx Trail","address2":"#6","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.065707,"lng":-94.1276125}},{"address1":"110 Seaton Place Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.9146701,"lng":-77.01264680000001}},{"address1":"5385 Iris Street","address2":"","city":"Arvada","state":"CO","postalCode":"80002","coordinates":{"lat":39.794498,"lng":-105.106056}},{"address1":"5628 West Tonopah Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6710947,"lng":-112.1810955}},{"address1":"65 Bay Drive","address2":"","city":"Annapolis","state":"MD","postalCode":"21403","coordinates":{"lat":38.937493,"lng":-76.45638699999999}},{"address1":"7401 North 61st Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5450005,"lng":-112.191417}},{"address1":"8 Watkins Road","address2":"","city":"Milton","state":"VT","postalCode":"05468","coordinates":{"lat":44.6028809,"lng":-73.17689299999999}},{"address1":"2209 June Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37214","coordinates":{"lat":36.16848,"lng":-86.695241}},{"address1":"1840 Nobel Place","address2":"","city":"Louisville","state":"KY","postalCode":"40216","coordinates":{"lat":38.198892,"lng":-85.8090129}},{"address1":"2622 Martin Luther King Junior Boulevard","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.053922,"lng":-94.1973008}},{"address1":"4 Glen Circle","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21060","coordinates":{"lat":39.157751,"lng":-76.60633399999999}},{"address1":"7529 West 72nd Avenue","address2":"#4","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8276128,"lng":-105.0799305}},{"address1":"10996 Largo Drive","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.99178,"lng":-81.14366799999999}},{"address1":"2027 North Shannon Drive","address2":"#5","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0892622,"lng":-94.17333020000001}},{"address1":"154 Boca Lagoon Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32408","coordinates":{"lat":30.171012,"lng":-85.77501099999999}},{"address1":"3311 Wiley Post Loop","address2":"","city":"Anchorage","state":"AK","postalCode":"99517","coordinates":{"lat":61.18686499999999,"lng":-149.946288}},{"address1":"5055 West 58th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80002","coordinates":{"lat":39.8024171,"lng":-105.0505121}},{"address1":"3228 Chettenham Drive","address2":"","city":"Rancho Cordova","state":"CA","postalCode":"95670","coordinates":{"lat":38.577813,"lng":-121.301333}},{"address1":"1901 North Midwest Boulevard","address2":"","city":"Edmond","state":"OK","postalCode":"73034","coordinates":{"lat":35.67413,"lng":-97.39058399999999}},{"address1":"1536 North Main Street","address2":"","city":"Salinas","state":"CA","postalCode":"93906","coordinates":{"lat":36.7122208,"lng":-121.6522485}},{"address1":"33 Linscott Road","address2":"","city":"Hingham","state":"MA","postalCode":"02043","coordinates":{"lat":42.2257391,"lng":-70.8828675}},{"address1":"1732 27th Avenue","address2":"","city":"Oakland","state":"CA","postalCode":"94601","coordinates":{"lat":37.783431,"lng":-122.228238}},{"address1":"22 Gallatin Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.9526368,"lng":-77.0080993}},{"address1":"8125 Glynnwood Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.341844,"lng":-86.14093}},{"address1":"2139 Glynnwood Drive","address2":"","city":"Savannah","state":"GA","postalCode":"31404","coordinates":{"lat":32.021538,"lng":-81.06860999999999}},{"address1":"14 School Street","address2":"","city":"Medway","state":"MA","postalCode":"02053","coordinates":{"lat":42.141711,"lng":-71.395014}},{"address1":"264 Crest Drive","address2":"","city":"Soldotna","state":"AK","postalCode":"99669","coordinates":{"lat":60.497608,"lng":-151.080848}},{"address1":"307 Joel Street","address2":"","city":"Pooler","state":"GA","postalCode":"31322","coordinates":{"lat":32.123265,"lng":-81.24991}},{"address1":"188 River Road","address2":"","city":"Essex","state":"VT","postalCode":"05452","coordinates":{"lat":44.478846,"lng":-73.058294}},{"address1":"1643 Oxford Street","address2":"R C","city":"Berkeley","state":"CA","postalCode":"94709","coordinates":{"lat":37.877894,"lng":-122.266436}},{"address1":"5545 Saddlewood Lane","address2":"","city":"Brentwood","state":"TN","postalCode":"37027","coordinates":{"lat":36.026888,"lng":-86.7576629}},{"address1":"26466 Mockingbird Lane","address2":"","city":"Hayward","state":"CA","postalCode":"94544","coordinates":{"lat":37.6410262,"lng":-122.0864272}},{"address1":"4840 Reservoir Road Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20007","coordinates":{"lat":38.9158933,"lng":-77.0962873}},{"address1":"599 Cambridge Street","address2":"#303","city":"Cambridge","state":"MA","postalCode":"02141","coordinates":{"lat":42.3720518,"lng":-71.08610949999999}},{"address1":"584 Rural Hill Road","address2":"","city":"Nashville","state":"TN","postalCode":"37217","coordinates":{"lat":36.089291,"lng":-86.621854}},{"address1":"10262 West 59th Avenue","address2":"#1","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.803718,"lng":-105.111974}},{"address1":"945 South 5th Street","address2":"#1020","city":"Louisville","state":"KY","postalCode":"40203","coordinates":{"lat":38.2402351,"lng":-85.76031119999999}},{"address1":"2543 The Meadows","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.3463001,"lng":-86.2185382}},{"address1":"153 Atlantic Avenue","address2":"#6","city":"Salisbury","state":"MA","postalCode":"01952","coordinates":{"lat":42.8339101,"lng":-70.81575269999999}},{"address1":"9 Brooklyn Street","address2":"","city":"Morrisville","state":"VT","postalCode":"05488","coordinates":{"lat":44.924599,"lng":-73.12809399999999}},{"address1":"5722 8th Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.959305,"lng":-77.024463}},{"address1":"8700 Seaton Boulevard","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.3378676,"lng":-86.1731595}},{"address1":"1004 Bellflower Street","address2":"","city":"Livermore","state":"CA","postalCode":"94551","coordinates":{"lat":37.710745,"lng":-121.732765}},{"address1":"4738 Mallard Common","address2":"","city":"Fremont","state":"CA","postalCode":"94555","coordinates":{"lat":37.5666441,"lng":-122.0444344}},{"address1":"875 Latouche Street","address2":"#APT 001010","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.2132529,"lng":-149.8608243}},{"address1":"4940 Fuller Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36110","coordinates":{"lat":32.42936,"lng":-86.21683519999999}},{"address1":"5754 Belleau Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.394398,"lng":-86.203138}},{"address1":"1403 Lincoln Street","address2":"","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.0613716,"lng":-81.09482249999999}},{"address1":"140 South Hill Avenue","address2":"#305","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0618737,"lng":-94.16920189999999}},{"address1":"642 South 2nd Street","address2":"#608","city":"Louisville","state":"KY","postalCode":"40202","coordinates":{"lat":38.2472593,"lng":-85.7549195}},{"address1":"6473 Zephyr Street","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.814341,"lng":-105.085116}},{"address1":"4250 North Valley Lake Drive","address2":"#8","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.1279064,"lng":-94.12180719999999}},{"address1":"565 North Lakeshore Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.246868,"lng":-85.918511}},{"address1":"5514 West Wedington Drive","address2":"#3","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.079411,"lng":-94.240031}},{"address1":"1909 Wainwright Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.183868,"lng":-85.722174}},{"address1":"4525 West Frier Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5488732,"lng":-112.1565998}},{"address1":"201 West Montgomery Cross Road","address2":"#170","city":"Savannah","state":"GA","postalCode":"31406","coordinates":{"lat":31.9996137,"lng":-81.13121}},{"address1":"915 Heath Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.363883,"lng":-86.333247}},{"address1":"95 Briarwood Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.745751,"lng":-72.542544}},{"address1":"69 Washington Street","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.78712489999999,"lng":-72.52083069999999}},{"address1":"2900 North Western Avenue","address2":"","city":"Edmond","state":"OK","postalCode":"73012","coordinates":{"lat":35.687568,"lng":-97.53227299999999}},{"address1":"7841 West Kristal Way","address2":"","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.658804,"lng":-112.228834}},{"address1":"361 Parmley Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37207","coordinates":{"lat":36.2446128,"lng":-86.8197718}},{"address1":"6120 Southeast 84th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73135","coordinates":{"lat":35.380836,"lng":-97.41582}},{"address1":"9428 North 65th Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.571222,"lng":-112.20045}},{"address1":"11 Meeting Place Circle","address2":"","city":"Boxford","state":"MA","postalCode":"01921","coordinates":{"lat":42.6946519,"lng":-71.0008529}},{"address1":"4438 Maine Avenue","address2":"","city":"Baldwin Park","state":"CA","postalCode":"91706","coordinates":{"lat":34.093409,"lng":-117.959953}},{"address1":"65 Jones Lane","address2":"","city":"Montevallo","state":"AL","postalCode":"35115","coordinates":{"lat":33.096851,"lng":-86.846577}},{"address1":"3140 Commander Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40220","coordinates":{"lat":38.215781,"lng":-85.653981}},{"address1":"107 Guaymas Place","address2":"","city":"Davis","state":"CA","postalCode":"95616","coordinates":{"lat":38.567048,"lng":-121.746046}},{"address1":"6114 West Glenn Drive","address2":"#1","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5401454,"lng":-112.1912722}},{"address1":"622 Thomas Street","address2":"","city":"Woodland","state":"CA","postalCode":"95776","coordinates":{"lat":38.672731,"lng":-121.76065}},{"address1":"127 Grand Heron Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32407","coordinates":{"lat":30.189702,"lng":-85.80841099999999}},{"address1":"3504 East 16th Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99508","coordinates":{"lat":61.2058945,"lng":-149.8158624}},{"address1":"1230 Stafford Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.32403,"lng":-86.14840099999999}},{"address1":"6007 Yarrow Street","address2":"H","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.806211,"lng":-105.084446}},{"address1":"632 Belmar Drive","address2":"","city":"Edmond","state":"OK","postalCode":"73025","coordinates":{"lat":35.7016024,"lng":-97.4912627}},{"address1":"1515 Chandlee Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.176365,"lng":-85.666253}},{"address1":"10632 Admiral Court","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73162","coordinates":{"lat":35.57886200000001,"lng":-97.6270728}},{"address1":"11655 West 81st Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.84356820000001,"lng":-105.1297584}},{"address1":"3500 Blanchard Drive Southwest","address2":"","city":"Washington","state":"DC","postalCode":"20032","coordinates":{"lat":38.8388931,"lng":-77.02011139999999}},{"address1":"2755 Country Drive","address2":"#244","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.557882,"lng":-121.986823}},{"address1":"1850 Berryhill Place","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.3527548,"lng":-86.16858669999999}},{"address1":"58 North U.S.A Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":35.994914,"lng":-94.185867}},{"address1":"8785 Ellis Court","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.853725,"lng":-105.158861}},{"address1":"1636 Briarview Court","address2":"","city":"Severn","state":"MD","postalCode":"21144","coordinates":{"lat":39.12539599999999,"lng":-76.704015}},{"address1":"12 Knox Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.774166,"lng":-72.527697}},{"address1":"425 Middle Turnpike East","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7847772,"lng":-72.50354829999999}},{"address1":"2017 North Hartford Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.08820499999999,"lng":-94.1074905}},{"address1":"5900 Upland Road","address2":"","city":"Brooklyn Park","state":"MD","postalCode":"21225","coordinates":{"lat":39.213888,"lng":-76.61925099999999}},{"address1":"9331 Edison Road","address2":"","city":"Lithia","state":"FL","postalCode":"33547","coordinates":{"lat":27.86851,"lng":-82.07391199999999}},{"address1":"1810 Orchard Place","address2":"","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.145912,"lng":-149.9134259}},{"address1":"145 Grau Drive","address2":"","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.582453,"lng":-121.994476}},{"address1":"3959 Fairlands Drive","address2":"","city":"Pleasanton","state":"CA","postalCode":"94588","coordinates":{"lat":37.6992001,"lng":-121.8703701}},{"address1":"3613 East 18th Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99508","coordinates":{"lat":61.20485339999999,"lng":-149.8135521}},{"address1":"1275 South Holland Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.051782,"lng":-94.226855}},{"address1":"109 Cambridge Station Road","address2":"","city":"Louisville","state":"KY","postalCode":"40223","coordinates":{"lat":38.244527,"lng":-85.56912799999999}},{"address1":"2107 Elfen Glen","address2":"Apt B","city":"Van Buren","state":"AR","postalCode":"72956","coordinates":{"lat":35.469752,"lng":-94.364987}},{"address1":"8522 Ingalls Circle","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8528593,"lng":-105.0629778}},{"address1":"1809 Cedar Drive","address2":"","city":"Severn","state":"MD","postalCode":"21144","coordinates":{"lat":39.139311,"lng":-76.72028999999999}},{"address1":"1376 Oakland Avenue","address2":"#1","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.080981,"lng":-94.172549}},{"address1":"4306 Bylsma Circle","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.223294,"lng":-85.589715}},{"address1":"233 Buckland Hills Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.8100683,"lng":-72.5453665}},{"address1":"7701 Southwest 104th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73169","coordinates":{"lat":35.3641983,"lng":-97.6475346}},{"address1":"14003 Crossbranch Court","address2":"","city":"Louisville","state":"KY","postalCode":"40245","coordinates":{"lat":38.242033,"lng":-85.489885}},{"address1":"19590 East Batavia Drive","address2":"","city":"Aurora","state":"CO","postalCode":"80011","coordinates":{"lat":39.7420886,"lng":-104.7581149}},{"address1":"6424 Simms Street","address2":"#71","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8133443,"lng":-105.1283237}},{"address1":"718 Dutchmans Court","address2":"","city":"Nashville","state":"TN","postalCode":"37076","coordinates":{"lat":36.2048851,"lng":-86.5994752}},{"address1":"8496 Isles Court","address2":"","city":"Pasadena","state":"MD","postalCode":"21122","coordinates":{"lat":39.111297,"lng":-76.467049}},{"address1":"100 East Joyce Boulevard","address2":"#110","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.1253411,"lng":-94.1551631}},{"address1":"9036 Calico Court","address2":"","city":"Hesperia","state":"CA","postalCode":"92344","coordinates":{"lat":34.414491,"lng":-117.375403}},{"address1":"2723 East Joyce Boulevard","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.119414,"lng":-94.12229500000001}},{"address1":"90 Via Verde","address2":"","city":"San Lorenzo","state":"CA","postalCode":"94580","coordinates":{"lat":37.67869,"lng":-122.117142}},{"address1":"1015 Castle Road","address2":"","city":"Edmond","state":"OK","postalCode":"73034","coordinates":{"lat":35.665019,"lng":-97.466045}},{"address1":"2787 West Blackstone Crossing","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0608984,"lng":-94.1993461}},{"address1":"3555 Alamosa Drive","address2":"","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.142316,"lng":-149.9454749}},{"address1":"6231 North 59th Avenue","address2":"#35","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5285304,"lng":-112.1860744}},{"address1":"311 South Panama Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36107","coordinates":{"lat":32.376833,"lng":-86.27416099999999}},{"address1":"3313 Daisy Trail","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.076186,"lng":-86.60113799999999}},{"address1":"5436 Dorbrandt Street","address2":"#APT 000002","city":"Anchorage","state":"AK","postalCode":"99518","coordinates":{"lat":61.17090200000001,"lng":-149.904782}},{"address1":"553 South Arlington Road","address2":"","city":"Orange","state":"CA","postalCode":"92869","coordinates":{"lat":33.7794839,"lng":-117.820383}},{"address1":"615 Q Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.9113118,"lng":-77.0206808}},{"address1":"457 Mountain Village Boulevard","address2":"#320-3","city":"Mountain Village","state":"CO","postalCode":"81435","coordinates":{"lat":37.93323040000001,"lng":-107.8515732}},{"address1":"144 Lauderdale Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.309978,"lng":-86.259716}},{"address1":"2 Ambelwood Way","address2":"","city":"Savannah","state":"GA","postalCode":"31411","coordinates":{"lat":31.9138389,"lng":-81.07297989999999}},{"address1":"4113 Holiday Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32408","coordinates":{"lat":30.1548681,"lng":-85.7709976}},{"address1":"2001 Van Hoose Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.039421,"lng":-94.065534}},{"address1":"9457 Winfield Place","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.341347,"lng":-86.14867799999999}},{"address1":"1120 Mitchell Young Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.327464,"lng":-86.44011599999999}},{"address1":"12816 West 65th Way","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8141779,"lng":-105.1426275}},{"address1":"10 Erick Road","address2":"#47","city":"Mansfield","state":"MA","postalCode":"02048","coordinates":{"lat":42.032505,"lng":-71.17718599999999}},{"address1":"481 East Redbud Lane","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.103899,"lng":-94.151128}},{"address1":"320 Northwest 22nd Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73103","coordinates":{"lat":35.491908,"lng":-97.51843099999999}},{"address1":"33 South Hill Avenue","address2":"#306","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0619602,"lng":-94.16977700000001}},{"address1":"355 Gillette Road","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.061143,"lng":-86.70823299999999}},{"address1":"151 Main Street","address2":"","city":"Savannah","state":"GA","postalCode":"31408","coordinates":{"lat":32.113199,"lng":-81.148934}},{"address1":"545 Tracey Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.1354251,"lng":-85.5573034}},{"address1":"3 Southerberry Drive","address2":"","city":"Milton","state":"VT","postalCode":"05468","coordinates":{"lat":44.62322460000001,"lng":-73.1326629}},{"address1":"736 Sicard Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20003","coordinates":{"lat":38.8729038,"lng":-76.9949528}},{"address1":"6214 Herzog Street","address2":"","city":"Oakland","state":"CA","postalCode":"94608","coordinates":{"lat":37.84557849999999,"lng":-122.2825201}},{"address1":"1160 North College Avenue","address2":"#2","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0785477,"lng":-94.1566273}},{"address1":"5843 West McLellan Road","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5330898,"lng":-112.1857087}},{"address1":"1452 55th Avenue","address2":"B","city":"Oakland","state":"CA","postalCode":"94621","coordinates":{"lat":37.767671,"lng":-122.202326}},{"address1":"4255 Tanager Common","address2":"","city":"Fremont","state":"CA","postalCode":"94555","coordinates":{"lat":37.5738888,"lng":-122.0460256}},{"address1":"13426 West Rovey Avenue","address2":"","city":"Litchfield Park","state":"AZ","postalCode":"85340","coordinates":{"lat":33.522973,"lng":-112.34802}},{"address1":"195 Nursery Street","address2":"#D10","city":"Springfield","state":"MA","postalCode":"01104","coordinates":{"lat":42.1178409,"lng":-72.5892289}},{"address1":"126 Marjorie Lane","address2":"C","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.8073257,"lng":-72.5188292}},{"address1":"22 Charnock Street","address2":"#2","city":"Beverly","state":"MA","postalCode":"01915","coordinates":{"lat":42.55227,"lng":-70.876549}},{"address1":"817 25th Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20037","coordinates":{"lat":38.900077,"lng":-77.053066}},{"address1":"2552 Massachusetts Avenue Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20008","coordinates":{"lat":38.9165459,"lng":-77.057323}},{"address1":"1711 Lore Road","address2":"#APT 000106","city":"Anchorage","state":"AK","postalCode":"99507","coordinates":{"lat":61.15195259999999,"lng":-149.8511487}},{"address1":"19091 Northeast 23rd Street","address2":"","city":"Harrah","state":"OK","postalCode":"73045","coordinates":{"lat":35.493447,"lng":-97.193078}},{"address1":"8318 North 57th Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.557537,"lng":-112.183238}},{"address1":"7256 West 84th Way","address2":"#918","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8506912,"lng":-105.0767393}},{"address1":"706 Seagrove Road","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21060","coordinates":{"lat":39.163384,"lng":-76.609205}},{"address1":"2318 Camryns Crossing","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.221926,"lng":-85.62420000000002}},{"address1":"968 Virginia Avenue","address2":"","city":"Olivehurst","state":"CA","postalCode":"95961","coordinates":{"lat":39.1022419,"lng":-121.581218}},{"address1":"416 South University Boulevard","address2":"","city":"Norman","state":"OK","postalCode":"73069","coordinates":{"lat":35.215351,"lng":-97.446319}},{"address1":"137 Gazebo East Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.3793507,"lng":-86.20407399999999}},{"address1":"10723 Colonial Woods Court","address2":"","city":"Louisville","state":"KY","postalCode":"40223","coordinates":{"lat":38.2496439,"lng":-85.55717709999999}},{"address1":"119 Matthew Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37215","coordinates":{"lat":36.11663619999999,"lng":-86.80955829999999}},{"address1":"3142 West Finger Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.042837,"lng":-94.205309}},{"address1":"4 Elm Street","address2":"","city":"Windsor","state":"VT","postalCode":"05089","coordinates":{"lat":43.476997,"lng":-72.398925}},{"address1":"78 School Street","address2":"","city":"Woburn","state":"MA","postalCode":"01801","coordinates":{"lat":42.506877,"lng":-71.15299}},{"address1":"19020 North 68th Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6574037,"lng":-112.2062039}},{"address1":"2849 Quail Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.095294,"lng":-94.20036300000001}},{"address1":"2456 22nd Avenue","address2":"","city":"Greeley","state":"CO","postalCode":"80631","coordinates":{"lat":40.397153,"lng":-104.713982}},{"address1":"200 Boulder Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7792079,"lng":-72.494963}},{"address1":"11150 Sun Valley Drive","address2":"","city":"Oakland","state":"CA","postalCode":"94605","coordinates":{"lat":37.752039,"lng":-122.11822}},{"address1":"505 Southeast 32nd Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73129","coordinates":{"lat":35.4325058,"lng":-97.5032743}},{"address1":"1025 West 19th Street","address2":"#UNIT 1-C","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.18252889999999,"lng":-85.676771}},{"address1":"6725 Pamela Court","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.334546,"lng":-86.20349999999999}},{"address1":"4714 Narrow Lane Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.3140725,"lng":-86.2819674}},{"address1":"11 Proctor Circle","address2":"","city":"Peabody","state":"MA","postalCode":"01960","coordinates":{"lat":42.535503,"lng":-70.953384}},{"address1":"10508 Kovats Court","address2":"","city":"Louisville","state":"KY","postalCode":"40223","coordinates":{"lat":38.2330381,"lng":-85.5695464}},{"address1":"3179 18th Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20010","coordinates":{"lat":38.9312712,"lng":-77.0412983}},{"address1":"3194 Bladensburg Road Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20018","coordinates":{"lat":38.930136,"lng":-76.95929799999999}},{"address1":"260 Rio Del Mar Boulevard","address2":"##14","city":"Aptos","state":"CA","postalCode":"95003","coordinates":{"lat":36.967915,"lng":-121.902513}},{"address1":"1040 West 27th Avenue","address2":"#APT 000401","city":"Anchorage","state":"AK","postalCode":"99503","coordinates":{"lat":61.195892,"lng":-149.901984}},{"address1":"42 Lake Lane","address2":"","city":"Westmore","state":"VT","postalCode":"05860","coordinates":{"lat":44.77954099999999,"lng":-72.0682889}},{"address1":"3718 Bay Tree Road","address2":"","city":"Lynn Haven","state":"FL","postalCode":"32444","coordinates":{"lat":30.205726,"lng":-85.63441999999999}},{"address1":"3408 Bellisima Place","address2":"#204","city":"Louisville","state":"KY","postalCode":"40245","coordinates":{"lat":38.2857023,"lng":-85.5023064}},{"address1":"4109 General Bate Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37204","coordinates":{"lat":36.099427,"lng":-86.787756}},{"address1":"5329 A Street","address2":"","city":"Greeley","state":"CO","postalCode":"80634","coordinates":{"lat":40.4347001,"lng":-104.7702805}},{"address1":"88 Shute Street","address2":"#1","city":"Everett","state":"MA","postalCode":"02149","coordinates":{"lat":42.4192568,"lng":-71.0469179}},{"address1":"480 Keene Road","address2":"","city":"Walden","state":"VT","postalCode":"05836","coordinates":{"lat":44.4879516,"lng":-72.2823264}},{"address1":"4 Cutting Avenue","address2":"","city":"Worcester","state":"MA","postalCode":"01606","coordinates":{"lat":42.307664,"lng":-71.79180099999999}},{"address1":"275 South 40th Street","address2":"","city":"Boulder","state":"CO","postalCode":"80305","coordinates":{"lat":39.988864,"lng":-105.247011}},{"address1":"1189 Northwest End Avenue","address2":"#D3","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0793885,"lng":-94.19657190000001}},{"address1":"25 Cliffside Drive","address2":"D","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.79505229999999,"lng":-72.48762169999999}},{"address1":"2515 60th Avenue","address2":"","city":"Oakland","state":"CA","postalCode":"94605","coordinates":{"lat":37.7705346,"lng":-122.1907449}},{"address1":"2057 Lucas Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36107","coordinates":{"lat":32.3934472,"lng":-86.2766814}},{"address1":"386 Daniels Road","address2":"","city":"New Haven","state":"VT","postalCode":"05472","coordinates":{"lat":44.114323,"lng":-73.1911159}},{"address1":"9805 Meadow Vale Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40242","coordinates":{"lat":38.281955,"lng":-85.57182100000001}},{"address1":"8 Village Circle","address2":"","city":"Randolph","state":"VT","postalCode":"05060","coordinates":{"lat":43.927687,"lng":-72.65563}},{"address1":"1011 San Jose Street","address2":"","city":"San Leandro","state":"CA","postalCode":"94577","coordinates":{"lat":37.72956300000001,"lng":-122.147074}},{"address1":"2505 Walker Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37207","coordinates":{"lat":36.2125119,"lng":-86.806625}},{"address1":"11225 West 79th Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.840784,"lng":-105.124533}},{"address1":"1907 18th Avenue South","address2":"","city":"Nashville","state":"TN","postalCode":"37212","coordinates":{"lat":36.134703,"lng":-86.79737700000001}},{"address1":"16 Conway Street","address2":"","city":"Shelburne Falls","state":"MA","postalCode":"01370","coordinates":{"lat":42.6022637,"lng":-72.74100059999999}},{"address1":"20375 Wisteria Street","address2":"","city":"Castro Valley","state":"CA","postalCode":"94546","coordinates":{"lat":37.696683,"lng":-122.085865}},{"address1":"6408 Fern Crest Road","address2":"","city":"Louisville","state":"KY","postalCode":"40291","coordinates":{"lat":38.154488,"lng":-85.612144}},{"address1":"175 Creek Road","address2":"","city":"Castleton","state":"VT","postalCode":"05735","coordinates":{"lat":43.6055996,"lng":-73.2336737}},{"address1":"2531 Prestwick Avenue","address2":"","city":"Concord","state":"CA","postalCode":"94519","coordinates":{"lat":37.9966039,"lng":-122.0280747}},{"address1":"1002 Highland Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40204","coordinates":{"lat":38.2371577,"lng":-85.7367362}},{"address1":"2927 Leatherwood Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37214","coordinates":{"lat":36.156413,"lng":-86.65534099999999}},{"address1":"8467 Chase Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.851766,"lng":-105.071498}},{"address1":"8556 Nelson Court","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.850965,"lng":-105.117879}},{"address1":"122 Summer Street","address2":"#1","city":"Medford","state":"MA","postalCode":"02155","coordinates":{"lat":42.415648,"lng":-71.116886}},{"address1":"12061 Johns Road","address2":"#APT 000002","city":"Anchorage","state":"AK","postalCode":"99515","coordinates":{"lat":61.111453,"lng":-149.8780899}},{"address1":"8358 WB&A Road","address2":"","city":"Severn","state":"MD","postalCode":"21144","coordinates":{"lat":39.108962,"lng":-76.68668799999999}},{"address1":"43 Henderson Avenue","address2":"","city":"Savannah","state":"GA","postalCode":"31406","coordinates":{"lat":31.97937899999999,"lng":-81.06062}},{"address1":"347 Brewer Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.054592,"lng":-86.708157}},{"address1":"2765 North Barcelona Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.102026,"lng":-94.15365}},{"address1":"5311 Chenoweth Park Lane","address2":"","city":"Louisville","state":"KY","postalCode":"40291","coordinates":{"lat":38.168051,"lng":-85.571491}},{"address1":"6398 Jellison Way","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8118489,"lng":-105.1121974}},{"address1":"604 Northwest 118th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73114","coordinates":{"lat":35.5902559,"lng":-97.523444}},{"address1":"37 Rushforde Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.738226,"lng":-72.538398}},{"address1":"5434 West Beck Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.6266139,"lng":-112.176412}},{"address1":"1516 Ringe Drive","address2":"","city":"Severn","state":"MD","postalCode":"21144","coordinates":{"lat":39.094173,"lng":-76.68423299999999}},{"address1":"3701 Lake Towne Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.068871,"lng":-86.612042}},{"address1":"20250 North 67th Avenue","address2":"#2143","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6705359,"lng":-112.2044722}},{"address1":"62 Prospect Avenue","address2":"#1","city":"Quincy","state":"MA","postalCode":"02170","coordinates":{"lat":42.261576,"lng":-71.020522}},{"address1":"25 Morton Street","address2":"#216","city":"Quincy","state":"MA","postalCode":"02169","coordinates":{"lat":42.24450900000001,"lng":-71.021176}},{"address1":"8202 4 Winds Drive","address2":"#3","city":"Lyndon","state":"KY","postalCode":"40222","coordinates":{"lat":38.26545309999999,"lng":-85.60216830000002}},{"address1":"513 Habberton Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.107299,"lng":-94.053033}},{"address1":"1960 Sigfrid Court","address2":"","city":"Annapolis","state":"MD","postalCode":"21401","coordinates":{"lat":38.998796,"lng":-76.564554}},{"address1":"663 Chesapeake Way","address2":"#1","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0498647,"lng":-94.1504411}},{"address1":"3354 Wilmington Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36105","coordinates":{"lat":32.345724,"lng":-86.301384}},{"address1":"8529 Old Harding Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37221","coordinates":{"lat":36.027995,"lng":-87.014506}},{"address1":"22219 Panama City Beach Parkway","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.2620426,"lng":-85.96316709999999}},{"address1":"37 East Broad Street","address2":"","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.0776278,"lng":-81.08469219999999}},{"address1":"1309 Columbia Road Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20009","coordinates":{"lat":38.9275945,"lng":-77.0307141}},{"address1":"1211 Castine Court","address2":"","city":"Pasadena","state":"MD","postalCode":"21122","coordinates":{"lat":39.1404092,"lng":-76.5313772}},{"address1":"906 West Berry Street","address2":"#204","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0760793,"lng":-94.1723526}},{"address1":"341 Oakland Street","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.805274,"lng":-72.5180772}},{"address1":"60 Downey Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7786337,"lng":-72.5757232}},{"address1":"3770 North Front Street","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.1183319,"lng":-94.1443548}},{"address1":"25 Church Street","address2":"A","city":"Pittsfield","state":"MA","postalCode":"01201","coordinates":{"lat":42.446859,"lng":-73.255836}},{"address1":"6578 Marauder Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37209","coordinates":{"lat":36.142929,"lng":-86.885521}},{"address1":"2747 68th Avenue","address2":"","city":"Oakland","state":"CA","postalCode":"94605","coordinates":{"lat":37.768532,"lng":-122.180694}},{"address1":"95 Woods Hill Road","address2":"","city":"Swanton","state":"VT","postalCode":"05488","coordinates":{"lat":44.897682,"lng":-73.0753299}},{"address1":"35 Keach Avenue","address2":"","city":"Worcester","state":"MA","postalCode":"01607","coordinates":{"lat":42.2269409,"lng":-71.801441}},{"address1":"1822 North Grand Avenue","address2":"","city":"Pueblo","state":"CO","postalCode":"81003","coordinates":{"lat":38.284427,"lng":-104.611581}},{"address1":"1809 U.S. 80","address2":"","city":"Savannah","state":"GA","postalCode":"31408","coordinates":{"lat":32.0847824,"lng":-81.16739679999999}},{"address1":"5065 North 54th Avenue","address2":"#8","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5118429,"lng":-112.1748805}},{"address1":"1261 Steamboat Drive","address2":"#3","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0804859,"lng":-94.2049698}},{"address1":"1695 Archer Street","address2":"","city":"Savannah","state":"GA","postalCode":"31405","coordinates":{"lat":32.0475974,"lng":-81.13348289999999}},{"address1":"3904 October Woods Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.009291,"lng":-86.624016}},{"address1":"1223 Delaware Avenue","address2":"","city":"Deale","state":"MD","postalCode":"20733","coordinates":{"lat":38.799962,"lng":-76.51803699999999}},{"address1":"10383 Eagle River Lane","address2":"","city":"Anchorage","state":"AK","postalCode":"99577","coordinates":{"lat":61.31412899999999,"lng":-149.509103}},{"address1":"1314 89th Avenue","address2":"","city":"Oakland","state":"CA","postalCode":"94621","coordinates":{"lat":37.7497401,"lng":-122.1762833}},{"address1":"21 Longview Bluff Drive East","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.95754299999999,"lng":-81.13848899999999}},{"address1":"1689 Fisher Pond Road","address2":"","city":"Saint Albans City","state":"VT","postalCode":"05478","coordinates":{"lat":44.826977,"lng":-73.055054}},{"address1":"9920 West 81st Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8446204,"lng":-105.1083834}},{"address1":"2732 Rosedale Place","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.1230861,"lng":-86.7625204}},{"address1":"10881 Northforde Drive","address2":"","city":"Cupertino","state":"CA","postalCode":"95014","coordinates":{"lat":37.335812,"lng":-122.023985}},{"address1":"926 Mill Court","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.959343,"lng":-81.142287}},{"address1":"7550 Kline Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8342031,"lng":-105.1106565}},{"address1":"5688 Johnson Court","address2":"","city":"Arvada","state":"CO","postalCode":"80002","coordinates":{"lat":39.798419,"lng":-105.109316}},{"address1":"4439 Gale Street","address2":"","city":"Livermore","state":"CA","postalCode":"94550","coordinates":{"lat":37.690199,"lng":-121.7411119}},{"address1":"6450 West Bethany Home Road","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5242005,"lng":-112.1991369}},{"address1":"2931 Shady Oaks Drive","address2":"","city":"Evans","state":"CO","postalCode":"80620","coordinates":{"lat":40.384469,"lng":-104.726478}},{"address1":"6451 West Bell Road","address2":"#1144","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6380231,"lng":-112.1986753}},{"address1":"644 West Maple Street","address2":"#2","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0703335,"lng":-94.1686289}},{"address1":"1219 North Storer Avenue","address2":"#66","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.078949,"lng":-94.17225499999999}},{"address1":"152 Holly Court","address2":"","city":"Mountain View","state":"CA","postalCode":"94043","coordinates":{"lat":37.390391,"lng":-122.060062}},{"address1":"6086 Kennedy Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.103629,"lng":-94.24773599999999}},{"address1":"2300 Deer Path Circle","address2":"#207","city":"Hurstbourne Acres","state":"KY","postalCode":"40220","coordinates":{"lat":38.2187876,"lng":-85.59292239999999}},{"address1":"802 East 37th Street","address2":"","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.054012,"lng":-81.087324}},{"address1":"5821 Taft Street","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8029119,"lng":-105.1308558}},{"address1":"188 Saint Matthews Avenue","address2":"#1","city":"Louisville","state":"KY","postalCode":"40207","coordinates":{"lat":38.2577576,"lng":-85.6546706}},{"address1":"68 Hampstead Place","address2":"","city":"Athol","state":"MA","postalCode":"01331","coordinates":{"lat":42.5894395,"lng":-72.2275859}},{"address1":"3164 West Woodfield Way","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.084691,"lng":-94.20445}},{"address1":"7998 Chase Circle","address2":"#1","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.841232,"lng":-105.057933}},{"address1":"1797 Pasatiempo Drive","address2":"","city":"Chico","state":"CA","postalCode":"95928","coordinates":{"lat":39.6777229,"lng":-121.7704692}},{"address1":"3722 Kisling Loop","address2":"","city":"Tyndall Air Force Base","state":"FL","postalCode":"32403","coordinates":{"lat":30.1048481,"lng":-85.65097360000001}},{"address1":"429 Patterson Street","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.102655,"lng":-86.744186}},{"address1":"6140 Fenton Street","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8080314,"lng":-105.0601435}},{"address1":"7404 West Crest Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85310","coordinates":{"lat":33.6851098,"lng":-112.2167229}},{"address1":"7841 North 59th Lane","address2":"#G37","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5516587,"lng":-112.1879207}},{"address1":"8043 Cranberry Street","address2":"#APT 000001","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.14769579999999,"lng":-149.9369466}},{"address1":"173 Spruce Street","address2":"#18","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7705332,"lng":-72.51594109999999}},{"address1":"4712 Cherokee Heights Road","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.234223,"lng":-85.566684}},{"address1":"915 Sacramento Street","address2":"","city":"Bakersfield","state":"CA","postalCode":"93305","coordinates":{"lat":35.3798759,"lng":-119.0002119}},{"address1":"317 Windsor Road","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.973034,"lng":-81.141871}},{"address1":"1332 Maple Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.3589738,"lng":-86.3278235}},{"address1":"4709 Blagden Terrace Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.9481213,"lng":-77.0401892}},{"address1":"5102 Ander Drive","address2":"","city":"Brentwood","state":"TN","postalCode":"37027","coordinates":{"lat":36.0025004,"lng":-86.6944901}},{"address1":"6754 Field Street","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8193709,"lng":-105.097531}},{"address1":"2347 Glen Eagle Drive","address2":"","city":"Northfield","state":"KY","postalCode":"40222","coordinates":{"lat":38.2862836,"lng":-85.6299745}},{"address1":"1613 Maple Timber Court","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.067096,"lng":-86.607005}},{"address1":"269 Park Street","address2":"#1","city":"North Reading","state":"MA","postalCode":"01864","coordinates":{"lat":42.57268,"lng":-71.09888800000002}},{"address1":"6444 North 67th Avenue","address2":"#1081","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5302444,"lng":-112.2049579}},{"address1":"11 Pine Point Road","address2":"","city":"Duxbury","state":"MA","postalCode":"02332","coordinates":{"lat":42.0613192,"lng":-70.6510247}},{"address1":"4136 East Virginia Lane","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.295998,"lng":-86.22073999999999}},{"address1":"5740 North 59th Avenue","address2":"#1156","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5207722,"lng":-112.189044}},{"address1":"95 Central Street","address2":"A","city":"Springfield","state":"MA","postalCode":"01105","coordinates":{"lat":42.098581,"lng":-72.57880999999999}},{"address1":"74 Heard Street","address2":"#1","city":"Chelsea","state":"MA","postalCode":"02150","coordinates":{"lat":42.3972985,"lng":-71.035599}},{"address1":"2500 Snowdoun Chambers Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36105","coordinates":{"lat":32.24569110000001,"lng":-86.2577436}},{"address1":"429 Dennison Ridge Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.750419,"lng":-72.474013}},{"address1":"1208 Lindenwood Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.187016,"lng":-85.681247}},{"address1":"7609 Doris Place","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73162","coordinates":{"lat":35.5759649,"lng":-97.64877299999999}},{"address1":"1915 Southeast 29th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73129","coordinates":{"lat":35.4360844,"lng":-97.4787061}},{"address1":"212 Holiday Circle","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":32.025153,"lng":-81.240329}},{"address1":"32 Amsden Street","address2":"#1","city":"Arlington","state":"MA","postalCode":"02474","coordinates":{"lat":42.4043927,"lng":-71.138137}},{"address1":"4016 Doane Street","address2":"","city":"Fremont","state":"CA","postalCode":"94538","coordinates":{"lat":37.514834,"lng":-121.95302}},{"address1":"8700 Lillington Circle","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.330168,"lng":-86.14481099999999}},{"address1":"7720 Allison Street","address2":"#105","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8383411,"lng":-105.0855734}},{"address1":"17878 Front Beach Road","address2":"#C-2","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.237658,"lng":-85.91577099999999}},{"address1":"1328 Tuckerman Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.9673595,"lng":-77.03106919999999}},{"address1":"4600 East Huntsville Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0476559,"lng":-94.0953342}},{"address1":"5038 North Cimarron Drive","address2":"","city":"Beverly Hills","state":"FL","postalCode":"34465","coordinates":{"lat":28.935938,"lng":-82.527367}},{"address1":"1216 West Hill Street","address2":"M","city":"Louisville","state":"KY","postalCode":"40210","coordinates":{"lat":38.227343,"lng":-85.7764254}},{"address1":"3033 Aubert Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40206","coordinates":{"lat":38.250779,"lng":-85.679931}},{"address1":"17020 West 64th Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80007","coordinates":{"lat":39.8131034,"lng":-105.1914804}},{"address1":"12420 West Montebello Avenue","address2":"","city":"Litchfield Park","state":"AZ","postalCode":"85340","coordinates":{"lat":33.519491,"lng":-112.32613}},{"address1":"2538 East 40th Plaza","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.221455,"lng":-85.626834}},{"address1":"827 10th Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.901021,"lng":-76.992391}},{"address1":"5912 North 48th Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5231022,"lng":-112.162186}},{"address1":"37 Fieldside Drive","address2":"","city":"Groton","state":"CT","postalCode":"06340","coordinates":{"lat":41.3668422,"lng":-72.07844349999999}},{"address1":"9176 Ellis Way","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8624095,"lng":-105.1574648}},{"address1":"5370 Business Park Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.317376,"lng":-86.232969}},{"address1":"1612 Beech Street","address2":"","city":"Louisville","state":"KY","postalCode":"40211","coordinates":{"lat":38.2296247,"lng":-85.805719}},{"address1":"8532 Ingalls Circle","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8532617,"lng":-105.0629712}},{"address1":"7941 Alpine View Circle","address2":"","city":"Anchorage","state":"AK","postalCode":"99507","coordinates":{"lat":61.1486467,"lng":-149.830947}},{"address1":"8595 West 81st Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8449341,"lng":-105.0937351}},{"address1":"4296 North Blossom Court","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.1288759,"lng":-94.1239252}},{"address1":"1738 Annabellas Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32407","coordinates":{"lat":30.1877596,"lng":-85.7782311}},{"address1":"3215 Madsen Street","address2":"","city":"Hayward","state":"CA","postalCode":"94541","coordinates":{"lat":37.6618825,"lng":-122.0904612}},{"address1":"4 Village Lake Drive","address2":"#4","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0994717,"lng":-94.1570279}},{"address1":"86 Russell Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.77985700000001,"lng":-72.525724}},{"address1":"570 Broadway","address2":"","city":"Lynnfield","state":"MA","postalCode":"01940","coordinates":{"lat":42.517525,"lng":-71.00125799999999}},{"address1":"1405 Monroe Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20017","coordinates":{"lat":38.93258,"lng":-76.98579699999999}},{"address1":"900 North Leverett Avenue","address2":"#126","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0754825,"lng":-94.1696884}},{"address1":"222 Quince Street","address2":"#2-B","city":"San Diego","state":"CA","postalCode":"92103","coordinates":{"lat":32.7368499,"lng":-117.162443}},{"address1":"370 Wallace Road","address2":"#D-28","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.078257,"lng":-86.724182}},{"address1":"6672 Urban Court","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.817946,"lng":-105.13477}},{"address1":"516 Southwest 60th Terrace","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73139","coordinates":{"lat":35.4051605,"lng":-97.5223633}},{"address1":"1513 Southeast 9th Street","address2":"","city":"Moore","state":"OK","postalCode":"73160","coordinates":{"lat":35.329431,"lng":-97.465397}},{"address1":"154 Byrd Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.161691,"lng":-85.59920199999999}},{"address1":"1106 Homer Avenue","address2":"","city":"Savannah","state":"GA","postalCode":"31405","coordinates":{"lat":32.0453896,"lng":-81.12456809999999}},{"address1":"1010 M Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.9054822,"lng":-77.0265494}},{"address1":"5420 Allison Street","address2":"#202","city":"Arvada","state":"CO","postalCode":"80002","coordinates":{"lat":39.7958727,"lng":-105.0858231}},{"address1":"20 Hacker Street","address2":"#3","city":"Worcester","state":"MA","postalCode":"01603","coordinates":{"lat":42.244896,"lng":-71.8175172}},{"address1":"732 Kevin Court","address2":"","city":"Oakland","state":"CA","postalCode":"94621","coordinates":{"lat":37.757904,"lng":-122.206479}},{"address1":"509 Franklin Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20017","coordinates":{"lat":38.9255849,"lng":-76.9990895}},{"address1":"23 Whitcomb Street","address2":"","city":"Springfield","state":"VT","postalCode":"05156","coordinates":{"lat":43.2987361,"lng":-72.4880749}},{"address1":"3377 Sandstone Court","address2":"","city":"Pleasanton","state":"CA","postalCode":"94588","coordinates":{"lat":37.680463,"lng":-121.860128}},{"address1":"14 Huntington Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7772379,"lng":-72.518456}},{"address1":"2802 US Highway 98","address2":"BLDG F","city":"Mexico Beach","state":"FL","postalCode":"32456","coordinates":{"lat":29.9474344,"lng":-85.4170788}},{"address1":"412 Virginia Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40222","coordinates":{"lat":38.2538807,"lng":-85.6152334}},{"address1":"1644 New Jersey Avenue Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.91233,"lng":-77.017736}},{"address1":"832 51st Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20019","coordinates":{"lat":38.9008832,"lng":-76.9273381}},{"address1":"894 Windmill Park Lane","address2":"","city":"Mountain View","state":"CA","postalCode":"94043","coordinates":{"lat":37.399505,"lng":-122.077478}},{"address1":"9636 Morar Road","address2":"","city":"Panama City","state":"FL","postalCode":"32409","coordinates":{"lat":30.324968,"lng":-85.620589}},{"address1":"9472 Noble Way","address2":"","city":"Arvada","state":"CO","postalCode":"80007","coordinates":{"lat":39.8690661,"lng":-105.1784169}},{"address1":"618 Staley Avenue","address2":"","city":"Hayward","state":"CA","postalCode":"94541","coordinates":{"lat":37.6629263,"lng":-122.091801}},{"address1":"8704 Bayberry Place","address2":"","city":"Plantation","state":"KY","postalCode":"40242","coordinates":{"lat":38.2814983,"lng":-85.5918425}},{"address1":"2506 West Madison Street","address2":"","city":"Louisville","state":"KY","postalCode":"40211","coordinates":{"lat":38.253755,"lng":-85.7933322}},{"address1":"840 Inglewood Drive","address2":"","city":"West Sacramento","state":"CA","postalCode":"95605","coordinates":{"lat":38.591235,"lng":-121.524984}},{"address1":"10 Dalry Lane","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.941447,"lng":-81.160151}},{"address1":"3301 Nora Lane","address2":"","city":"Louisville","state":"KY","postalCode":"40220","coordinates":{"lat":38.199844,"lng":-85.61509}},{"address1":"8304 Glaser Lane","address2":"","city":"Louisville","state":"KY","postalCode":"40291","coordinates":{"lat":38.1437892,"lng":-85.6080724}},{"address1":"3720 West 86th Avenue","address2":"APT F","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.142615,"lng":-149.949251}},{"address1":"3298 Chestnut Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20015","coordinates":{"lat":38.979577,"lng":-77.061088}},{"address1":"82 Fairfield Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7673619,"lng":-72.53831}},{"address1":"3138 P Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20007","coordinates":{"lat":38.9091118,"lng":-77.0629963}},{"address1":"80 Locust Avenue","address2":"#110","city":"Worcester","state":"MA","postalCode":"01604","coordinates":{"lat":42.266896,"lng":-71.762913}},{"address1":"2715 Thornbrook Court","address2":"","city":"Odenton","state":"MD","postalCode":"21113","coordinates":{"lat":39.06450299999999,"lng":-76.727459}},{"address1":"3579 2nd Avenue","address2":"","city":"Edgewater","state":"MD","postalCode":"21037","coordinates":{"lat":38.91283200000001,"lng":-76.5224099}},{"address1":"6739 Taft Court","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8189901,"lng":-105.1325295}},{"address1":"1528 Stafford Avenue","address2":"","city":"Hayward","state":"CA","postalCode":"94541","coordinates":{"lat":37.680081,"lng":-122.074569}},{"address1":"2024 Merrily Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36111","coordinates":{"lat":32.3328739,"lng":-86.28072999999999}},{"address1":"2034 Fairfax Road","address2":"","city":"Annapolis","state":"MD","postalCode":"21401","coordinates":{"lat":38.9734343,"lng":-76.5357427}},{"address1":"1430 East Audubon Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36111","coordinates":{"lat":32.328226,"lng":-86.28300399999999}},{"address1":"3652 East Blue Stone Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72764","coordinates":{"lat":36.139309,"lng":-94.1078069}},{"address1":"3302 Woodland Park Drive","address2":"#APT 000001","city":"Anchorage","state":"AK","postalCode":"99517","coordinates":{"lat":61.190512,"lng":-149.927286}},{"address1":"1771 Daisey Court","address2":"","city":"Millersville","state":"MD","postalCode":"21108","coordinates":{"lat":39.044662,"lng":-76.64797399999999}},{"address1":"406 East Waldburg Street","address2":"","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.064691,"lng":-81.092321}},{"address1":"11843 North 60th Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85304","coordinates":{"lat":33.594584,"lng":-112.188319}},{"address1":"9515 West 74th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.831067,"lng":-105.103952}},{"address1":"119 Antioch Pike","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.10072,"lng":-86.72331}},{"address1":"1157 1st Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.90538280000001,"lng":-77.0121662}},{"address1":"3578 Galindo Street","address2":"","city":"Oakland","state":"CA","postalCode":"94601","coordinates":{"lat":37.783471,"lng":-122.2149729}},{"address1":"12800 Saunders Road","address2":"","city":"Anchorage","state":"AK","postalCode":"99516","coordinates":{"lat":61.10499799999999,"lng":-149.746856}},{"address1":"5556 West Northview Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5433092,"lng":-112.1797889}},{"address1":"3617 Oak Grove Circle","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.333812,"lng":-86.21464499999999}},{"address1":"2443 Sierra Nevada Road","address2":"#N5","city":"Mammoth Lakes","state":"CA","postalCode":"93546","coordinates":{"lat":37.641304,"lng":-118.971489}},{"address1":"10124 Watsonville Road","address2":"","city":"Louisville","state":"KY","postalCode":"40272","coordinates":{"lat":38.105204,"lng":-85.820047}},{"address1":"2441 Chase Park Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36110","coordinates":{"lat":32.4266516,"lng":-86.2700112}},{"address1":"28 Wayne Avenue","address2":"","city":"Waltham","state":"MA","postalCode":"02453","coordinates":{"lat":42.3806325,"lng":-71.2015761}},{"address1":"3605 Normandy Place South","address2":"","city":"Nashville","state":"TN","postalCode":"37209","coordinates":{"lat":36.1459501,"lng":-86.8276312}},{"address1":"25538 Calaroga Avenue","address2":"","city":"Hayward","state":"CA","postalCode":"94545","coordinates":{"lat":37.642952,"lng":-122.098647}},{"address1":"1521 159th Avenue","address2":"","city":"San Leandro","state":"CA","postalCode":"94578","coordinates":{"lat":37.70179340000001,"lng":-122.1192658}},{"address1":"344 Island Road","address2":"","city":"Savannah","state":"GA","postalCode":"31406","coordinates":{"lat":31.927239,"lng":-81.09320199999999}},{"address1":"826 South Hancock Street","address2":"","city":"Louisville","state":"KY","postalCode":"40203","coordinates":{"lat":38.2408519,"lng":-85.744652}},{"address1":"2212 Greenville Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36107","coordinates":{"lat":32.3767039,"lng":-86.275049}},{"address1":"325 East 7th Street","address2":"","city":"Edmond","state":"OK","postalCode":"73034","coordinates":{"lat":35.6480391,"lng":-97.47550249999999}},{"address1":"7 Maple Hill Road","address2":"","city":"Aquinnah","state":"MA","postalCode":"02535","coordinates":{"lat":41.33201400000001,"lng":-70.8181309}},{"address1":"73455 Twentynine Palms Highway","address2":"","city":"Twentynine Palms","state":"CA","postalCode":"92277","coordinates":{"lat":34.1353352,"lng":-116.0598794}},{"address1":"410 West 89th Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99515","coordinates":{"lat":61.1402906,"lng":-149.8870399}},{"address1":"24147 Clinton Court","address2":"","city":"Hayward","state":"CA","postalCode":"94545","coordinates":{"lat":37.648857,"lng":-122.112388}},{"address1":"5620 Lilly Street","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.148082,"lng":-85.58977999999999}},{"address1":"207 Spruce Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7690054,"lng":-72.51569599999999}},{"address1":"236 Alden Road","address2":"","city":"Hayward","state":"CA","postalCode":"94541","coordinates":{"lat":37.682588,"lng":-122.112121}},{"address1":"467 North Mountain Ranch Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0706293,"lng":-94.2107741}},{"address1":"2042 High Street","address2":"","city":"Oakland","state":"CA","postalCode":"94601","coordinates":{"lat":37.776415,"lng":-122.209418}},{"address1":"6244 Sun River Drive","address2":"","city":"Sacramento","state":"CA","postalCode":"95824","coordinates":{"lat":38.512894,"lng":-121.41258}},{"address1":"8801 Rosshire Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40118","coordinates":{"lat":38.1216631,"lng":-85.7505505}},{"address1":"449 15th Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.896241,"lng":-76.983372}},{"address1":"4385 Wares Ferry Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36109","coordinates":{"lat":32.389301,"lng":-86.228872}},{"address1":"8546 North 59th Lane","address2":"#171","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.5615847,"lng":-112.1884147}},{"address1":"8262 Elvaton Road","address2":"","city":"Millersville","state":"MD","postalCode":"21108","coordinates":{"lat":39.12422,"lng":-76.610394}},{"address1":"7018 Russell Court","address2":"","city":"Arvada","state":"CO","postalCode":"80007","coordinates":{"lat":39.824701,"lng":-105.186699}},{"address1":"1353 West 27th Avenue","address2":"#APT 000004","city":"Anchorage","state":"AK","postalCode":"99503","coordinates":{"lat":61.19630069999999,"lng":-149.9098041}},{"address1":"1030 Lake Claire Drive","address2":"","city":"Annapolis","state":"MD","postalCode":"21409","coordinates":{"lat":39.048603,"lng":-76.448911}},{"address1":"10980 Splendor Loop","address2":"","city":"Anchorage","state":"AK","postalCode":"99577","coordinates":{"lat":61.319069,"lng":-149.563601}},{"address1":"36043 Soapberry Commons","address2":"","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.555484,"lng":-122.012744}},{"address1":"419 Wabasso Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40209","coordinates":{"lat":38.1812976,"lng":-85.7511801}},{"address1":"2098 Lower Newton Street","address2":"","city":"Saint Albans City","state":"VT","postalCode":"05478","coordinates":{"lat":44.843051,"lng":-73.106488}},{"address1":"115 Waddell Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7660221,"lng":-72.5477647}},{"address1":"463 East Rutgers Loop","address2":"","city":"Montgomery","state":"AL","postalCode":"36109","coordinates":{"lat":32.386378,"lng":-86.22309899999999}},{"address1":"31130 Meadowbrook Avenue","address2":"","city":"Hayward","state":"CA","postalCode":"94544","coordinates":{"lat":37.61744100000001,"lng":-122.038397}},{"address1":"8506 Laviento Drive","address2":"","city":"Anchorage","state":"AK","postalCode":"99515","coordinates":{"lat":61.143603,"lng":-149.8784269}},{"address1":"19404 North 77th Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6603179,"lng":-112.223814}},{"address1":"302 East Granada Street","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.1004549,"lng":-94.15316299999999}},{"address1":"9321 Amy Lane","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32407","coordinates":{"lat":30.186053,"lng":-85.79181899999999}},{"address1":"1156 Greenhill Road","address2":"","city":"Arnold","state":"MD","postalCode":"21012","coordinates":{"lat":39.052169,"lng":-76.48806499999999}},{"address1":"30 Curtis Road","address2":"#509","city":"Milton","state":"MA","postalCode":"02186","coordinates":{"lat":42.2660192,"lng":-71.0910829}},{"address1":"904 Shepherd Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.9396331,"lng":-77.0252273}},{"address1":"124 Crane Street","address2":"","city":"Panama City","state":"FL","postalCode":"32413","coordinates":{"lat":30.203032,"lng":-85.84606699999999}},{"address1":"15847 West 74th Place","address2":"","city":"Arvada","state":"CO","postalCode":"80007","coordinates":{"lat":39.832021,"lng":-105.178337}},{"address1":"435 Granite Street","address2":"","city":"Quincy","state":"MA","postalCode":"02169","coordinates":{"lat":42.2404974,"lng":-71.01624509999999}},{"address1":"4418 Signal Hill Road","address2":"","city":"Louisville","state":"KY","postalCode":"40207","coordinates":{"lat":38.27605399999999,"lng":-85.650572}},{"address1":"2285 Wold Run Drive","address2":"#1","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0992725,"lng":-94.19149589999999}},{"address1":"110 Castle Hill","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7820711,"lng":-72.4827912}},{"address1":"8474 Chase Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8522641,"lng":-105.0715699}},{"address1":"4074 North Sunflower Circle","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.125209,"lng":-94.1317431}},{"address1":"249 Yellow Leaf Circle","address2":"","city":"Anchorage","state":"AK","postalCode":"99504","coordinates":{"lat":61.221345,"lng":-149.71888}},{"address1":"8010 Holland Court","address2":"D","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.84229029999999,"lng":-105.1030368}},{"address1":"1300 East Dowling Road","address2":"","city":"Anchorage","state":"AK","postalCode":"99518","coordinates":{"lat":61.1663648,"lng":-149.858972}},{"address1":"189 Danforth Street","address2":"","city":"Framingham","state":"MA","postalCode":"01701","coordinates":{"lat":42.3259861,"lng":-71.39104990000001}},{"address1":"1011 Bell Avenue","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21060","coordinates":{"lat":39.177114,"lng":-76.59223899999999}},{"address1":"5224 Wasena Avenue","address2":"","city":"Baltimore","state":"MD","postalCode":"21225","coordinates":{"lat":39.223779,"lng":-76.60339499999999}},{"address1":"7613 Yule Court","address2":"","city":"Arvada","state":"CO","postalCode":"80007","coordinates":{"lat":39.834511,"lng":-105.202472}},{"address1":"1243 Doris Avenue","address2":"","city":"Pasadena","state":"MD","postalCode":"21122","coordinates":{"lat":39.109591,"lng":-76.486294}},{"address1":"3504 East 5th Street","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.156461,"lng":-85.61573399999999}},{"address1":"1 Dunsmuir Lane","address2":"","city":"Savannah","state":"GA","postalCode":"31411","coordinates":{"lat":31.891353,"lng":-81.053618}},{"address1":"1320 Dunbarton Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.401737,"lng":-86.19376799999999}},{"address1":"14524 Lodestar Drive","address2":"","city":"Grass Valley","state":"CA","postalCode":"95949","coordinates":{"lat":39.101221,"lng":-121.008546}},{"address1":"8404 West Myrtle Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85305","coordinates":{"lat":33.5414927,"lng":-112.2400905}},{"address1":"620 Oakland Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.072612,"lng":-94.17295999999999}},{"address1":"39 Cottage Street","address2":"","city":"Athol","state":"MA","postalCode":"01331","coordinates":{"lat":42.5926786,"lng":-72.2271482}},{"address1":"82 Lookout Mountain Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.75723,"lng":-72.491035}},{"address1":"1635 Generals Highway","address2":"","city":"Annapolis","state":"MD","postalCode":"21401","coordinates":{"lat":39.0139641,"lng":-76.5724717}},{"address1":"555 North Dupont Avenue","address2":"#C-55","city":"Nashville","state":"TN","postalCode":"37115","coordinates":{"lat":36.268033,"lng":-86.6999979}},{"address1":"2505 North Hampton Court","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0959268,"lng":-94.1238079}},{"address1":"136 Acacia Drive","address2":"","city":"Blue Lake","state":"CA","postalCode":"95525","coordinates":{"lat":40.879484,"lng":-123.978726}},{"address1":"22825 North 74th Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85310","coordinates":{"lat":33.691213,"lng":-112.219428}},{"address1":"643 Farragut Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20011","coordinates":{"lat":38.951281,"lng":-77.021523}},{"address1":"17 West 26th Circle","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.033699,"lng":-94.15958800000001}},{"address1":"335 C Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20003","coordinates":{"lat":38.8858796,"lng":-77.00075350000002}},{"address1":"1418 Paddocks Court","address2":"","city":"Crownsville","state":"MD","postalCode":"21032","coordinates":{"lat":39.05389,"lng":-76.623632}},{"address1":"2917 Miramar Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.107054,"lng":-94.2004709}},{"address1":"301 Argonaut Street","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.20514,"lng":-85.84755899999999}},{"address1":"12901 Mission Circle","address2":"","city":"Anchorage","state":"AK","postalCode":"99516","coordinates":{"lat":61.10380240000001,"lng":-149.8253975}},{"address1":"3013 Sprowl Road","address2":"#4","city":"Jeffersontown","state":"KY","postalCode":"40299","coordinates":{"lat":38.1966913,"lng":-85.5693363}},{"address1":"5929 West Via Montoya Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85310","coordinates":{"lat":33.68642,"lng":-112.188159}},{"address1":"325 Joseph Circle","address2":"","city":"Southport","state":"FL","postalCode":"32409","coordinates":{"lat":30.407817,"lng":-85.684715}},{"address1":"922 Urciolo Court","address2":"","city":"Annapolis","state":"MD","postalCode":"21401","coordinates":{"lat":38.979099,"lng":-76.57732589999999}},{"address1":"2212 Daffin Drive","address2":"","city":"Savannah","state":"GA","postalCode":"31404","coordinates":{"lat":32.027338,"lng":-81.07870799999999}},{"address1":"1401 Cordova Street","address2":"#APT 000006","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.20849370000001,"lng":-149.8792198}},{"address1":"8064 Claytie Circle","address2":"","city":"Nashville","state":"TN","postalCode":"37221","coordinates":{"lat":36.06466899999999,"lng":-86.976433}},{"address1":"566 Middle Turnpike East","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7850955,"lng":-72.4967557}},{"address1":"93 Hamlin Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7735186,"lng":-72.5152106}},{"address1":"123 Remember Baker Lane","address2":"","city":"Hartford","state":"VT","postalCode":"05001","coordinates":{"lat":43.6696484,"lng":-72.4299719}},{"address1":"125 Connors Street","address2":"#516","city":"Gardner","state":"MA","postalCode":"01440","coordinates":{"lat":42.5738871,"lng":-71.9966865}},{"address1":"2315 Chestnut Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36107","coordinates":{"lat":32.367382,"lng":-86.27867599999999}},{"address1":"2716 30th Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20020","coordinates":{"lat":38.855798,"lng":-76.96482499999999}},{"address1":"2406 Lindbergh Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40208","coordinates":{"lat":38.215833,"lng":-85.775153}},{"address1":"2035 Ninth Street","address2":"R A","city":"Berkeley","state":"CA","postalCode":"94710","coordinates":{"lat":37.8676351,"lng":-122.2938418}},{"address1":"34 Holyoke Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.753855,"lng":-72.498972}},{"address1":"2276 West Woodley Square","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.3256494,"lng":-86.2702235}},{"address1":"20251 North 75th Avenue","address2":"#1046","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6696067,"lng":-112.2196548}},{"address1":"72 Bentley Avenue","address2":"","city":"Poultney","state":"VT","postalCode":"05764","coordinates":{"lat":43.5158214,"lng":-73.2343441}},{"address1":"2807 Huxley Place","address2":"","city":"Fremont","state":"CA","postalCode":"94555","coordinates":{"lat":37.584941,"lng":-122.03291}},{"address1":"7772 West Palmaire Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85303","coordinates":{"lat":33.540431,"lng":-112.227013}},{"address1":"82 Linnmore Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.777262,"lng":-72.54537499999999}},{"address1":"882 Plantation Way","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.400186,"lng":-86.20771099999999}},{"address1":"8150 North 61st Avenue","address2":"#3128","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.555668,"lng":-112.1926295}},{"address1":"503 Orchard Road","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21061","coordinates":{"lat":39.19076099999999,"lng":-76.64618}},{"address1":"3616 Echo Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37218","coordinates":{"lat":36.236713,"lng":-86.833956}},{"address1":"376 Whites Road","address2":"","city":"Wilmington","state":"VT","postalCode":"05363","coordinates":{"lat":42.880951,"lng":-72.84163699999999}},{"address1":"322 East Taylor Street","address2":"#1103","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.0706543,"lng":-81.0908408}},{"address1":"605 Main Street","address2":"","city":"Watertown","state":"MA","postalCode":"02472","coordinates":{"lat":42.373378,"lng":-71.202116}},{"address1":"238 West Rock Street","address2":"#4","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0609635,"lng":-94.1628029}},{"address1":"1819 Q Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20020","coordinates":{"lat":38.870406,"lng":-76.978219}},{"address1":"1261 Sioux Terrace","address2":"","city":"Nashville","state":"TN","postalCode":"37115","coordinates":{"lat":36.247799,"lng":-86.670508}},{"address1":"7002 Secrest Court","address2":"","city":"Arvada","state":"CO","postalCode":"80007","coordinates":{"lat":39.8236009,"lng":-105.1901759}},{"address1":"169 Avenida Drive","address2":"M","city":"Berkeley","state":"CA","postalCode":"94708","coordinates":{"lat":37.884824,"lng":-122.249694}},{"address1":"6095 Terry Lane","address2":"","city":"Golden","state":"CO","postalCode":"80403","coordinates":{"lat":39.807376,"lng":-105.191019}},{"address1":"3620 Colmar Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40211","coordinates":{"lat":38.235977,"lng":-85.81636}},{"address1":"8820 Vaughn Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.337777,"lng":-86.13765590000001}},{"address1":"113 Hammarlee Road","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21060","coordinates":{"lat":39.177265,"lng":-76.602519}},{"address1":"281 MacArthur Boulevard","address2":"","city":"Oakland","state":"CA","postalCode":"94610","coordinates":{"lat":37.8147324,"lng":-122.25217}},{"address1":"8159 West 81st Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.843993,"lng":-105.089124}},{"address1":"512 North Center Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.15768199999999,"lng":-85.6292129}},{"address1":"4876 Norris Road","address2":"","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.543515,"lng":-122.008143}},{"address1":"8378 Cole Street","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8479398,"lng":-105.1526049}},{"address1":"2406 Brighton Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40205","coordinates":{"lat":38.217094,"lng":-85.66769599999999}},{"address1":"19 Heritage","address2":"","city":"Oakland","state":"CA","postalCode":"94605","coordinates":{"lat":37.765568,"lng":-122.129528}},{"address1":"6228 West Larkspur Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85304","coordinates":{"lat":33.600267,"lng":-112.193207}},{"address1":"2504 Longest Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40204","coordinates":{"lat":38.239449,"lng":-85.7079849}},{"address1":"3 Mad Anthony Lane","address2":"","city":"Savannah","state":"GA","postalCode":"31411","coordinates":{"lat":31.949414,"lng":-81.02015399999999}},{"address1":"2248 South Sutherland Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.331721,"lng":-86.19776999999999}},{"address1":"330 Michell Court","address2":"","city":"Livermore","state":"CA","postalCode":"94551","coordinates":{"lat":37.690035,"lng":-121.759468}},{"address1":"6748 West San Juan Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85303","coordinates":{"lat":33.518939,"lng":-112.205511}},{"address1":"1734 Tamarack Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20012","coordinates":{"lat":38.993375,"lng":-77.04060299999999}},{"address1":"915 Arkansas Avenue","address2":"","city":"Lynn Haven","state":"FL","postalCode":"32444","coordinates":{"lat":30.244151,"lng":-85.6392089}},{"address1":"116 Queens Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37218","coordinates":{"lat":36.214841,"lng":-86.859562}},{"address1":"8 Linden Circle","address2":"","city":"Somerville","state":"MA","postalCode":"02143","coordinates":{"lat":42.3879993,"lng":-71.11345200000001}},{"address1":"4 Chamois Court","address2":"","city":"Pooler","state":"GA","postalCode":"31322","coordinates":{"lat":32.088701,"lng":-81.24825}},{"address1":"6941 West 87th Way","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.852809,"lng":-105.073449}},{"address1":"354 North University Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0659848,"lng":-94.16817080000001}},{"address1":"6145 East Castro Valley Boulevard","address2":"","city":"Castro Valley","state":"CA","postalCode":"94552","coordinates":{"lat":37.6992206,"lng":-122.0300502}},{"address1":"1401 Saint George Avenue","address2":"","city":"Moore","state":"OK","postalCode":"73160","coordinates":{"lat":35.3503092,"lng":-97.5079329}},{"address1":"1713 Arrow Cove Lane","address2":"","city":"Annapolis","state":"MD","postalCode":"21401","coordinates":{"lat":39.00848999999999,"lng":-76.53611699999999}},{"address1":"56 Gardner Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7630186,"lng":-72.5033322}},{"address1":"327 Idlewylde Drive","address2":"#3","city":"Louisville","state":"KY","postalCode":"40206","coordinates":{"lat":38.260003,"lng":-85.70065199999999}},{"address1":"18789 Crane Avenue","address2":"","city":"Castro Valley","state":"CA","postalCode":"94546","coordinates":{"lat":37.70902600000001,"lng":-122.059504}},{"address1":"814 East 10th Court","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.166997,"lng":-85.648022}},{"address1":"6431 Shattuck Avenue","address2":"B","city":"Oakland","state":"CA","postalCode":"94609","coordinates":{"lat":37.85015,"lng":-122.266142}},{"address1":"4719 Bayou Bluff Trail","address2":"","city":"Lynn Haven","state":"FL","postalCode":"32444","coordinates":{"lat":30.236109,"lng":-85.599884}},{"address1":"24 Lambert Street","address2":"","city":"Medford","state":"MA","postalCode":"02155","coordinates":{"lat":42.4235908,"lng":-71.093309}},{"address1":"1318 35th Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20007","coordinates":{"lat":38.90724700000001,"lng":-77.0690174}},{"address1":"4807 North Grove Avenue","address2":"","city":"Warr Acres","state":"OK","postalCode":"73122","coordinates":{"lat":35.5203601,"lng":-97.6147122}},{"address1":"4408 Bonaparte Boulevard","address2":"","city":"Midwest City","state":"OK","postalCode":"73110","coordinates":{"lat":35.482651,"lng":-97.38337399999999}},{"address1":"73 Twin Hills Drive","address2":"","city":"Longmeadow","state":"MA","postalCode":"01106","coordinates":{"lat":42.0420378,"lng":-72.5428872}},{"address1":"34 Harris Street","address2":"#6","city":"Brookline","state":"MA","postalCode":"02446","coordinates":{"lat":42.3382219,"lng":-71.12330899999999}},{"address1":"22352 North 67th Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85310","coordinates":{"lat":33.686126,"lng":-112.203991}},{"address1":"11522 Country Spring Court","address2":"","city":"Cupertino","state":"CA","postalCode":"95014","coordinates":{"lat":37.3004559,"lng":-122.049009}},{"address1":"21 Soling Avenue","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":32.0376484,"lng":-81.2540562}},{"address1":"302 Mcmillin Street","address2":"","city":"Nashville","state":"TN","postalCode":"37203","coordinates":{"lat":36.1583239,"lng":-86.7947425}},{"address1":"129 Grant Street","address2":"","city":"Redlands","state":"CA","postalCode":"92373","coordinates":{"lat":34.0529643,"lng":-117.1847245}},{"address1":"3035 South Highway A1A","address2":"#3B","city":"Melbourne Beach","state":"FL","postalCode":"32951","coordinates":{"lat":28.0357085,"lng":-80.54249569999999}},{"address1":"1637 Acre Circle","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32407","coordinates":{"lat":30.18644399999999,"lng":-85.78322299999999}},{"address1":"130 West Brown Road","address2":"","city":"Mesa","state":"AZ","postalCode":"85201","coordinates":{"lat":33.4356918,"lng":-111.8348295}},{"address1":"2632 Jackson Street East","address2":"","city":"Carson","state":"CA","postalCode":"90810","coordinates":{"lat":33.8360282,"lng":-118.2202665}},{"address1":"4503 North Council Road","address2":"","city":"Bethany","state":"OK","postalCode":"73008","coordinates":{"lat":35.5176604,"lng":-97.65550879999999}},{"address1":"119 Redwood Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.751289,"lng":-72.563575}},{"address1":"5721 Frank Hough Road","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.23643,"lng":-85.559361}},{"address1":"2917 Danzig Place","address2":"#102","city":"Louisville","state":"KY","postalCode":"40245","coordinates":{"lat":38.280137,"lng":-85.49418639999999}},{"address1":"26563 Chisholm Court","address2":"","city":"Hayward","state":"CA","postalCode":"94544","coordinates":{"lat":37.641711,"lng":-122.078659}},{"address1":"4221 East Mission Boulevard","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0954898,"lng":-94.10028220000001}},{"address1":"6021 Yarrow Street","address2":"#A1","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.806803,"lng":-105.084306}},{"address1":"7102 North 43rd Avenue","address2":"#160","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5415384,"lng":-112.1514119}},{"address1":"3386 Sudlersville South","address2":"","city":"Laurel","state":"MD","postalCode":"20724","coordinates":{"lat":39.089731,"lng":-76.81937599999999}},{"address1":"6022 West Alice Avenue","address2":"#3","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.5640709,"lng":-112.1893361}},{"address1":"580 Hollow Wood Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36109","coordinates":{"lat":32.3914018,"lng":-86.2181083}},{"address1":"435 East 5th Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.217854,"lng":-149.875705}},{"address1":"6713 Holt Road","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.013723,"lng":-86.729686}},{"address1":"5605 North Terry Avenue","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73111","coordinates":{"lat":35.526483,"lng":-97.4830379}},{"address1":"412 West Ila Street","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.071266,"lng":-94.165154}},{"address1":"9403 Fairground Road","address2":"","city":"Louisville","state":"KY","postalCode":"40291","coordinates":{"lat":38.17058,"lng":-85.5852139}},{"address1":"6049 Quail Street","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.806876,"lng":-105.1239949}},{"address1":"17 Hillcrest Road","address2":"","city":"Rutland","state":"VT","postalCode":"05701","coordinates":{"lat":43.6216373,"lng":-72.9688374}},{"address1":"424 Callan Avenue","address2":"#216","city":"San Leandro","state":"CA","postalCode":"94577","coordinates":{"lat":37.72780789999999,"lng":-122.152331}},{"address1":"105 Gilmore Street","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21061","coordinates":{"lat":39.176817,"lng":-76.630884}},{"address1":"910 Arlington Terrace","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.077652,"lng":-94.14529000000002}},{"address1":"2204 7th Street Road","address2":"#12","city":"Louisville","state":"KY","postalCode":"40208","coordinates":{"lat":38.218784,"lng":-85.7800649}},{"address1":"11 North Vineyard Drive","address2":"","city":"Pueblo West","state":"CO","postalCode":"81007","coordinates":{"lat":38.318953,"lng":-104.680591}},{"address1":"3505 Albee Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37076","coordinates":{"lat":36.181781,"lng":-86.611408}},{"address1":"689 Stableway Road","address2":"","city":"Pike Road","state":"AL","postalCode":"36064","coordinates":{"lat":32.354837,"lng":-86.076679}},{"address1":"102 East Cydnee Street","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.10683,"lng":-94.155547}},{"address1":"208 Towne Lake Way","address2":"","city":"Pooler","state":"GA","postalCode":"31322","coordinates":{"lat":32.137605,"lng":-81.25850600000001}},{"address1":"2555 West 69th Court","address2":"","city":"Anchorage","state":"AK","postalCode":"99502","coordinates":{"lat":61.158468,"lng":-149.933297}},{"address1":"58 Rice Street Southwest","address2":"","city":"Washington","state":"DC","postalCode":"20032","coordinates":{"lat":38.83841899999999,"lng":-77.0113105}},{"address1":"2961 Vinson Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36110","coordinates":{"lat":32.42687530000001,"lng":-86.2080404}},{"address1":"172 Chestnut Street","address2":"","city":"Lynn","state":"MA","postalCode":"01902","coordinates":{"lat":42.4696809,"lng":-70.93746680000001}},{"address1":"307 Meadowood Court","address2":"","city":"Lynn Haven","state":"FL","postalCode":"32444","coordinates":{"lat":30.237071,"lng":-85.60347}},{"address1":"403 Turkey Creek Road","address2":"","city":"Mathews","state":"AL","postalCode":"36052","coordinates":{"lat":32.220426,"lng":-86.059168}},{"address1":"11 Rosewood Lane","address2":"","city":"Essex","state":"VT","postalCode":"05452","coordinates":{"lat":44.4912319,"lng":-73.097297}},{"address1":"102 Old Depot Road","address2":"#14","city":"Farmington","state":"AR","postalCode":"72730","coordinates":{"lat":36.040414,"lng":-94.245223}},{"address1":"9 Pierce Road","address2":"","city":"Watertown","state":"MA","postalCode":"02472","coordinates":{"lat":42.380059,"lng":-71.19283399999999}},{"address1":"15254 North 52nd Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.6244609,"lng":-112.171094}},{"address1":"11140 West 60th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.805639,"lng":-105.122694}},{"address1":"803 18th Avenue South","address2":"","city":"Nashville","state":"TN","postalCode":"37203","coordinates":{"lat":36.1500199,"lng":-86.79477}},{"address1":"918 Cheryl Ann Circle","address2":"","city":"Hayward","state":"CA","postalCode":"94544","coordinates":{"lat":37.635859,"lng":-122.076923}},{"address1":"1328 Jenks Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.1726222,"lng":-85.6620902}},{"address1":"2201 Marks Mill Lane","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0917726,"lng":-94.15142089999999}},{"address1":"12371 Atlanta Highway","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.369194,"lng":-86.06518799999999}},{"address1":"3437 Sommerville Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36111","coordinates":{"lat":32.342288,"lng":-86.256546}},{"address1":"829 Dunbarton Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.397179,"lng":-86.205326}},{"address1":"8 Kozera Avenue","address2":"","city":"Hadley","state":"MA","postalCode":"01035","coordinates":{"lat":42.36135549999999,"lng":-72.57288930000001}},{"address1":"89 High Ledge Circle","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7495971,"lng":-72.476336}},{"address1":"35 Lakewood Circle South","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.754591,"lng":-72.52192000000001}},{"address1":"2222 Martin Luther King Junior Boulevard","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0554972,"lng":-94.1910602}},{"address1":"1720 Quacco Road","address2":"A","city":"Pooler","state":"GA","postalCode":"31322","coordinates":{"lat":32.062374,"lng":-81.269502}},{"address1":"116 Jourdan Street","address2":"","city":"Hinesburg","state":"VT","postalCode":"05461","coordinates":{"lat":44.347454,"lng":-73.08877600000001}},{"address1":"2507 R Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20020","coordinates":{"lat":38.869211,"lng":-76.970202}},{"address1":"4719 West Cochise Drive","address2":"","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.580297,"lng":-112.161185}},{"address1":"1838 Crofton Parkway","address2":"","city":"Crofton","state":"MD","postalCode":"21114","coordinates":{"lat":38.9983069,"lng":-76.67975299999999}},{"address1":"26 Seaman Circle","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7668725,"lng":-72.5461613}},{"address1":"2572 Drake Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.342203,"lng":-86.33643599999999}},{"address1":"4231 Miramonte Way","address2":"","city":"Union City","state":"CA","postalCode":"94587","coordinates":{"lat":37.591721,"lng":-122.075993}},{"address1":"2508 Grant Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.193964,"lng":-85.712509}},{"address1":"6505 South Lagoon Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32408","coordinates":{"lat":30.155249,"lng":-85.76467099999999}},{"address1":"2032 Gorgas Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36106","coordinates":{"lat":32.357466,"lng":-86.27658699999999}},{"address1":"1129 I Street","address2":"","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.2110743,"lng":-149.899634}},{"address1":"5201 North Miller Avenue","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73112","coordinates":{"lat":35.523283,"lng":-97.561933}},{"address1":"1987 Boxer Court","address2":"","city":"San Lorenzo","state":"CA","postalCode":"94580","coordinates":{"lat":37.670738,"lng":-122.147019}},{"address1":"3219 Lakeshore Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37138","coordinates":{"lat":36.242959,"lng":-86.625265}},{"address1":"415 West 42nd Street","address2":"","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.0543472,"lng":-81.1064222}},{"address1":"5792 Owl Hill Avenue","address2":"","city":"Santa Rosa","state":"CA","postalCode":"95409","coordinates":{"lat":38.467127,"lng":-122.640498}},{"address1":"6816 West 84th Circle","address2":"#42","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.848863,"lng":-105.0735009}},{"address1":"1900 West Virginia Avenue Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.9114897,"lng":-76.9847941}},{"address1":"2936 State Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.202236,"lng":-85.66611499999999}},{"address1":"2604 13th Street","address2":"","city":"Savannah","state":"GA","postalCode":"31408","coordinates":{"lat":32.092738,"lng":-81.17643199999999}},{"address1":"10304 North 179th Drive","address2":"","city":"Waddell","state":"AZ","postalCode":"85355","coordinates":{"lat":33.5780134,"lng":-112.4458901}},{"address1":"8142 Mallard Shore Drive","address2":"","city":"Laurel","state":"MD","postalCode":"20724","coordinates":{"lat":39.112812,"lng":-76.80575499999999}},{"address1":"653 Stratton Arlington Road","address2":"","city":"Stratton","state":"VT","postalCode":"05360","coordinates":{"lat":43.04115300000001,"lng":-72.90772199999999}},{"address1":"2414 Parker Street","address2":"#R 16","city":"Berkeley","state":"CA","postalCode":"94704","coordinates":{"lat":37.862903,"lng":-122.2595092}},{"address1":"43 Westminster Street","address2":"","city":"Pittsfield","state":"MA","postalCode":"01201","coordinates":{"lat":42.458409,"lng":-73.23273499999999}},{"address1":"422 C Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.8942029,"lng":-76.99988809999999}},{"address1":"535 Saddlewood Lane","address2":"","city":"Montgomery","state":"AL","postalCode":"36109","coordinates":{"lat":32.39012,"lng":-86.218373}},{"address1":"7910 West Krall Street","address2":"","city":"Glendale","state":"AZ","postalCode":"85303","coordinates":{"lat":33.534019,"lng":-112.2299964}},{"address1":"1600 20th Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20009","coordinates":{"lat":38.9113128,"lng":-77.0451932}},{"address1":"1217 Bay Street","address2":"#318-A","city":"Tybee Island","state":"GA","postalCode":"31328","coordinates":{"lat":32.0222005,"lng":-80.8587482}},{"address1":"7645 Marshall Street","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.835952,"lng":-105.070063}},{"address1":"717 Joseph Avenue","address2":"","city":"Nashville","state":"TN","postalCode":"37207","coordinates":{"lat":36.183641,"lng":-86.772214}},{"address1":"2106 Standard Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40210","coordinates":{"lat":38.231378,"lng":-85.7922619}},{"address1":"316 20th Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.8939527,"lng":-76.97642739999999}},{"address1":"227 West Montgomery Cross Road","address2":"#736","city":"Savannah","state":"GA","postalCode":"31406","coordinates":{"lat":31.998812,"lng":-81.134464}},{"address1":"310 12th Avenue","address2":"","city":"Santa Cruz","state":"CA","postalCode":"95062","coordinates":{"lat":36.963154,"lng":-121.994045}},{"address1":"2685 California Street","address2":"#APT 305","city":"Mountain View","state":"CA","postalCode":"94040","coordinates":{"lat":37.4068693,"lng":-122.1129728}},{"address1":"6460 Vermont 113","address2":"","city":"Vershire","state":"VT","postalCode":"05079","coordinates":{"lat":43.9678972,"lng":-72.3154863}},{"address1":"8404 South Villa Avenue","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73159","coordinates":{"lat":35.3818163,"lng":-97.5570041}},{"address1":"7030 West Krall Street","address2":"","city":"Glendale","state":"AZ","postalCode":"85303","coordinates":{"lat":33.534067,"lng":-112.210763}},{"address1":"189 Dalton Avenue","address2":"","city":"Pittsfield","state":"MA","postalCode":"01201","coordinates":{"lat":42.459217,"lng":-73.22532799999999}},{"address1":"2455 Manchester Drive","address2":"","city":"The Village","state":"OK","postalCode":"73120","coordinates":{"lat":35.576392,"lng":-97.55644629999999}},{"address1":"2405 230th Street","address2":"","city":"Pasadena","state":"MD","postalCode":"21122","coordinates":{"lat":39.12585,"lng":-76.549013}},{"address1":"589 East Main Street","address2":"","city":"Newport","state":"VT","postalCode":"05855","coordinates":{"lat":44.943275,"lng":-72.19193299999999}},{"address1":"1520 H Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20006","coordinates":{"lat":38.90021429999999,"lng":-77.0351541}},{"address1":"4603 Grant Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20019","coordinates":{"lat":38.8983173,"lng":-76.9364561}},{"address1":"171 Brickhill Circle","address2":"","city":"Pooler","state":"GA","postalCode":"31322","coordinates":{"lat":32.175349,"lng":-81.25099}},{"address1":"607 North 46th Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0741371,"lng":-94.22645829999999}},{"address1":"9134 Brook Park Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.3076534,"lng":-86.1451185}},{"address1":"2134 West Mills Drive","address2":"","city":"Orange","state":"CA","postalCode":"92868","coordinates":{"lat":33.786584,"lng":-117.875665}},{"address1":"2 Cockle Shell Road","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.960368,"lng":-81.229034}},{"address1":"1431 King George Boulevard","address2":"#21-C","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.9775273,"lng":-81.2259819}},{"address1":"1804 Calhoun Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.181413,"lng":-85.693748}},{"address1":"23 Florida Avenue Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.910125,"lng":-77.00808099999999}},{"address1":"5630 Silverado Way","address2":"#STE A8","city":"Anchorage","state":"AK","postalCode":"99518","coordinates":{"lat":61.1695128,"lng":-149.8896842}},{"address1":"11300 Lillian Lane","address2":"","city":"Anchorage","state":"AK","postalCode":"99515","coordinates":{"lat":61.11845399999999,"lng":-149.881223}},{"address1":"2209 East Manor Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.075132,"lng":-94.12903399999999}},{"address1":"8325 Northwest 19th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73127","coordinates":{"lat":35.48856,"lng":-97.66233199999999}},{"address1":"6925 Lariat Lane","address2":"","city":"Castro Valley","state":"CA","postalCode":"94552","coordinates":{"lat":37.7157257,"lng":-122.0270913}},{"address1":"6721 Boundary Run","address2":"","city":"Nashville","state":"TN","postalCode":"37221","coordinates":{"lat":36.087655,"lng":-87.006136}},{"address1":"1700 William E Summers III Avenue","address2":"#201","city":"Louisville","state":"KY","postalCode":"40211","coordinates":{"lat":38.22952540000001,"lng":-85.82045680000002}},{"address1":"14 6th Street","address2":"#1","city":"Medford","state":"MA","postalCode":"02155","coordinates":{"lat":42.4074868,"lng":-71.07807670000001}},{"address1":"11865 West 74th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.830545,"lng":-105.131624}},{"address1":"912 Countryside Lane","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.404751,"lng":-86.18589899999999}},{"address1":"6080 Frontier Lane","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.030597,"lng":-86.73436}},{"address1":"1124 Bluewillow Court","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.040783,"lng":-86.577798}},{"address1":"17722 North 79th Avenue","address2":"#1135","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.646496,"lng":-112.2317614}},{"address1":"6 Oak Street","address2":"","city":"Town of Rockingham","state":"VT","postalCode":"05101","coordinates":{"lat":43.134108,"lng":-72.449474}},{"address1":"1537 Northwest 123rd Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73120","coordinates":{"lat":35.5961896,"lng":-97.53951699999999}},{"address1":"10001 Pheasant Lane","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73162","coordinates":{"lat":35.571646,"lng":-97.63995700000001}},{"address1":"10340 West 62nd Place","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.8101545,"lng":-105.1135667}},{"address1":"52 Oleary Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7716925,"lng":-72.5521002}},{"address1":"15082 North 59th Avenue","address2":"#111","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.6231673,"lng":-112.1871757}},{"address1":"7047 Vinson Road","address2":"","city":"Panama City","state":"FL","postalCode":"32413","coordinates":{"lat":30.336868,"lng":-85.829662}},{"address1":"200 Edson Road","address2":"","city":"Windham","state":"VT","postalCode":"05359","coordinates":{"lat":43.2215166,"lng":-72.7049368}},{"address1":"150 Manistee Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.235428,"lng":-85.89155099999999}},{"address1":"2335 Orchard View Lane","address2":"","city":"Escondido","state":"CA","postalCode":"92027","coordinates":{"lat":33.119461,"lng":-117.007959}},{"address1":"65 Clark Street","address2":"#2","city":"Newton","state":"MA","postalCode":"02459","coordinates":{"lat":42.321396,"lng":-71.1995577}},{"address1":"18318 Pioneer Drive","address2":"","city":"Anchorage","state":"AK","postalCode":"99577","coordinates":{"lat":61.364421,"lng":-149.540056}},{"address1":"110 Elmwood Avenue","address2":"","city":"Barre","state":"VT","postalCode":"05641","coordinates":{"lat":44.2097089,"lng":-72.50493600000001}},{"address1":"4800 Huffman Road","address2":"","city":"Anchorage","state":"AK","postalCode":"99516","coordinates":{"lat":61.10827899999999,"lng":-149.791977}},{"address1":"8219 Minor Lane","address2":"#9","city":"Louisville","state":"KY","postalCode":"40219","coordinates":{"lat":38.12841,"lng":-85.7107249}},{"address1":"10129 Spring Gate Drive","address2":"","city":"Louisville","state":"KY","postalCode":"40241","coordinates":{"lat":38.312891,"lng":-85.562299}},{"address1":"65 Arcellia Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.788139,"lng":-72.491989}},{"address1":"12460 West Solano Drive","address2":"","city":"Litchfield Park","state":"AZ","postalCode":"85340","coordinates":{"lat":33.520308,"lng":-112.3275521}},{"address1":"618 Watts Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36104","coordinates":{"lat":32.37152700000001,"lng":-86.294285}},{"address1":"5805 Armada Drive","address2":"","city":"Carlsbad","state":"CA","postalCode":"92008","coordinates":{"lat":33.1238541,"lng":-117.3152497}},{"address1":"1644 Queenstown Road","address2":"","city":"Nichols Hills","state":"OK","postalCode":"73116","coordinates":{"lat":35.542511,"lng":-97.547282}},{"address1":"143 Main Street","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.7886316,"lng":-72.52390249999999}},{"address1":"226 Tranquility Lane","address2":"","city":"Saint Albans Town","state":"VT","postalCode":"05488","coordinates":{"lat":44.8389381,"lng":-73.18372149999999}},{"address1":"831 21st Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.9011079,"lng":-76.974034}},{"address1":"22825 Paseo Place","address2":"","city":"Hayward","state":"CA","postalCode":"94541","coordinates":{"lat":37.6678961,"lng":-122.0832649}},{"address1":"2902 Flint Street","address2":"","city":"Union City","state":"CA","postalCode":"94587","coordinates":{"lat":37.60442,"lng":-122.069607}},{"address1":"919 Windsor Avenue","address2":"","city":"Annapolis","state":"MD","postalCode":"21403","coordinates":{"lat":38.968518,"lng":-76.4905689}},{"address1":"6041 North 72nd Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85303","coordinates":{"lat":33.525117,"lng":-112.215039}},{"address1":"163 Highwood Drive","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.76664299999999,"lng":-72.490877}},{"address1":"1334 East 14th Avenue","address2":"#APT 000004","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.208547,"lng":-149.857294}},{"address1":"223 Goose Pond Road","address2":"","city":"Fairfax","state":"VT","postalCode":"05454","coordinates":{"lat":44.653053,"lng":-72.971587}},{"address1":"1021 North Center Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.1670475,"lng":-85.6292984}},{"address1":"1559 Alabama Avenue Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20032","coordinates":{"lat":38.8467679,"lng":-76.98076200000001}},{"address1":"1238 Roanwood Way","address2":"","city":"Concord","state":"CA","postalCode":"94521","coordinates":{"lat":37.94042,"lng":-121.944464}},{"address1":"2068 Happy Lane","address2":"","city":"Crofton","state":"MD","postalCode":"21114","coordinates":{"lat":39.013318,"lng":-76.6754904}},{"address1":"5378 Allison Street","address2":"#102","city":"Arvada","state":"CO","postalCode":"80002","coordinates":{"lat":39.7944109,"lng":-105.0860024}},{"address1":"4604 Virginia Loop Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.314591,"lng":-86.24074999999999}},{"address1":"7711 North 51st Avenue","address2":"#1180","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5502243,"lng":-112.1665731}},{"address1":"343 Daman Drive","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.2999,"lng":-86.342286}},{"address1":"3623 Chateau Lane","address2":"","city":"Louisville","state":"KY","postalCode":"40219","coordinates":{"lat":38.1473803,"lng":-85.6954641}},{"address1":"2619 North Quality Lane","address2":"#315","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.09925399999999,"lng":-94.164274}},{"address1":"5334 West Northern Avenue","address2":"#327","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5535111,"lng":-112.1747068}},{"address1":"3835 Oakes Drive","address2":"","city":"Hayward","state":"CA","postalCode":"94542","coordinates":{"lat":37.661345,"lng":-122.032784}},{"address1":"295 Townes Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37211","coordinates":{"lat":36.052158,"lng":-86.70206900000001}},{"address1":"125 13th Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20002","coordinates":{"lat":38.891265,"lng":-76.988068}},{"address1":"7308 Northwest 119th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73162","coordinates":{"lat":35.592396,"lng":-97.643619}},{"address1":"1911 East 58th Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99507","coordinates":{"lat":61.16876999999999,"lng":-149.847225}},{"address1":"22649 McManus Drive","address2":"","city":"Anchorage","state":"AK","postalCode":"99567","coordinates":{"lat":61.418189,"lng":-149.460766}},{"address1":"4617 East 3rd Street","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.129243,"lng":-85.606926}},{"address1":"6436 Stoney Point Road","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.266241,"lng":-85.599245}},{"address1":"2577 Rhode Island Avenue Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20018","coordinates":{"lat":38.931902,"lng":-76.969579}},{"address1":"44 Campfield Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.768442,"lng":-72.540232}},{"address1":"7132 South Villa Avenue","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73159","coordinates":{"lat":35.392665,"lng":-97.5569639}},{"address1":"107 West Canton Circle","address2":"","city":"Springfield","state":"MA","postalCode":"01104","coordinates":{"lat":42.144682,"lng":-72.57098599999999}},{"address1":"14358 West 88th Place","address2":"C","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.8568436,"lng":-105.161713}},{"address1":"2100 Sandy Creek Trail","address2":"","city":"Edmond","state":"OK","postalCode":"73013","coordinates":{"lat":35.63330699999999,"lng":-97.509911}},{"address1":"6404 West 82nd Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.846475,"lng":-105.067397}},{"address1":"1609 Porter Avenue","address2":"","city":"Nashville","state":"TN","postalCode":"37206","coordinates":{"lat":36.196292,"lng":-86.725028}},{"address1":"8421 Thomas Drive","address2":"#4","city":"Panama City","state":"FL","postalCode":"32408","coordinates":{"lat":30.165178,"lng":-85.78605}},{"address1":"116 Frost Park","address2":"","city":"Hartford","state":"VT","postalCode":"05001","coordinates":{"lat":43.6692262,"lng":-72.3088865}},{"address1":"132 Tensaw Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36117","coordinates":{"lat":32.384289,"lng":-86.147064}},{"address1":"3147 West Old Farmington Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.0531475,"lng":-94.2055113}},{"address1":"3538 Mendenhall Court","address2":"","city":"Pleasanton","state":"CA","postalCode":"94588","coordinates":{"lat":37.6991919,"lng":-121.85909}},{"address1":"1623 Mines Road","address2":"","city":"Lowell","state":"VT","postalCode":"05847","coordinates":{"lat":44.795108,"lng":-72.48690599999999}},{"address1":"99 Pond Avenue","address2":"#606","city":"Brookline","state":"MA","postalCode":"02445","coordinates":{"lat":42.3293159,"lng":-71.1152839}},{"address1":"557 West Willoughby Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.019975,"lng":-94.16828199999999}},{"address1":"309 Brooke Court","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.1536175,"lng":-85.5881338}},{"address1":"4696 Bull Run Road","address2":"","city":"Ashland City","state":"TN","postalCode":"37015","coordinates":{"lat":36.241285,"lng":-86.940741}},{"address1":"18330 North 79th Avenue","address2":"#3155","city":"Glendale","state":"AZ","postalCode":"85308","coordinates":{"lat":33.6487128,"lng":-112.2313289}},{"address1":"5601 West Missouri Avenue","address2":"#165","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.5152999,"lng":-112.179748}},{"address1":"2903 West 31st Avenue","address2":"#APT 000002","city":"Anchorage","state":"AK","postalCode":"99517","coordinates":{"lat":61.192819,"lng":-149.937665}},{"address1":"2611 Bluefield Avenue","address2":"","city":"Nashville","state":"TN","postalCode":"37214","coordinates":{"lat":36.16786,"lng":-86.670203}},{"address1":"203 East Gwinnett Street","address2":"","city":"Savannah","state":"GA","postalCode":"31401","coordinates":{"lat":32.06637,"lng":-81.093895}},{"address1":"3517 S Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20007","coordinates":{"lat":38.914807,"lng":-77.070229}},{"address1":"1123 Ardee Avenue","address2":"","city":"Nashville","state":"TN","postalCode":"37216","coordinates":{"lat":36.219121,"lng":-86.725616}},{"address1":"3811 W Street Southeast","address2":"","city":"Washington","state":"DC","postalCode":"20020","coordinates":{"lat":38.8629369,"lng":-76.9515086}},{"address1":"2130 Loren Circle","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.071889,"lng":-94.191613}},{"address1":"4 Orchard Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.7747,"lng":-72.5247351}},{"address1":"4755 Coventry Road","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.318132,"lng":-86.28353}},{"address1":"1806 Boscobel Street","address2":"","city":"Nashville","state":"TN","postalCode":"37206","coordinates":{"lat":36.170799,"lng":-86.73835299999999}},{"address1":"7034 West John Garrison Road","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.107097,"lng":-94.2619139}},{"address1":"233 Juniper Drive","address2":"","city":"South Burlington","state":"VT","postalCode":"05403","coordinates":{"lat":44.473457,"lng":-73.176118}},{"address1":"1831 Frankford Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.181993,"lng":-85.692285}},{"address1":"4924 West 65th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8146604,"lng":-105.050343}},{"address1":"7095 Gladiola Street","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.824892,"lng":-105.162799}},{"address1":"7564 Moore Court","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.834188,"lng":-105.11569}},{"address1":"8442 Everett Way","address2":"A","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.850942,"lng":-105.096599}},{"address1":"1330 West 82nd Avenue","address2":"","city":"Anchorage","state":"AK","postalCode":"99518","coordinates":{"lat":61.147676,"lng":-149.905329}},{"address1":"4907 Roger Drive","address2":"","city":"Anchorage","state":"AK","postalCode":"99507","coordinates":{"lat":61.17564799999999,"lng":-149.839627}},{"address1":"123 Blossom Road","address2":"","city":"Westport","state":"MA","postalCode":"02790","coordinates":{"lat":41.68531,"lng":-71.0961337}},{"address1":"915 Hargrove Street","address2":"","city":"Ardmore","state":"OK","postalCode":"73401","coordinates":{"lat":34.184371,"lng":-97.13386190000001}},{"address1":"1983 Reidsville Street","address2":"","city":"Annapolis","state":"MD","postalCode":"21401","coordinates":{"lat":38.9817243,"lng":-76.5313745}},{"address1":"12403 Deerfield Road","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.977229,"lng":-81.145139}},{"address1":"1011 Devon Drive","address2":"","city":"Hayward","state":"CA","postalCode":"94542","coordinates":{"lat":37.65444100000001,"lng":-122.067741}},{"address1":"5222 West Laurie Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85302","coordinates":{"lat":33.5587639,"lng":-112.172235}},{"address1":"35 Pilgrim Lane","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.772138,"lng":-72.498806}},{"address1":"2728 Hale Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40211","coordinates":{"lat":38.2390813,"lng":-85.79926999999999}},{"address1":"65 Lowry Road","address2":"","city":"Falmouth","state":"MA","postalCode":"02540","coordinates":{"lat":41.5471365,"lng":-70.6075836}},{"address1":"302 Depot Road","address2":"","city":"Boxborough","state":"MA","postalCode":"01719","coordinates":{"lat":42.5013,"lng":-71.49441}},{"address1":"1402 Maggies Way","address2":"","city":"Waterbury Center","state":"VT","postalCode":"05677","coordinates":{"lat":44.410965,"lng":-72.71017499999999}},{"address1":"81 Lyness Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.76787789999999,"lng":-72.5443361}},{"address1":"6518 Dolphin Court","address2":"","city":"Glen Burnie","state":"MD","postalCode":"21061","coordinates":{"lat":39.198769,"lng":-76.63721}},{"address1":"1842 West Park Place","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73106","coordinates":{"lat":35.4795219,"lng":-97.5431009}},{"address1":"1 Pond View Road","address2":"","city":"Proctor","state":"VT","postalCode":"05765","coordinates":{"lat":43.663678,"lng":-73.0458419}},{"address1":"1340 5th Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20001","coordinates":{"lat":38.907549,"lng":-77.018924}},{"address1":"6000 Parker Drive","address2":"","city":"Deale","state":"MD","postalCode":"20751","coordinates":{"lat":38.780208,"lng":-76.539991}},{"address1":"822 Bowden Street","address2":"","city":"Savannah","state":"GA","postalCode":"31415","coordinates":{"lat":32.071342,"lng":-81.11783199999999}},{"address1":"1710 East Harold Street","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.109875,"lng":-94.1359389}},{"address1":"1518 Jenks Avenue","address2":"","city":"Panama City","state":"FL","postalCode":"32405","coordinates":{"lat":30.1765819,"lng":-85.662077}},{"address1":"814 South Pickard Avenue","address2":"","city":"Norman","state":"OK","postalCode":"73069","coordinates":{"lat":35.206961,"lng":-97.45494099999999}},{"address1":"100 Fenwick Village Drive","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":32.0244412,"lng":-81.23017689999999}},{"address1":"218 Middle Street","address2":"","city":"Brighton","state":"VT","postalCode":"05846","coordinates":{"lat":44.818438,"lng":-71.8846049}},{"address1":"5470 Atlanta Highway","address2":"","city":"Montgomery","state":"AL","postalCode":"36109","coordinates":{"lat":32.3802399,"lng":-86.21232959999999}},{"address1":"43 Main Street","address2":"","city":"Essex","state":"VT","postalCode":"05452","coordinates":{"lat":44.4921,"lng":-73.1074749}},{"address1":"804 East 7th Court","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.161259,"lng":-85.648719}},{"address1":"1709 Queensbury Road","address2":"","city":"Moore","state":"OK","postalCode":"73160","coordinates":{"lat":35.3546959,"lng":-97.507938}},{"address1":"646 Clinton Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36108","coordinates":{"lat":32.3602725,"lng":-86.3183004}},{"address1":"708 Pine Drift Drive","address2":"","city":"Odenton","state":"MD","postalCode":"21113","coordinates":{"lat":39.070589,"lng":-76.715406}},{"address1":"5104 West Tierra Buena Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.62898759999999,"lng":-112.168811}},{"address1":"1234 Carmel Street","address2":"","city":"Madera","state":"CA","postalCode":"93638","coordinates":{"lat":36.949941,"lng":-120.043739}},{"address1":"1753 Zion Road","address2":"#E33","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.1273162,"lng":-94.1350437}},{"address1":"22538 6th Street","address2":"","city":"Hayward","state":"CA","postalCode":"94541","coordinates":{"lat":37.680829,"lng":-122.07335}},{"address1":"415 Lullwater Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.22177929999999,"lng":-85.8841423}},{"address1":"219 Bidwell Street","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.761322,"lng":-72.5498278}},{"address1":"4500 Margalo Avenue","address2":"","city":"Bakersfield","state":"CA","postalCode":"93313","coordinates":{"lat":35.305082,"lng":-119.052448}},{"address1":"8380 West 67th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80004","coordinates":{"lat":39.817999,"lng":-105.090301}},{"address1":"2334 Nantucket Drive","address2":"","city":"Crofton","state":"MD","postalCode":"21114","coordinates":{"lat":39.0298609,"lng":-76.67307600000001}},{"address1":"720 East Muhammad Ali Boulevard","address2":"","city":"Louisville","state":"KY","postalCode":"40202","coordinates":{"lat":38.2491941,"lng":-85.7396682}},{"address1":"12022 Town Park Circle","address2":"","city":"Anchorage","state":"AK","postalCode":"99577","coordinates":{"lat":61.32927710000001,"lng":-149.5778193}},{"address1":"2305 Ranchland Drive","address2":"","city":"Savannah","state":"GA","postalCode":"31404","coordinates":{"lat":32.026112,"lng":-81.0755779}},{"address1":"1656 Newton Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20010","coordinates":{"lat":38.933985,"lng":-77.03866099999999}},{"address1":"91 85th Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72704","coordinates":{"lat":36.064165,"lng":-94.285358}},{"address1":"228 Central Street","address2":"","city":"Milford","state":"MA","postalCode":"01757","coordinates":{"lat":42.13911,"lng":-71.5115022}},{"address1":"20 Masters Way","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.740694,"lng":-72.51832}},{"address1":"5396 North Reese Avenue","address2":"","city":"Fresno","state":"CA","postalCode":"93722","coordinates":{"lat":36.815278,"lng":-119.864119}},{"address1":"28 Wilfred Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.766696,"lng":-72.5597335}},{"address1":"200 Pheasant Avenue","address2":"#103","city":"Louisville","state":"KY","postalCode":"40118","coordinates":{"lat":38.1134628,"lng":-85.76321279999999}},{"address1":"1650 Garland Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.0845144,"lng":-94.1751065}},{"address1":"4600 Ritchie Highway","address2":"","city":"Baltimore","state":"MD","postalCode":"21225","coordinates":{"lat":39.228241,"lng":-76.6136159}},{"address1":"733 East DeRenne Avenue","address2":"","city":"Savannah","state":"GA","postalCode":"31405","coordinates":{"lat":32.024217,"lng":-81.095602}},{"address1":"8349 West Stella Way","address2":"","city":"Glendale","state":"AZ","postalCode":"85305","coordinates":{"lat":33.529493,"lng":-112.240632}},{"address1":"33 Pond Avenue","address2":"#804","city":"Brookline","state":"MA","postalCode":"02445","coordinates":{"lat":42.33094200000001,"lng":-71.1145331}},{"address1":"9 Kimball Court","address2":"#107","city":"Burlington","state":"MA","postalCode":"01803","coordinates":{"lat":42.501798,"lng":-71.168725}},{"address1":"2433 Southwest 36th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73109","coordinates":{"lat":35.42839900000001,"lng":-97.556119}},{"address1":"4607 Artelia Drive","address2":"","city":"Nashville","state":"TN","postalCode":"37013","coordinates":{"lat":36.071468,"lng":-86.675555}},{"address1":"212 Ambleside Drive","address2":"","city":"Severna Park","state":"MD","postalCode":"21146","coordinates":{"lat":39.097022,"lng":-76.55617699999999}},{"address1":"8757 Lamar Circle","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.8557446,"lng":-105.0681477}},{"address1":"130 Carolina Cherry Circle","address2":"","city":"Pooler","state":"GA","postalCode":"31322","coordinates":{"lat":32.1485911,"lng":-81.2620116}},{"address1":"7804 Abercorn Street","address2":"#11","city":"Savannah","state":"GA","postalCode":"31406","coordinates":{"lat":32.00192,"lng":-81.11689830000002}},{"address1":"12870 Old Seward Highway","address2":"#STE 000105","city":"Anchorage","state":"AK","postalCode":"99515","coordinates":{"lat":61.10396369999999,"lng":-149.8575515}},{"address1":"8133 Meadowgreen Place","address2":"","city":"Louisville","state":"KY","postalCode":"40299","coordinates":{"lat":38.1899697,"lng":-85.60704779999999}},{"address1":"5 Meadow Lane","address2":"","city":"Rutland","state":"VT","postalCode":"05701","coordinates":{"lat":43.619797,"lng":-72.983231}},{"address1":"562 South Pierremont Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.05627330000001,"lng":-94.1251461}},{"address1":"1219 Carleton Street","address2":"M","city":"Berkeley","state":"CA","postalCode":"94702","coordinates":{"lat":37.8591054,"lng":-122.285823}},{"address1":"1403 Boulder Court","address2":"","city":"Hanover","state":"MD","postalCode":"21076","coordinates":{"lat":39.140743,"lng":-76.69958}},{"address1":"122 Coral Drive","address2":"","city":"Panama City Beach","state":"FL","postalCode":"32413","coordinates":{"lat":30.233822,"lng":-85.89228399999999}},{"address1":"1404 James Way","address2":"","city":"Edgewater","state":"MD","postalCode":"21037","coordinates":{"lat":38.8879642,"lng":-76.5100926}},{"address1":"4300 Woodley Square","address2":"","city":"Montgomery","state":"AL","postalCode":"36116","coordinates":{"lat":32.3269015,"lng":-86.2695368}},{"address1":"422 Richmond Street","address2":"","city":"El Cerrito","state":"CA","postalCode":"94530","coordinates":{"lat":37.9028101,"lng":-122.2981152}},{"address1":"222 Plymouth Street","address2":"A","city":"Middleborough","state":"MA","postalCode":"02346","coordinates":{"lat":41.928117,"lng":-70.9416075}},{"address1":"451 East Street","address2":"","city":"Huntington","state":"VT","postalCode":"05462","coordinates":{"lat":44.3194104,"lng":-72.9844982}},{"address1":"9209 Eupora Court","address2":"","city":"Jeffersontown","state":"KY","postalCode":"40299","coordinates":{"lat":38.1970417,"lng":-85.58631430000001}},{"address1":"4 Conti Circle","address2":"","city":"Barre","state":"VT","postalCode":"05641","coordinates":{"lat":44.1731699,"lng":-72.4920951}},{"address1":"5264 Shafter Avenue","address2":"","city":"Oakland","state":"CA","postalCode":"94618","coordinates":{"lat":37.839058,"lng":-122.256035}},{"address1":"1630 Eton Way","address2":"","city":"Crofton","state":"MD","postalCode":"21114","coordinates":{"lat":39.008958,"lng":-76.69134199999999}},{"address1":"5244 West Port Au Prince Lane","address2":"","city":"Glendale","state":"AZ","postalCode":"85306","coordinates":{"lat":33.622672,"lng":-112.17283}},{"address1":"1835 Pointer Lane","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.08606899999999,"lng":-94.1187549}},{"address1":"107 Laurel Green Court","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":32.025628,"lng":-81.24673399999999}},{"address1":"7250 Urban Drive","address2":"","city":"Arvada","state":"CO","postalCode":"80005","coordinates":{"lat":39.827875,"lng":-105.133965}},{"address1":"12 Kane Road","address2":"","city":"Manchester","state":"CT","postalCode":"06040","coordinates":{"lat":41.764315,"lng":-72.51276}},{"address1":"4132 Northwest 57th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73112","coordinates":{"lat":35.529164,"lng":-97.594155}},{"address1":"10774 West 54th Lane","address2":"","city":"Arvada","state":"CO","postalCode":"80002","coordinates":{"lat":39.7963587,"lng":-105.11861}},{"address1":"6729 North 54th Avenue","address2":"","city":"Glendale","state":"AZ","postalCode":"85301","coordinates":{"lat":33.536068,"lng":-112.17458}},{"address1":"6483 West 76th Avenue","address2":"","city":"Arvada","state":"CO","postalCode":"80003","coordinates":{"lat":39.834927,"lng":-105.069802}},{"address1":"5732 Jean Drive","address2":"","city":"Union City","state":"CA","postalCode":"94587","coordinates":{"lat":37.580691,"lng":-122.082773}},{"address1":"8221 Surf Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32408","coordinates":{"lat":30.1630986,"lng":-85.7845665}},{"address1":"9101 Vanguard Drive","address2":"","city":"Anchorage","state":"AK","postalCode":"99507","coordinates":{"lat":61.1382426,"lng":-149.84756}},{"address1":"18713 Shilstone Way","address2":"","city":"Edmond","state":"OK","postalCode":"73012","coordinates":{"lat":35.6618776,"lng":-97.53426999999999}},{"address1":"51185 Helmsman Street","address2":"","city":"Kenai","state":"AK","postalCode":"99611","coordinates":{"lat":60.509562,"lng":-151.265293}},{"address1":"128 East Oak Street","address2":"#3","city":"Louisville","state":"KY","postalCode":"40203","coordinates":{"lat":38.2342125,"lng":-85.7539867}},{"address1":"1222 Arcade Boulevard","address2":"","city":"Sacramento","state":"CA","postalCode":"95815","coordinates":{"lat":38.626122,"lng":-121.43861}},{"address1":"1405 Mercedes Avenue","address2":"APARTMENT G","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.1738039,"lng":-85.6462091}},{"address1":"7024 Johnny Mercer Boulevard","address2":"","city":"Savannah","state":"GA","postalCode":"31410","coordinates":{"lat":32.022447,"lng":-80.969861}},{"address1":"3600 Pennsylvania Avenue","address2":"#APT 6","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.5516245,"lng":-121.9872735}},{"address1":"312 North Cove Boulevard","address2":"","city":"Panama City","state":"FL","postalCode":"32401","coordinates":{"lat":30.1520433,"lng":-85.6500713}},{"address1":"3118 Sora Avenue","address2":"","city":"Louisville","state":"KY","postalCode":"40213","coordinates":{"lat":38.208849,"lng":-85.724113}},{"address1":"6420 Via Baron","address2":"","city":"Rancho Palos Verdes","state":"CA","postalCode":"90275","coordinates":{"lat":33.741162,"lng":-118.390767}},{"address1":"3321 Furman Boulevard","address2":"","city":"Louisville","state":"KY","postalCode":"40220","coordinates":{"lat":38.2134349,"lng":-85.640439}},{"address1":"98 Lincoln Street","address2":"","city":"Revere","state":"MA","postalCode":"02151","coordinates":{"lat":42.418115,"lng":-71.027503}},{"address1":"984 Greendale Avenue","address2":"","city":"Needham","state":"MA","postalCode":"02492","coordinates":{"lat":42.275811,"lng":-71.203287}},{"address1":"239 Eastern Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0605438,"lng":-94.18373079999999}},{"address1":"1106 Commanders Way South","address2":"","city":"Annapolis","state":"MD","postalCode":"21409","coordinates":{"lat":39.033352,"lng":-76.447767}},{"address1":"4927 Alvin Sperry Road","address2":"","city":"Mount Juliet","state":"TN","postalCode":"37122","coordinates":{"lat":36.143557,"lng":-86.556877}},{"address1":"1632 North Lunsford Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.0827979,"lng":-94.137607}},{"address1":"2349 East Tall Oaks Drive","address2":"","city":"Fayetteville","state":"AR","postalCode":"72703","coordinates":{"lat":36.09277,"lng":-94.12758799999999}},{"address1":"2036 Hermitage Hills Drive","address2":"","city":"Gambrills","state":"MD","postalCode":"21054","coordinates":{"lat":38.9951,"lng":-76.65160999999999}},{"address1":"119 Oakland Street","address2":"","city":"Manchester","state":"CT","postalCode":"06042","coordinates":{"lat":41.7976637,"lng":-72.5199944}},{"address1":"37675 Fremont Boulevard","address2":"#APT 42","city":"Fremont","state":"CA","postalCode":"94536","coordinates":{"lat":37.555306,"lng":-122.003412}},{"address1":"3104 Southwest 46th Street","address2":"","city":"Oklahoma City","state":"OK","postalCode":"73119","coordinates":{"lat":35.4186213,"lng":-97.56952249999999}},{"address1":"2036 Gorgas Street","address2":"","city":"Montgomery","state":"AL","postalCode":"36106","coordinates":{"lat":32.357301,"lng":-86.276583}},{"address1":"11102 Little Rock Court","address2":"","city":"Louisville","state":"KY","postalCode":"40241","coordinates":{"lat":38.3214271,"lng":-85.5421016}},{"address1":"46 Deslauriers Street","address2":"","city":"Chicopee","state":"MA","postalCode":"01020","coordinates":{"lat":42.1855005,"lng":-72.5733508}},{"address1":"12 Red Fox Drive","address2":"","city":"Savannah","state":"GA","postalCode":"31419","coordinates":{"lat":31.981396,"lng":-81.22833899999999}},{"address1":"503 Blackwood Terrace Southeast","address2":"","city":"Calhoun","state":"GA","postalCode":"30701","coordinates":{"lat":34.459017,"lng":-84.914659}},{"address1":"2223 North Fernwood Court","address2":"","city":"Savannah","state":"GA","postalCode":"31404","coordinates":{"lat":32.029307,"lng":-81.06297099999999}},{"address1":"5444 Nicole Boulevard","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.238007,"lng":-85.562274}},{"address1":"849 East Victoria Street","address2":"#204","city":"Carson","state":"CA","postalCode":"90746","coordinates":{"lat":33.8673562,"lng":-118.2597713}},{"address1":"445 South Potomac Circle","address2":"","city":"Aurora","state":"CO","postalCode":"80012","coordinates":{"lat":39.705341,"lng":-104.830397}},{"address1":"201 East 9th Avenue","address2":"#APT 000102","city":"Anchorage","state":"AK","postalCode":"99501","coordinates":{"lat":61.213897,"lng":-149.880633}},{"address1":"3500 15th Street Northeast","address2":"","city":"Washington","state":"DC","postalCode":"20017","coordinates":{"lat":38.93311000000001,"lng":-76.98485699999999}},{"address1":"4981 Shirley Way","address2":"","city":"Livermore","state":"CA","postalCode":"94550","coordinates":{"lat":37.682649,"lng":-121.733308}},{"address1":"1300 Lemos Lane","address2":"","city":"Fremont","state":"CA","postalCode":"94539","coordinates":{"lat":37.546996,"lng":-121.951627}},{"address1":"5000 V Street Northwest","address2":"","city":"Washington","state":"DC","postalCode":"20007","coordinates":{"lat":38.917076,"lng":-77.09743399999999}},{"address1":"6823 Forsythe Drive","address2":"","city":"Panama City","state":"FL","postalCode":"32404","coordinates":{"lat":30.12332199999999,"lng":-85.571428}},{"address1":"1522 South 36th Street","address2":"","city":"Louisville","state":"KY","postalCode":"40211","coordinates":{"lat":38.231691,"lng":-85.8144612}},{"address1":"313 Lone Oak Drive","address2":"","city":"Norman","state":"OK","postalCode":"73071","coordinates":{"lat":35.221084,"lng":-97.405029}},{"address1":"970 Old Oak Road","address2":"","city":"Livermore","state":"CA","postalCode":"94550","coordinates":{"lat":37.653774,"lng":-121.796632}},{"address1":"1653 Brooks Avenue","address2":"","city":"Fayetteville","state":"AR","postalCode":"72701","coordinates":{"lat":36.04687,"lng":-94.17589699999999}},{"address1":"441 Merritt Avenue","address2":"","city":"Oakland","state":"CA","postalCode":"94610","coordinates":{"lat":37.8058663,"lng":-122.2493644}},{"address1":"632 North Pine Street","address2":"","city":"Anchorage","state":"AK","postalCode":"99508","coordinates":{"lat":61.22930220000001,"lng":-149.7938547}}],"attribution":["City of Haddam (CT)","Ciy of Hartford (CT)","City of Lyme (CT)","City of Manchester (CT)","City of Watertown (CT)","City of Avon (CT)","Town of Fairfield (CT)","City of Groton (CT)","Office of Geographic Information (MassGIS), Commonwealth of Massachusetts, MassIT (MA)","VT Enhanced 911 Board, VCGI (VT)","City of Huntsville (AL)","City of Montgomery (AL)","Shelby County (AL)","Talladega County (AL)","City of Fayetteville (AR)","Arkansas Geographic Information Office (AR)","City of Washington (DC)","Bay County (FL)","Brevard County (FL)","Charlotte County (FL)","Citrus County (FL)","Clay County (FL)","Highlands County, FL (FL)","Hillsborough County (FL)","City of Savannah (GA)","Gordon County (GA)","Muscogee County (GA)","Sumter County (GA)","Metro Louisville, LOJIC partners (KY)","Anne Arundel County (MD)","City of Baltimore (MD)","Frederick County (MD)","Oklahoma and Logan Counties - Association of Central Oklahoma Governments (OK)","Kern, Cleveland, Canadian, Logan Counties (OK)","City of Nashville (TN)","Cooke,Fannin,Grayson Counties - Texoma Council of Governments (TX)","Municipality of Anchorage (AK)","Copyright © 2015 Kenai Peninsula Borough (AK)","Matanuska-Susitna Borough (AK)","City of Glendale (AZ)","City of Mesa (AZ)","Alameda County (CA)","Amador County (CA)","City of Berkeley (CA)","Butte County (CA)","City of Bakersfield (CA)","City of Carson (CA)","City of Cupertino (CA)","City of Hayward and Fairview. Licensed for Public Use (CA)","City of Mountain View (CA)","City of Orange (CA)","Contra Costa County (CA)","El Dorando County (CA)","Fresno County (CA)","Humboldt County (CA)","Kern County (CA)","Kings County (CA)","Lake County (CA)","Lassen County (CA)","Los Angeles County (CA)","Madera County (CA)","Marin County (CA)","Merced County (CA)","Mono County (CA)","Monterey County (CA)","Napa County (CA)","County of Nevada, California (CA)","Orange County (CA)","City of Palo Alto (CA)","County of Placer (CA)","Secramento County (CA)","San Bernardino County (CA)","San Diego Geographic Information Source - JPA (CA)","San Joaquin County (CA)","San Luis Obispo County (CA)","San Mateo County (CA)","Santa Barbara County (CA)","Santa Clara County (CA)","Santa Cruz County (CA)","Shasta County (CA)","Solano County (CA)","Sonoma County (CA)","Stanislaus County (CA)","Tuolumne County (CA)","Yolo County (CA)","Yuba County (CA)","Arapahoe County (CO)","Archuleta County (CO)","City of Arvada (CO)","City of Aurora (CO)","City of Boulder (CO)","City of Fort Collins (CO)","City of Greeley (CO)","City of Loveland (CO)","City of Westminster (CO)","Gilpin County (CO)","Gunnison County (CO)","Jefferson County (CO)","Larimer County (CO)","Mesa County (CO)","Pitkin County (CO)","Pubelo County (CO)","San Miguel County (CO)","City of Honolulu (HI)"]} diff --git a/vendor/github.com/go-faker/faker/v4/misc/country_info.json b/vendor/github.com/go-faker/faker/v4/misc/country_info.json new file mode 100644 index 0000000..ed99552 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/misc/country_info.json @@ -0,0 +1,1754 @@ +{ + "countries": [ + { + "abbr": "AD", + "name": "Andorra", + "capital": "Andorra la Vella", + "population": "77,006", + "continent": "EU" + }, + { + "abbr": "AE", + "name": "United Arab Emirates", + "capital": "Abu Dhabi", + "population": "9,630,959", + "continent": "AS" + }, + { + "abbr": "AF", + "name": "Afghanistan", + "capital": "Kabul", + "population": "37,172,386", + "continent": "AS" + }, + { + "abbr": "AG", + "name": "Antigua and Barbuda", + "capital": "St. John's", + "population": "96,286", + "continent": "NA" + }, + { + "abbr": "AI", + "name": "Anguilla", + "capital": "The Valley", + "population": "13,254", + "continent": "NA" + }, + { + "abbr": "AL", + "name": "Albania", + "capital": "Tirana", + "population": "2,866,376", + "continent": "EU" + }, + { + "abbr": "AM", + "name": "Armenia", + "capital": "Yerevan", + "population": "2,951,776", + "continent": "AS" + }, + { + "abbr": "AO", + "name": "Angola", + "capital": "Luanda", + "population": "30,809,762", + "continent": "AF" + }, + { + "abbr": "AQ", + "name": "Antarctica", + "capital": "", + "population": "0", + "continent": "AN" + }, + { + "abbr": "AR", + "name": "Argentina", + "capital": "Buenos Aires", + "population": "44,494,502", + "continent": "SA" + }, + { + "abbr": "AS", + "name": "American Samoa", + "capital": "Pago Pago", + "population": "55,465", + "continent": "OC" + }, + { + "abbr": "AT", + "name": "Austria", + "capital": "Vienna", + "population": "8,847,037", + "continent": "EU" + }, + { + "abbr": "AU", + "name": "Australia", + "capital": "Canberra", + "population": "24,992,369", + "continent": "OC" + }, + { + "abbr": "AW", + "name": "Aruba", + "capital": "Oranjestad", + "population": "105,845", + "continent": "NA" + }, + { + "abbr": "AX", + "name": "Åland", + "capital": "Mariehamn", + "population": "26,711", + "continent": "EU" + }, + { + "abbr": "AZ", + "name": "Azerbaijan", + "capital": "Baku", + "population": "9,942,334", + "continent": "AS" + }, + { + "abbr": "BA", + "name": "Bosnia and Herzegovina", + "capital": "Sarajevo", + "population": "3,323,929", + "continent": "EU" + }, + { + "abbr": "BB", + "name": "Barbados", + "capital": "Bridgetown", + "population": "286,641", + "continent": "NA" + }, + { + "abbr": "BD", + "name": "Bangladesh", + "capital": "Dhaka", + "population": "161,356,039", + "continent": "AS" + }, + { + "abbr": "BE", + "name": "Belgium", + "capital": "Brussels", + "population": "11,422,068", + "continent": "EU" + }, + { + "abbr": "BF", + "name": "Burkina Faso", + "capital": "Ouagadougou", + "population": "19,751,535", + "continent": "AF" + }, + { + "abbr": "BG", + "name": "Bulgaria", + "capital": "Sofia", + "population": "7,000,039", + "continent": "EU" + }, + { + "abbr": "BH", + "name": "Bahrain", + "capital": "Manama", + "population": "1,569,439", + "continent": "AS" + }, + { + "abbr": "BI", + "name": "Burundi", + "capital": "Gitega", + "population": "11,175,378", + "continent": "AF" + }, + { + "abbr": "BJ", + "name": "Benin", + "capital": "Porto-Novo", + "population": "11,485,048", + "continent": "AF" + }, + { + "abbr": "BL", + "name": "Saint Barthélemy", + "capital": "Gustavia", + "population": "8,450", + "continent": "NA" + }, + { + "abbr": "BM", + "name": "Bermuda", + "capital": "Hamilton", + "population": "63,968", + "continent": "NA" + }, + { + "abbr": "BN", + "name": "Brunei", + "capital": "Bandar Seri Begawan", + "population": "428,962", + "continent": "AS" + }, + { + "abbr": "BO", + "name": "Bolivia", + "capital": "Sucre", + "population": "11,353,142", + "continent": "SA" + }, + { + "abbr": "BQ", + "name": "Bonaire, Sint Eustatius, and Saba", + "capital": "", + "population": "18,012", + "continent": "NA" + }, + { + "abbr": "BR", + "name": "Brazil", + "capital": "Brasilia", + "population": "209,469,333", + "continent": "SA" + }, + { + "abbr": "BS", + "name": "Bahamas", + "capital": "Nassau", + "population": "385,640", + "continent": "NA" + }, + { + "abbr": "BT", + "name": "Bhutan", + "capital": "Thimphu", + "population": "754,394", + "continent": "AS" + }, + { + "abbr": "BV", + "name": "Bouvet Island", + "capital": "", + "population": "0", + "continent": "AN" + }, + { + "abbr": "BW", + "name": "Botswana", + "capital": "Gaborone", + "population": "2,254,126", + "continent": "AF" + }, + { + "abbr": "BY", + "name": "Belarus", + "capital": "Minsk", + "population": "9,485,386", + "continent": "EU" + }, + { + "abbr": "BZ", + "name": "Belize", + "capital": "Belmopan", + "population": "383,071", + "continent": "NA" + }, + { + "abbr": "CA", + "name": "Canada", + "capital": "Ottawa", + "population": "37,058,856", + "continent": "NA" + }, + { + "abbr": "CC", + "name": "Cocos (Keeling) Islands", + "capital": "West Island", + "population": "628", + "continent": "AS" + }, + { + "abbr": "CD", + "name": "DR Congo", + "capital": "Kinshasa", + "population": "84,068,091", + "continent": "AF" + }, + { + "abbr": "CF", + "name": "Central African Republic", + "capital": "Bangui", + "population": "4,666,377", + "continent": "AF" + }, + { + "abbr": "CG", + "name": "Congo Republic", + "capital": "Brazzaville", + "population": "5,244,363", + "continent": "AF" + }, + { + "abbr": "CH", + "name": "Switzerland", + "capital": "Bern", + "population": "8,516,543", + "continent": "EU" + }, + { + "abbr": "CI", + "name": "Ivory Coast", + "capital": "Yamoussoukro", + "population": "25,069,229", + "continent": "AF" + }, + { + "abbr": "CK", + "name": "Cook Islands", + "capital": "Avarua", + "population": "21,388", + "continent": "OC" + }, + { + "abbr": "CL", + "name": "Chile", + "capital": "Santiago", + "population": "18,729,160", + "continent": "SA" + }, + { + "abbr": "CM", + "name": "Cameroon", + "capital": "Yaounde", + "population": "25,216,237", + "continent": "AF" + }, + { + "abbr": "CN", + "name": "China", + "capital": "Beijing", + "population": "1,411,778,724", + "continent": "AS" + }, + { + "abbr": "CO", + "name": "Colombia", + "capital": "Bogota", + "population": "49,648,685", + "continent": "SA" + }, + { + "abbr": "CR", + "name": "Costa Rica", + "capital": "San Jose", + "population": "4,999,441", + "continent": "NA" + }, + { + "abbr": "CU", + "name": "Cuba", + "capital": "Havana", + "population": "11,338,138", + "continent": "NA" + }, + { + "abbr": "CV", + "name": "Cabo Verde", + "capital": "Praia", + "population": "543,767", + "continent": "AF" + }, + { + "abbr": "CW", + "name": "Curaçao", + "capital": "Willemstad", + "population": "159,849", + "continent": "NA" + }, + { + "abbr": "CX", + "name": "Christmas Island", + "capital": "Flying Fish Cove", + "population": "1,500", + "continent": "OC" + }, + { + "abbr": "CY", + "name": "Cyprus", + "capital": "Nicosia", + "population": "1,189,265", + "continent": "EU" + }, + { + "abbr": "CZ", + "name": "Czechia", + "capital": "Prague", + "population": "10,625,695", + "continent": "EU" + }, + { + "abbr": "DE", + "name": "Germany", + "capital": "Berlin", + "population": "82,927,922", + "continent": "EU" + }, + { + "abbr": "DJ", + "name": "Djibouti", + "capital": "Djibouti", + "population": "958,920", + "continent": "AF" + }, + { + "abbr": "DK", + "name": "Denmark", + "capital": "Copenhagen", + "population": "5,797,446", + "continent": "EU" + }, + { + "abbr": "DM", + "name": "Dominica", + "capital": "Roseau", + "population": "71,625", + "continent": "NA" + }, + { + "abbr": "DO", + "name": "Dominican Republic", + "capital": "Santo Domingo", + "population": "10,627,165", + "continent": "NA" + }, + { + "abbr": "DZ", + "name": "Algeria", + "capital": "Algiers", + "population": "42,228,429", + "continent": "AF" + }, + { + "abbr": "EC", + "name": "Ecuador", + "capital": "Quito", + "population": "17,084,357", + "continent": "SA" + }, + { + "abbr": "EE", + "name": "Estonia", + "capital": "Tallinn", + "population": "1,320,884", + "continent": "EU" + }, + { + "abbr": "EG", + "name": "Egypt", + "capital": "Cairo", + "population": "98,423,595", + "continent": "AF" + }, + { + "abbr": "EH", + "name": "Western Sahara", + "capital": "El-Aaiun", + "population": "273,008", + "continent": "AF" + }, + { + "abbr": "ER", + "name": "Eritrea", + "capital": "Asmara", + "population": "6,209,262", + "continent": "AF" + }, + { + "abbr": "ES", + "name": "Spain", + "capital": "Madrid", + "population": "46,723,749", + "continent": "EU" + }, + { + "abbr": "ET", + "name": "Ethiopia", + "capital": "Addis Ababa", + "population": "109,224,559", + "continent": "AF" + }, + { + "abbr": "FI", + "name": "Finland", + "capital": "Helsinki", + "population": "5,518,050", + "continent": "EU" + }, + { + "abbr": "FJ", + "name": "Fiji", + "capital": "Suva", + "population": "883,483", + "continent": "OC" + }, + { + "abbr": "FK", + "name": "Falkland Islands", + "capital": "Stanley", + "population": "2,638", + "continent": "SA" + }, + { + "abbr": "FM", + "name": "Micronesia", + "capital": "Palikir", + "population": "112,640", + "continent": "OC" + }, + { + "abbr": "FO", + "name": "Faroe Islands", + "capital": "Torshavn", + "population": "48,497", + "continent": "EU" + }, + { + "abbr": "FR", + "name": "France", + "capital": "Paris", + "population": "66,987,244", + "continent": "EU" + }, + { + "abbr": "GA", + "name": "Gabon", + "capital": "Libreville", + "population": "2,119,275", + "continent": "AF" + }, + { + "abbr": "GB", + "name": "United Kingdom", + "capital": "London", + "population": "66,488,991", + "continent": "EU" + }, + { + "abbr": "GD", + "name": "Grenada", + "capital": "St. George's", + "population": "111,454", + "continent": "NA" + }, + { + "abbr": "GE", + "name": "Georgia", + "capital": "Tbilisi", + "population": "3,731,000", + "continent": "AS" + }, + { + "abbr": "GF", + "name": "French Guiana", + "capital": "Cayenne", + "population": "195,506", + "continent": "SA" + }, + { + "abbr": "GG", + "name": "Guernsey", + "capital": "St Peter Port", + "population": "65,228", + "continent": "EU" + }, + { + "abbr": "GH", + "name": "Ghana", + "capital": "Accra", + "population": "29,767,108", + "continent": "AF" + }, + { + "abbr": "GI", + "name": "Gibraltar", + "capital": "Gibraltar", + "population": "33,718", + "continent": "EU" + }, + { + "abbr": "GL", + "name": "Greenland", + "capital": "Nuuk", + "population": "56,025", + "continent": "NA" + }, + { + "abbr": "GM", + "name": "The Gambia", + "capital": "Banjul", + "population": "2,280,102", + "continent": "AF" + }, + { + "abbr": "GN", + "name": "Guinea", + "capital": "Conakry", + "population": "12,414,318", + "continent": "AF" + }, + { + "abbr": "GP", + "name": "Guadeloupe", + "capital": "Basse-Terre", + "population": "443,000", + "continent": "NA" + }, + { + "abbr": "GQ", + "name": "Equatorial Guinea", + "capital": "Malabo", + "population": "1,308,974", + "continent": "AF" + }, + { + "abbr": "GR", + "name": "Greece", + "capital": "Athens", + "population": "10,727,668", + "continent": "EU" + }, + { + "abbr": "GS", + "name": "South Georgia and South Sandwich Islands", + "capital": "Grytviken", + "population": "30", + "continent": "AN" + }, + { + "abbr": "GT", + "name": "Guatemala", + "capital": "Guatemala City", + "population": "17,247,807", + "continent": "NA" + }, + { + "abbr": "GU", + "name": "Guam", + "capital": "Hagatna", + "population": "165,768", + "continent": "OC" + }, + { + "abbr": "GW", + "name": "Guinea-Bissau", + "capital": "Bissau", + "population": "1,874,309", + "continent": "AF" + }, + { + "abbr": "GY", + "name": "Guyana", + "capital": "Georgetown", + "population": "779,004", + "continent": "SA" + }, + { + "abbr": "HK", + "name": "Hong Kong", + "capital": "Hong Kong", + "population": "7,491,609", + "continent": "AS" + }, + { + "abbr": "HM", + "name": "Heard and McDonald Islands", + "capital": "", + "population": "0", + "continent": "AN" + }, + { + "abbr": "HN", + "name": "Honduras", + "capital": "Tegucigalpa", + "population": "9,587,522", + "continent": "NA" + }, + { + "abbr": "HR", + "name": "Croatia", + "capital": "Zagreb", + "population": "3,871,833", + "continent": "EU" + }, + { + "abbr": "HT", + "name": "Haiti", + "capital": "Port-au-Prince", + "population": "11,123,176", + "continent": "NA" + }, + { + "abbr": "HU", + "name": "Hungary", + "capital": "Budapest", + "population": "9,768,785", + "continent": "EU" + }, + { + "abbr": "ID", + "name": "Indonesia", + "capital": "Jakarta", + "population": "267,663,435", + "continent": "AS" + }, + { + "abbr": "IE", + "name": "Ireland", + "capital": "Dublin", + "population": "4,853,506", + "continent": "EU" + }, + { + "abbr": "IL", + "name": "Israel", + "capital": "Jerusalem", + "population": "8,883,800", + "continent": "AS" + }, + { + "abbr": "IM", + "name": "Isle of Man", + "capital": "Douglas", + "population": "84,077", + "continent": "EU" + }, + { + "abbr": "IN", + "name": "India", + "capital": "New Delhi", + "population": "1,352,617,328", + "continent": "AS" + }, + { + "abbr": "IO", + "name": "British Indian Ocean Territory", + "capital": "Diego Garcia", + "population": "4,000", + "continent": "AS" + }, + { + "abbr": "IQ", + "name": "Iraq", + "capital": "Baghdad", + "population": "38,433,600", + "continent": "AS" + }, + { + "abbr": "IR", + "name": "Iran", + "capital": "Tehran", + "population": "81,800,269", + "continent": "AS" + }, + { + "abbr": "IS", + "name": "Iceland", + "capital": "Reykjavik", + "population": "353,574", + "continent": "EU" + }, + { + "abbr": "IT", + "name": "Italy", + "capital": "Rome", + "population": "60,431,283", + "continent": "EU" + }, + { + "abbr": "JE", + "name": "Jersey", + "capital": "Saint Helier", + "population": "90,812", + "continent": "EU" + }, + { + "abbr": "JM", + "name": "Jamaica", + "capital": "Kingston", + "population": "2,934,855", + "continent": "NA" + }, + { + "abbr": "JO", + "name": "Jordan", + "capital": "Amman", + "population": "9,956,011", + "continent": "AS" + }, + { + "abbr": "JP", + "name": "Japan", + "capital": "Tokyo", + "population": "126,529,100", + "continent": "AS" + }, + { + "abbr": "KE", + "name": "Kenya", + "capital": "Nairobi", + "population": "51,393,010", + "continent": "AF" + }, + { + "abbr": "KG", + "name": "Kyrgyzstan", + "capital": "Bishkek", + "population": "6,315,800", + "continent": "AS" + }, + { + "abbr": "KH", + "name": "Cambodia", + "capital": "Phnom Penh", + "population": "16,249,798", + "continent": "AS" + }, + { + "abbr": "KI", + "name": "Kiribati", + "capital": "Tarawa", + "population": "115,847", + "continent": "OC" + }, + { + "abbr": "KM", + "name": "Comoros", + "capital": "Moroni", + "population": "832,322", + "continent": "AF" + }, + { + "abbr": "KN", + "name": "St Kitts and Nevis", + "capital": "Basseterre", + "population": "52,441", + "continent": "NA" + }, + { + "abbr": "KP", + "name": "North Korea", + "capital": "Pyongyang", + "population": "25,549,819", + "continent": "AS" + }, + { + "abbr": "KR", + "name": "South Korea", + "capital": "Seoul", + "population": "51,635,256", + "continent": "AS" + }, + { + "abbr": "KW", + "name": "Kuwait", + "capital": "Kuwait City", + "population": "4,137,309", + "continent": "AS" + }, + { + "abbr": "KY", + "name": "Cayman Islands", + "capital": "George Town", + "population": "64,174", + "continent": "NA" + }, + { + "abbr": "KZ", + "name": "Kazakhstan", + "capital": "Nur-Sultan", + "population": "18,276,499", + "continent": "AS" + }, + { + "abbr": "LA", + "name": "Laos", + "capital": "Vientiane", + "population": "7,061,507", + "continent": "AS" + }, + { + "abbr": "LB", + "name": "Lebanon", + "capital": "Beirut", + "population": "6,848,925", + "continent": "AS" + }, + { + "abbr": "LC", + "name": "Saint Lucia", + "capital": "Castries", + "population": "181,889", + "continent": "NA" + }, + { + "abbr": "LI", + "name": "Liechtenstein", + "capital": "Vaduz", + "population": "37,910", + "continent": "EU" + }, + { + "abbr": "LK", + "name": "Sri Lanka", + "capital": "Colombo", + "population": "21,670,000", + "continent": "AS" + }, + { + "abbr": "LR", + "name": "Liberia", + "capital": "Monrovia", + "population": "4,818,977", + "continent": "AF" + }, + { + "abbr": "LS", + "name": "Lesotho", + "capital": "Maseru", + "population": "2,108,132", + "continent": "AF" + }, + { + "abbr": "LT", + "name": "Lithuania", + "capital": "Vilnius", + "population": "2,789,533", + "continent": "EU" + }, + { + "abbr": "LU", + "name": "Luxembourg", + "capital": "Luxembourg", + "population": "607,728", + "continent": "EU" + }, + { + "abbr": "LV", + "name": "Latvia", + "capital": "Riga", + "population": "1,926,542", + "continent": "EU" + }, + { + "abbr": "LY", + "name": "Libya", + "capital": "Tripoli", + "population": "6,678,567", + "continent": "AF" + }, + { + "abbr": "MA", + "name": "Morocco", + "capital": "Rabat", + "population": "36,029,138", + "continent": "AF" + }, + { + "abbr": "MC", + "name": "Monaco", + "capital": "Monaco", + "population": "38,682", + "continent": "EU" + }, + { + "abbr": "MD", + "name": "Moldova", + "capital": "Chisinau", + "population": "3,545,883", + "continent": "EU" + }, + { + "abbr": "ME", + "name": "Montenegro", + "capital": "Podgorica", + "population": "622,345", + "continent": "EU" + }, + { + "abbr": "MF", + "name": "Saint Martin", + "capital": "Marigot", + "population": "37,264", + "continent": "NA" + }, + { + "abbr": "MG", + "name": "Madagascar", + "capital": "Antananarivo", + "population": "26,262,368", + "continent": "AF" + }, + { + "abbr": "MH", + "name": "Marshall Islands", + "capital": "Majuro", + "population": "58,413", + "continent": "OC" + }, + { + "abbr": "MK", + "name": "North Macedonia", + "capital": "Skopje", + "population": "2,082,958", + "continent": "EU" + }, + { + "abbr": "ML", + "name": "Mali", + "capital": "Bamako", + "population": "19,077,690", + "continent": "AF" + }, + { + "abbr": "MM", + "name": "Myanmar", + "capital": "Nay Pyi Taw", + "population": "53,708,395", + "continent": "AS" + }, + { + "abbr": "MN", + "name": "Mongolia", + "capital": "Ulaanbaatar", + "population": "3,170,208", + "continent": "AS" + }, + { + "abbr": "MO", + "name": "Macao", + "capital": "Macao", + "population": "631,636", + "continent": "AS" + }, + { + "abbr": "MP", + "name": "Northern Mariana Islands", + "capital": "Saipan", + "population": "56,882", + "continent": "OC" + }, + { + "abbr": "MQ", + "name": "Martinique", + "capital": "Fort-de-France", + "population": "432,900", + "continent": "NA" + }, + { + "abbr": "MR", + "name": "Mauritania", + "capital": "Nouakchott", + "population": "4,403,319", + "continent": "AF" + }, + { + "abbr": "MS", + "name": "Montserrat", + "capital": "Plymouth", + "population": "9,341", + "continent": "NA" + }, + { + "abbr": "MT", + "name": "Malta", + "capital": "Valletta", + "population": "483,530", + "continent": "EU" + }, + { + "abbr": "MU", + "name": "Mauritius", + "capital": "Port Louis", + "population": "1,265,303", + "continent": "AF" + }, + { + "abbr": "MV", + "name": "Maldives", + "capital": "Male", + "population": "515,696", + "continent": "AS" + }, + { + "abbr": "MW", + "name": "Malawi", + "capital": "Lilongwe", + "population": "17,563,749", + "continent": "AF" + }, + { + "abbr": "MX", + "name": "Mexico", + "capital": "Mexico City", + "population": "126,190,788", + "continent": "NA" + }, + { + "abbr": "MY", + "name": "Malaysia", + "capital": "Kuala Lumpur", + "population": "31,528,585", + "continent": "AS" + }, + { + "abbr": "MZ", + "name": "Mozambique", + "capital": "Maputo", + "population": "29,495,962", + "continent": "AF" + }, + { + "abbr": "NA", + "name": "Namibia", + "capital": "Windhoek", + "population": "2,448,255", + "continent": "AF" + }, + { + "abbr": "NC", + "name": "New Caledonia", + "capital": "Noumea", + "population": "284,060", + "continent": "OC" + }, + { + "abbr": "NE", + "name": "Niger", + "capital": "Niamey", + "population": "22,442,948", + "continent": "AF" + }, + { + "abbr": "NF", + "name": "Norfolk Island", + "capital": "Kingston", + "population": "1,828", + "continent": "OC" + }, + { + "abbr": "NG", + "name": "Nigeria", + "capital": "Abuja", + "population": "195,874,740", + "continent": "AF" + }, + { + "abbr": "NI", + "name": "Nicaragua", + "capital": "Managua", + "population": "6,465,513", + "continent": "NA" + }, + { + "abbr": "NL", + "name": "The Netherlands", + "capital": "Amsterdam", + "population": "17,231,017", + "continent": "EU" + }, + { + "abbr": "NO", + "name": "Norway", + "capital": "Oslo", + "population": "5,314,336", + "continent": "EU" + }, + { + "abbr": "NP", + "name": "Nepal", + "capital": "Kathmandu", + "population": "28,087,871", + "continent": "AS" + }, + { + "abbr": "NR", + "name": "Nauru", + "capital": "Yaren", + "population": "12,704", + "continent": "OC" + }, + { + "abbr": "NU", + "name": "Niue", + "capital": "Alofi", + "population": "2,166", + "continent": "OC" + }, + { + "abbr": "NZ", + "name": "New Zealand", + "capital": "Wellington", + "population": "4,885,500", + "continent": "OC" + }, + { + "abbr": "OM", + "name": "Oman", + "capital": "Muscat", + "population": "4,829,483", + "continent": "AS" + }, + { + "abbr": "PA", + "name": "Panama", + "capital": "Panama City", + "population": "4,176,873", + "continent": "NA" + }, + { + "abbr": "PE", + "name": "Peru", + "capital": "Lima", + "population": "31,989,256", + "continent": "SA" + }, + { + "abbr": "PF", + "name": "French Polynesia", + "capital": "Papeete", + "population": "277,679", + "continent": "OC" + }, + { + "abbr": "PG", + "name": "Papua New Guinea", + "capital": "Port Moresby", + "population": "8,606,316", + "continent": "OC" + }, + { + "abbr": "PH", + "name": "Philippines", + "capital": "Manila", + "population": "106,651,922", + "continent": "AS" + }, + { + "abbr": "PK", + "name": "Pakistan", + "capital": "Islamabad", + "population": "212,215,030", + "continent": "AS" + }, + { + "abbr": "PL", + "name": "Poland", + "capital": "Warsaw", + "population": "37,978,548", + "continent": "EU" + }, + { + "abbr": "PM", + "name": "Saint Pierre and Miquelon", + "capital": "Saint-Pierre", + "population": "7,012", + "continent": "NA" + }, + { + "abbr": "PN", + "name": "Pitcairn Islands", + "capital": "Adamstown", + "population": "46", + "continent": "OC" + }, + { + "abbr": "PR", + "name": "Puerto Rico", + "capital": "San Juan", + "population": "3,195,153", + "continent": "NA" + }, + { + "abbr": "PS", + "name": "Palestine", + "capital": "East Jerusalem", + "population": "4,569,087", + "continent": "AS" + }, + { + "abbr": "PT", + "name": "Portugal", + "capital": "Lisbon", + "population": "10,281,762", + "continent": "EU" + }, + { + "abbr": "PW", + "name": "Palau", + "capital": "Melekeok", + "population": "17,907", + "continent": "OC" + }, + { + "abbr": "PY", + "name": "Paraguay", + "capital": "Asuncion", + "population": "6,956,071", + "continent": "SA" + }, + { + "abbr": "QA", + "name": "Qatar", + "capital": "Doha", + "population": "2,781,677", + "continent": "AS" + }, + { + "abbr": "RE", + "name": "Réunion", + "capital": "Saint-Denis", + "population": "776,948", + "continent": "AF" + }, + { + "abbr": "RO", + "name": "Romania", + "capital": "Bucharest", + "population": "19,473,936", + "continent": "EU" + }, + { + "abbr": "RS", + "name": "Serbia", + "capital": "Belgrade", + "population": "6,982,084", + "continent": "EU" + }, + { + "abbr": "RU", + "name": "Russia", + "capital": "Moscow", + "population": "144,478,050", + "continent": "EU" + }, + { + "abbr": "RW", + "name": "Rwanda", + "capital": "Kigali", + "population": "12,301,939", + "continent": "AF" + }, + { + "abbr": "SA", + "name": "Saudi Arabia", + "capital": "Riyadh", + "population": "33,699,947", + "continent": "AS" + }, + { + "abbr": "SB", + "name": "Solomon Islands", + "capital": "Honiara", + "population": "652,858", + "continent": "OC" + }, + { + "abbr": "SC", + "name": "Seychelles", + "capital": "Victoria", + "population": "96,762", + "continent": "AF" + }, + { + "abbr": "SD", + "name": "Sudan", + "capital": "Khartoum", + "population": "41,801,533", + "continent": "AF" + }, + { + "abbr": "SE", + "name": "Sweden", + "capital": "Stockholm", + "population": "10,183,175", + "continent": "EU" + }, + { + "abbr": "SG", + "name": "Singapore", + "capital": "Singapore", + "population": "5,638,676", + "continent": "AS" + }, + { + "abbr": "SH", + "name": "Saint Helena", + "capital": "Jamestown", + "population": "7,460", + "continent": "AF" + }, + { + "abbr": "SI", + "name": "Slovenia", + "capital": "Ljubljana", + "population": "2,067,372", + "continent": "EU" + }, + { + "abbr": "SJ", + "name": "Svalbard and Jan Mayen", + "capital": "Longyearbyen", + "population": "2,550", + "continent": "EU" + }, + { + "abbr": "SK", + "name": "Slovakia", + "capital": "Bratislava", + "population": "5,447,011", + "continent": "EU" + }, + { + "abbr": "SL", + "name": "Sierra Leone", + "capital": "Freetown", + "population": "7,650,154", + "continent": "AF" + }, + { + "abbr": "SM", + "name": "San Marino", + "capital": "San Marino", + "population": "33,785", + "continent": "EU" + }, + { + "abbr": "SN", + "name": "Senegal", + "capital": "Dakar", + "population": "15,854,360", + "continent": "AF" + }, + { + "abbr": "SO", + "name": "Somalia", + "capital": "Mogadishu", + "population": "15,008,154", + "continent": "AF" + }, + { + "abbr": "SR", + "name": "Suriname", + "capital": "Paramaribo", + "population": "575,991", + "continent": "SA" + }, + { + "abbr": "SS", + "name": "South Sudan", + "capital": "Juba", + "population": "8,260,490", + "continent": "AF" + }, + { + "abbr": "ST", + "name": "São Tomé and Príncipe", + "capital": "Sao Tome", + "population": "197,700", + "continent": "AF" + }, + { + "abbr": "SV", + "name": "El Salvador", + "capital": "San Salvador", + "population": "6,420,744", + "continent": "NA" + }, + { + "abbr": "SX", + "name": "Sint Maarten", + "capital": "Philipsburg", + "population": "40,654", + "continent": "NA" + }, + { + "abbr": "SY", + "name": "Syria", + "capital": "Damascus", + "population": "16,906,283", + "continent": "AS" + }, + { + "abbr": "SZ", + "name": "Eswatini", + "capital": "Mbabane", + "population": "1,136,191", + "continent": "AF" + }, + { + "abbr": "TC", + "name": "Turks and Caicos Islands", + "capital": "Cockburn Town", + "population": "37,665", + "continent": "NA" + }, + { + "abbr": "TD", + "name": "Chad", + "capital": "N'Djamena", + "population": "15,477,751", + "continent": "AF" + }, + { + "abbr": "TF", + "name": "French Southern Territories", + "capital": "Port-aux-Francais", + "population": "140", + "continent": "AN" + }, + { + "abbr": "TG", + "name": "Togo", + "capital": "Lome", + "population": "7,889,094", + "continent": "AF" + }, + { + "abbr": "TH", + "name": "Thailand", + "capital": "Bangkok", + "population": "69,428,524", + "continent": "AS" + }, + { + "abbr": "TJ", + "name": "Tajikistan", + "capital": "Dushanbe", + "population": "9,100,837", + "continent": "AS" + }, + { + "abbr": "TK", + "name": "Tokelau", + "capital": "", + "population": "1,466", + "continent": "OC" + }, + { + "abbr": "TL", + "name": "Timor-Leste", + "capital": "Dili", + "population": "1,267,972", + "continent": "OC" + }, + { + "abbr": "TM", + "name": "Turkmenistan", + "capital": "Ashgabat", + "population": "5,850,908", + "continent": "AS" + }, + { + "abbr": "TN", + "name": "Tunisia", + "capital": "Tunis", + "population": "11,565,204", + "continent": "AF" + }, + { + "abbr": "TO", + "name": "Tonga", + "capital": "Nuku'alofa", + "population": "103,197", + "continent": "OC" + }, + { + "abbr": "TR", + "name": "Türkiye", + "capital": "Ankara", + "population": "82,319,724", + "continent": "AS" + }, + { + "abbr": "TT", + "name": "Trinidad and Tobago", + "capital": "Port of Spain", + "population": "1,389,858", + "continent": "NA" + }, + { + "abbr": "TV", + "name": "Tuvalu", + "capital": "Funafuti", + "population": "11,508", + "continent": "OC" + }, + { + "abbr": "TW", + "name": "Taiwan", + "capital": "Taipei", + "population": "23,451,837", + "continent": "AS" + }, + { + "abbr": "TZ", + "name": "Tanzania", + "capital": "Dodoma", + "population": "56,318,348", + "continent": "AF" + }, + { + "abbr": "UA", + "name": "Ukraine", + "capital": "Kyiv", + "population": "44,622,516", + "continent": "EU" + }, + { + "abbr": "UG", + "name": "Uganda", + "capital": "Kampala", + "population": "42,723,139", + "continent": "AF" + }, + { + "abbr": "UM", + "name": "U.S. Outlying Islands", + "capital": "", + "population": "0", + "continent": "OC" + }, + { + "abbr": "US", + "name": "United States", + "capital": "Washington", + "population": "327,167,434", + "continent": "NA" + }, + { + "abbr": "UY", + "name": "Uruguay", + "capital": "Montevideo", + "population": "3,449,299", + "continent": "SA" + }, + { + "abbr": "UZ", + "name": "Uzbekistan", + "capital": "Tashkent", + "population": "32,955,400", + "continent": "AS" + }, + { + "abbr": "VA", + "name": "Vatican City", + "capital": "Vatican City", + "population": "921", + "continent": "EU" + }, + { + "abbr": "VC", + "name": "St Vincent and Grenadines", + "capital": "Kingstown", + "population": "110,211", + "continent": "NA" + }, + { + "abbr": "VE", + "name": "Venezuela", + "capital": "Caracas", + "population": "28,870,195", + "continent": "SA" + }, + { + "abbr": "VG", + "name": "British Virgin Islands", + "capital": "Road Town", + "population": "29,802", + "continent": "NA" + }, + { + "abbr": "VI", + "name": "U.S. Virgin Islands", + "capital": "Charlotte Amalie", + "population": "106,977", + "continent": "NA" + }, + { + "abbr": "VN", + "name": "Vietnam", + "capital": "Hanoi", + "population": "95,540,395", + "continent": "AS" + }, + { + "abbr": "VU", + "name": "Vanuatu", + "capital": "Port Vila", + "population": "292,680", + "continent": "OC" + }, + { + "abbr": "WF", + "name": "Wallis and Futuna", + "capital": "Mata Utu", + "population": "16,025", + "continent": "OC" + }, + { + "abbr": "WS", + "name": "Samoa", + "capital": "Apia", + "population": "196,130", + "continent": "OC" + }, + { + "abbr": "XK", + "name": "Kosovo", + "capital": "Pristina", + "population": "1,845,300", + "continent": "EU" + }, + { + "abbr": "YE", + "name": "Yemen", + "capital": "Sanaa", + "population": "28,498,687", + "continent": "AS" + }, + { + "abbr": "YT", + "name": "Mayotte", + "capital": "Mamoudzou", + "population": "279,471", + "continent": "AF" + }, + { + "abbr": "ZA", + "name": "South Africa", + "capital": "Pretoria", + "population": "57,779,622", + "continent": "AF" + }, + { + "abbr": "ZM", + "name": "Zambia", + "capital": "Lusaka", + "population": "17,351,822", + "continent": "AF" + }, + { + "abbr": "ZW", + "name": "Zimbabwe", + "capital": "Harare", + "population": "14,439,018", + "continent": "AF" + } + ] +} \ No newline at end of file diff --git a/vendor/github.com/go-faker/faker/v4/payment.go b/vendor/github.com/go-faker/faker/v4/payment.go new file mode 100644 index 0000000..1bb8776 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/payment.go @@ -0,0 +1,100 @@ +package faker + +import ( + "reflect" + "strconv" + "strings" + + "github.com/go-faker/faker/v4/pkg/options" +) + +const ( + numberBytes = "0123456789" +) + +// creditCard struct +type creditCard struct { + ccType string + length int + prefixes []int +} + +var creditCards = map[string]creditCard{ + "visa": {"VISA", 16, []int{4539, 4556, 4916, 4532, 4929, 40240071, 4485, 4716, 4}}, + "mastercard": {"MasterCard", 16, []int{51, 52, 53, 54, 55}}, + "american express": {"American Express", 15, []int{34, 37}}, + "discover": {"Discover", 16, []int{6011}}, + "jcb": {"JCB", 16, []int{3528, 3538, 3548, 3558, 3568, 3578, 3588}}, + "diners club": {"Diners Club", 14, []int{36, 38, 39}}, +} + +var cacheCreditCard string + +// GetPayment returns a new Render interface of Payment struct +func GetPayment() Render { + pay := &Payment{} + return pay +} + +// Render contains Whole Random Credit Card Generators with their types +type Render interface { + CreditCardType(v reflect.Value) (any, error) + CreditCardNumber(v reflect.Value) (any, error) +} + +// Payment struct +type Payment struct{} + +func (p Payment) cctype() string { + n := len(creditCards) + if cacheCreditCard != "" { + return cacheCreditCard + } + var ccTypes []string + + for _, cc := range creditCards { + ccTypes = append(ccTypes, cc.ccType) + } + cacheCreditCard = ccTypes[rand.Intn(n)] + return cacheCreditCard +} + +// CreditCardType returns one of the following credit values: +// VISA, MasterCard, American Express, Discover, JCB and Diners Club +func (p Payment) CreditCardType(v reflect.Value) (any, error) { + return p.cctype(), nil +} + +// CCType get a credit card type randomly in string (VISA, MasterCard, etc) +func CCType(opts ...options.OptionFunc) string { + return singleFakeData(CreditCardType, func() any { + p := Payment{} + return p.cctype() + }, opts...).(string) +} + +func (p Payment) ccnumber() string { + ccType := p.cctype() + cacheCreditCard = ccType + card := creditCards[strings.ToLower(ccType)] + prefix := strconv.Itoa(card.prefixes[rand.Intn(len(card.prefixes))]) + + num := prefix + digit := randomStringNumber(card.length - len(prefix)) + + num += digit + return num +} + +// CreditCardNumber generated credit card number according to the card number rules +func (p Payment) CreditCardNumber(v reflect.Value) (any, error) { + return p.ccnumber(), nil +} + +// CCNumber get a credit card number randomly in string (VISA, MasterCard, etc) +func CCNumber(opts ...options.OptionFunc) string { + return singleFakeData(CreditCardNumber, func() any { + p := Payment{} + return p.ccnumber() + }, opts...).(string) +} diff --git a/vendor/github.com/go-faker/faker/v4/person.go b/vendor/github.com/go-faker/faker/v4/person.go new file mode 100644 index 0000000..4af7892 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/person.go @@ -0,0 +1,877 @@ +package faker + +import ( + "fmt" + "reflect" + + "github.com/go-faker/faker/v4/pkg/options" +) + +// Dowser provides interfaces to generate random logical Names with their initials +type Dowser interface { + TitleMale(v reflect.Value) (any, error) + TitleFeMale(v reflect.Value) (any, error) + FirstName(v reflect.Value) (any, error) + FirstNameMale(v reflect.Value) (any, error) + FirstNameFemale(v reflect.Value) (any, error) + LastName(v reflect.Value) (any, error) + Name(v reflect.Value) (any, error) + Gender(v reflect.Value) (any, error) + ChineseFirstName(v reflect.Value) (any, error) + ChineseLastName(v reflect.Value) (any, error) + ChineseName(v reflect.Value) (any, error) + RussianFirstNameMale(v reflect.Value) (any, error) + RussianMiddleNameMale(v reflect.Value) (any, error) + RussianLastNameMale(v reflect.Value) (any, error) + RussianFirstNameFemale(v reflect.Value) (any, error) + RussianMiddleNameFemale(v reflect.Value) (any, error) + RussianLastNameFemale(v reflect.Value) (any, error) +} + +var titlesMale = []string{ + "Mr.", "Dr.", "Prof.", "Lord", "King", "Prince", +} +var titlesFemale = []string{ + "Mrs.", "Ms.", "Miss", "Dr.", "Prof.", "Lady", "Queen", "Princess", +} +var firstNamesMale = []string{ + "Aaron", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abner", "Abraham", "Adalberto", "Adam", "Adan", "Adelbert", "Adolfo", "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriel", "Adrien", "Afton", "Agustin", "Ahmad", "Ahmed", "Aidan", "Aiden", "Akeem", "Al", "Alan", "Albert", "Alberto", "Albin", "Alden", "Alec", "Alejandrin", "Alek", "Alessandro", "Alex", "Alexander", "Alexandre", "Alexandro", "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo", "Alford", "Alfred", "Alfredo", "Ali", "Allan", "Allen", "Alphonso", "Alvah", "Alvis", "Amani", "Amari", "Ambrose", "Americo", "Amir", "Amos", "Amparo", "Anastacio", "Anderson", "Andre", "Andres", "Andrew", "Andy", "Angel", "Angelo", "Angus", "Anibal", "Ansel", "Ansley", "Anthony", "Antone", "Antonio", "Antwan", "Antwon", "Arch", "Archibald", "Arden", "Arely", "Ari", "Aric", "Ariel", "Arjun", "Arlo", "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo", "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Ashton", "August", "Augustus", "Aurelio", "Austen", "Austin", "Austyn", "Avery", "Axel", "Ayden", + "Bailey", "Barney", "Baron", "Barrett", "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beau", "Bell", "Ben", "Benedict", "Benjamin", "Bennett", "Bennie", "Benny", "Benton", "Bernard", "Bernardo", "Bernhard", "Bernie", "Berry", "Berta", "Bertha", "Bertram", "Bertrand", "Bill", "Billy", "Blair", "Blaise", "Blake", "Blaze", "Bo", "Bobbie", "Bobby", "Boris", "Boyd", "Brad", "Braden", "Bradford", "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brando", "Brandon", "Brandt", "Brannon", "Branson", "Brant", "Braulio", "Braxton", "Brayan", "Brendan", "Brenden", "Brendon", "Brennan", "Brennon", "Brent", "Bret", "Brett", "Brian", "Brice", "Brock", "Broderick", "Brody", "Brook", "Brooks", "Brown", "Bruce", "Bryce", "Brycen", "Bryon", "Buck", "Bud", "Buddy", "Buford", "Burley", "Buster", + "Cade", "Caden", "Caesar", "Cale", "Caleb", "Camden", "Cameron", "Camren", "Camron", "Camryn", "Candelario", "Candido", "Carey", "Carleton", "Carlo", "Carlos", "Carmel", "Carmelo", "Carmine", "Carol", "Carroll", "Carson", "Carter", "Cary", "Casey", "Casimer", "Casimir", "Casper", "Ceasar", "Cecil", "Cedrick", "Celestino", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim", "Chance", "Chandler", "Charles", "Charley", "Charlie", "Chase", "Chauncey", "Chaz", "Chelsey", "Chesley", "Chester", "Chet", "Chris", "Christ", "Christian", "Christop", "Christophe", "Christopher", "Cicero", "Cielo", "Clair", "Clark", "Claud", "Claude", "Clay", "Clemens", "Clement", "Cleo", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton", "Clint", "Clinton", "Clovis", "Cloyd", "Clyde", "Coby", "Cody", "Colby", "Cole", "Coleman", "Colin", "Collin", "Colt", "Colten", "Colton", "Columbus", "Conner", "Connor", "Conor", "Conrad", "Constantin", "Consuelo", "Cooper", "Corbin", "Cordelia", "Cordell", "Cornelius", "Cornell", "Cortez", "Cory", "Coty", "Coy", "Craig", "Crawford", "Cristian", "Cristina", "Cristobal", "Cristopher", "Cruz", "Cullen", "Curt", "Curtis", "Cyril", "Cyrus", + "Dagmar", "Dale", "Dallas", "Dallin", "Dalton", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dane", "D'angelo", "Dangelo", "Danial", "Danny", "Dante", "Daren", "Darian", "Darien", "Dario", "Darion", "Darius", "Daron", "Darrel", "Darrell", "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin", "Daryl", "Dashawn", "Dave", "David", "Davin", "Davion", "Davon", "Davonte", "Dawson", "Dax", "Dayne", "Dayton", "Dean", "Deangelo", "Declan", "Dedric", "Dedrick", "Dee", "Deion", "Dejon", "Dejuan", "Delaney", "Delbert", "Dell", "Delmer", "Demarco", "Demarcus", "Demario", "Demetrius", "Demond", "Denis", "Dennis", "Deon", "Deondre", "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick", "Deshaun", "Deshawn", "Desmond", "Destin", "Devan", "Devante", "Deven", "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter", "Diamond", "Diego", "Dillan", "Dillon", "Dimitri", "Dino", "Dion", "Dock", "Domenic", "Domenick", "Domenico", "Domingo", "Dominic", "Don", "Donald", "Donato", "Donavon", "Donnell", "Donnie", "Donny", "Dorcas", "Dorian", "Doris", "Dorthy", "Doug", "Douglas", "Doyle", "Drake", "Dudley", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", + "Earl", "Earnest", "Easter", "Easton", "Ed", "Edd", "Eddie", "Edgar", "Edgardo", "Edison", "Edmond", "Edmund", "Eduardo", "Edward", "Edwardo", "Edwin", "Efrain", "Efren", "Einar", "Eino", "Eladio", "Elbert", "Eldon", "Eldred", "Eleazar", "Eli", "Elian", "Elias", "Eliezer", "Elijah", "Eliseo", "Elliot", "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmo", "Elmore", "Eloy", "Elroy", "Elton", "Elvis", "Elwin", "Elwyn", "Emanuel", "Emerald", "Emerson", "Emery", "Emil", "Emile", "Emiliano", "Emilio", "Emmanuel", "Emmet", "Emmett", "Emmitt", "Emory", "Enid", "Enoch", "Enos", "Enrico", "Enrique", "Ephraim", "Eriberto", "Eric", "Erich", "Erick", "Erik", "Erin", "Erling", "Ernest", "Ernesto", "Ernie", "Ervin", "Erwin", "Esteban", "Estevan", "Ethan", "Ethel", "Eugene", "Eusebio", "Evan", "Evans", "Everardo", "Everett", "Evert", "Ewald", "Ewell", "Ezekiel", "Ezequiel", "Ezra", + "Fabian", "Faustino", "Fausto", "Favian", "Federico", "Felipe", "Felix", "Felton", "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Finn", "Flavio", "Fletcher", "Florencio", "Florian", "Floy", "Floyd", "Ford", "Forest", "Forrest", "Foster", "Francesco", "Francis", "Francisco", "Franco", "Frank", "Frankie", "Franz", "Fred", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik", "Fredrick", "Fredy", "Freeman", "Friedrich", "Fritz", "Furman", + "Gabe", "Gabriel", "Gaetano", "Gage", "Gardner", "Garett", "Garfield", "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison", "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene", "General", "Gennaro", "Geo", "Geoffrey", "George", "Geovanni", "Geovanny", "Geovany", "Gerald", "Gerard", "Gerardo", "Gerhard", "German", "Gerson", "Gianni", "Gideon", "Gilbert", "Gilberto", "Giles", "Gillian", "Gino", "Giovani", "Giovanni", "Giovanny", "Giuseppe", "Glen", "Glennie", "Godfrey", "Golden", "Gonzalo", "Gordon", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson", "Green", "Greg", "Gregg", "Gregorio", "Gregory", "Greyson", "Griffin", "Grover", "Guido", "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust", "Gustave", "Guy", + "Hadley", "Hailey", "Hal", "Haleigh", "Haley", "Halle", "Hank", "Hans", "Hardy", "Harley", "Harmon", "Harold", "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hayden", "Hayley", "Hazel", "Hazle", "Heber", "Hector", "Helmer", "Henderson", "Henri", "Henry", "Herbert", "Herman", "Hermann", "Herminio", "Hershel", "Hester", "Hilario", "Hilbert", "Hillard", "Hilton", "Hipolito", "Hiram", "Hobart", "Holden", "Hollis", "Horace", "Horacio", "Houston", "Howard", "Howell", "Hoyt", "Hubert", "Hudson", "Hugh", "Humberto", "Hunter", "Hyman", + "Ian", "Ibrahim", "Ignacio", "Ignatius", "Ike", "Imani", "Immanuel", "Irving", "Irwin", "Isaac", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael", "Isom", "Israel", "Issac", "Izaiah", + "Jabari", "Jace", "Jacey", "Jacinto", "Jack", "Jackson", "Jacques", "Jaden", "Jadon", "Jaeden", "Jaiden", "Jaime", "Jairo", "Jake", "Jakob", "Jaleel", "Jalen", "Jalon", "Jamaal", "Jamal", "Jamar", "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison", "Jan", "Janick", "Jaquan", "Jared", "Jaren", "Jarod", "Jaron", "Jarred", "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin", "Jason", "Jasper", "Javier", "Javon", "Javonte", "Jay", "Jayce", "Jaycee", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin", "Jaylon", "Jayme", "Jayson", "Jean", "Jed", "Jedediah", "Jedidiah", "Jeff", "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jennings", "Jensen", "Jerad", "Jerald", "Jeramie", "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermey", "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess", "Jesse", "Jessie", "Jessy", "Jesus", "Jett", "Jettie", "Jevon", "Jillian", "Jimmie", "Jimmy", "Jo", "Joan", "Joany", "Joaquin", "Jocelyn", "Joe", "Joel", "Joesph", "Joey", "Johan", "Johann", "Johathan", "John", "Johnathan", "Johnathon", "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jon", "Jonas", "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordi", "Jordon", "Jordy", "Jordyn", "Jorge", "Jose", "Joseph", "Josh", "Joshua", "Joshuah", "Josiah", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Judah", "Judd", "Judge", "Judson", "Jules", "Julian", "Julien", "Julio", "Julius", "Junior", "Junius", "Justen", "Justice", "Juston", "Justus", "Justyn", "Juvenal", "Juwan", + "Kacey", "Kade", "Kaden", "Kadin", "Kale", "Kaleb", "Kaleigh", "Kaley", "Kameron", "Kamren", "Kamron", "Kamryn", "Kane", "Kareem", "Karl", "Karley", "Karson", "Kay", "Kayden", "Kayleigh", "Kayley", "Keagan", "Keanu", "Keaton", "Keegan", "Keeley", "Keenan", "Keith", "Kellen", "Kelley", "Kelton", "Kelvin", "Ken", "Kendall", "Kendrick", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin", "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiel", "Kieran", "Kiley", "Kim", "King", "Kip", "Kirk", "Kobe", "Koby", "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Kristian", "Kristofer", "Kristoffer", "Kristopher", "Kurt", "Kurtis", "Kyle", "Kyleigh", "Kyler", + "Ladarius", "Lafayette", "Lamar", "Lambert", "Lamont", "Lance", "Landen", "Lane", "Laron", "Larry", "Larue", "Laurel", "Lavern", "Laverna", "Laverne", "Lavon", "Lawrence", "Lawson", "Layne", "Lazaro", "Lee", "Leif", "Leland", "Lemuel", "Lennie", "Lenny", "Leo", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leopold", "Leopoldo", "Lesley", "Lester", "Levi", "Lew", "Lewis", "Lexus", "Liam", "Lincoln", "Lindsey", "Linwood", "Lionel", "Lisandro", "Llewellyn", "Lloyd", "Logan", "Lon", "London", "Lonnie", "Lonny", "Lonzo", "Lorenz", "Lorenza", "Lorenzo", "Louie", "Louisa", "Lourdes", "Louvenia", "Lowell", "Loy", "Loyal", "Lucas", "Luciano", "Lucio", "Lucious", "Lucius", "Ludwig", "Luigi", "Luis", "Lukas", "Lula", "Luther", "Lyric", + "Mac", "Macey", "Mack", "Mackenzie", "Madisen", "Madison", "Madyson", "Magnus", "Major", "Makenna", "Malachi", "Malcolm", "Mallory", "Manley", "Manuel", "Manuela", "Marc", "Marcel", "Marcelino", "Marcellus", "Marcelo", "Marco", "Marcos", "Marcus", "Mariano", "Mario", "Mark", "Markus", "Marley", "Marlin", "Marlon", "Marques", "Marquis", "Marshall", "Martin", "Marty", "Marvin", "Mason", "Mateo", "Mathew", "Mathias", "Matt", "Matteo", "Maurice", "Mauricio", "Maverick", "Mavis", "Max", "Maxime", "Maximilian", "Maximillian", "Maximo", "Maximus", "Maxine", "Maxwell", "Maynard", "Mckenna", "Mckenzie", "Mekhi", "Melany", "Melvin", "Melvina", "Merl", "Merle", "Merlin", "Merritt", "Mervin", "Micah", "Michael", "Michale", "Micheal", "Michel", "Miguel", "Mike", "Mikel", "Milan", "Miles", "Milford", "Miller", "Milo", "Milton", "Misael", "Mitchel", "Mitchell", "Modesto", "Mohamed", "Mohammad", "Mohammed", "Moises", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte", "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses", "Moshe", "Muhammad", "Murl", "Murphy", "Murray", "Mustafa", "Myles", "Myrl", "Myron", + "Napoleon", "Narciso", "Nash", "Nasir", "Nat", "Nathan", "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Neal", "Ned", "Neil", "Nels", "Nelson", "Nestor", "Newell", "Newton", "Nicholas", "Nicholaus", "Nick", "Nicklaus", "Nickolas", "Nico", "Nicola", "Nicolas", "Nigel", "Nikko", "Niko", "Nikolas", "Nils", "Noah", "Noble", "Noe", "Noel", "Nolan", "Norbert", "Norberto", "Norris", "Norval", "Norwood", + "Obie", "Oda", "Odell", "Okey", "Ola", "Olaf", "Ole", "Olen", "Olin", "Oliver", "Omari", "Omer", "Oral", "Oran", "Oren", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orrin", "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald", "Oswaldo", "Otho", "Otis", "Ottis", "Otto", "Owen", + "Pablo", "Paolo", "Paris", "Parker", "Patrick", "Paul", "Paxton", "Payton", "Pedro", "Percival", "Percy", "Perry", "Pete", "Peter", "Peyton", "Philip", "Pierce", "Pierre", "Pietro", "Porter", "Presley", "Preston", "Price", "Prince", + "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", + "Rafael", "Raheem", "Rahul", "Raleigh", "Ralph", "Ramiro", "Ramon", "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray", "Raymond", "Raymundo", "Reagan", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald", "Reid", "Reilly", "Reinhold", "Remington", "Rene", "Reuben", "Rex", "Rey", "Reyes", "Reymundo", "Reynold", "Rhett", "Rhiannon", "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie", "Ricky", "Rico", "Rigoberto", "Riley", "Robb", "Robbie", "Robert", "Roberto", "Robin", "Rocio", "Rocky", "Rod", "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio", "Roger", "Rogers", "Rolando", "Rollin", "Roman", "Ron", "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosario", "Roscoe", "Rosendo", "Ross", "Rowan", "Rowland", "Roy", "Royal", "Royce", "Ruben", "Rudolph", "Rudy", "Rupert", "Russ", "Russel", "Russell", "Rusty", "Ryan", "Ryann", "Ryder", "Rylan", "Ryleigh", "Ryley", + "Sage", "Saige", "Salvador", "Salvatore", "Sam", "Samir", "Sammie", "Sammy", "Samson", "Sanford", "Santa", "Santiago", "Santino", "Santos", "Saul", "Savion", "Schuyler", "Scot", "Scottie", "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selmer", "Seth", "Shad", "Shane", "Shaun", "Shawn", "Shayne", "Sheldon", "Sheridan", "Sherman", "Sherwood", "Sid", "Sidney", "Sigmund", "Sigrid", "Sigurd", "Silas", "Sim", "Simeon", "Skye", "Skylar", "Sofia", "Soledad", "Solon", "Sonny", "Spencer", "Stan", "Stanford", "Stanley", "Stanton", "Stefan", "Stephan", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart", "Stone", "Stuart", "Sven", "Sydney", "Sylvan", "Sylvester", + "Tad", "Talon", "Tanner", "Tate", "Tatum", "Taurean", "Tavares", "Taylor", "Ted", "Terence", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tevin", "Thad", "Thaddeus", "Theo", "Theodore", "Theron", "Thomas", "Thurman", "Tillman", "Timmothy", "Timmy", "Timothy", "Tito", "Titus", "Tobin", "Toby", "Tod", "Tom", "Tomas", "Tommie", "Toney", "Toni", "Tony", "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Travis", "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Trever", "Trevion", "Trevor", "Trey", "Tristian", "Tristin", "Triston", "Troy", "Trystan", "Turner", "Tyler", "Tyree", "Tyreek", "Tyrel", "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", + "Ubaldo", "Ulices", "Ulises", "Unique", "Urban", "Uriah", "Uriel", + "Valentin", "Van", "Vance", "Vaughn", "Vern", "Verner", "Vernon", "Vicente", "Victor", "Vidal", "Vince", "Vincent", "Vincenzo", "Vinnie", "Virgil", "Vito", "Vladimir", + "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Ward", "Warren", "Watson", "Waylon", "Wayne", "Webster", "Weldon", "Wellington", "Wendell", "Werner", "Westley", "Weston", "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo", "Wilfrid", "Wilhelm", "Will", "Willard", "William", "Willis", "Willy", "Wilmer", "Wilson", "Wilton", "Winfield", "Winston", "Woodrow", "Wyatt", "Wyman", + "Xavier", "Xzavier", "Xander", + "Yadav", "Yogesh", "Yaatiesh", "Yaamir", + "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery", "Zakary", "Zander", "Zane", "Zechariah", "Zion", +} +var firstNamesFemale = []string{ + "Aaliyah", "Abagail", "Abbey", "Abbie", "Abbigail", "Abby", "Abigail", "Abigale", "Abigayle", "Ada", "Adah", "Adaline", "Addie", "Addison", "Adela", "Adele", "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adriana", "Adrianna", "Adrienne", "Aglae", "Agnes", "Agustina", "Aida", "Aileen", "Aimee", "Aisha", "Aiyana", "Alaina", "Alana", "Alanis", "Alanna", "Alayna", "Alba", "Alberta", "Albertha", "Albina", "Alda", "Aleen", "Alejandra", "Alena", "Alene", "Alessandra", "Alessia", "Aletha", "Alexa", "Alexandra", "Alexandrea", "Alexandria", "Alexandrine", "Alexane", "Alexanne", "Alfreda", "Alia", "Alice", "Alicia", "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize", "Allene", "Allie", "Allison", "Ally", "Alta", "Althea", "Alva", "Alvena", "Alvera", "Alverta", "Alvina", "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda", "Amara", "Amaya", "Amber", "Amelia", "Amelie", "Amely", "America", "Amie", "Amina", "Amira", "Amiya", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi", "Anais", "Anastasia", "Andreane", "Andreanne", "Angela", "Angelica", "Angelina", "Angeline", "Angelita", "Angie", "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel", "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne", "Annetta", "Annette", "Annie", "Antoinette", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina", "Anya", "April", "Ara", "Araceli", "Aracely", "Ardella", "Ardith", "Ariane", "Arianna", "Arielle", "Arlene", "Arlie", "Arvilla", "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey", "Audie", "Audra", "Audreanne", "Audrey", "Augusta", "Augustine", "Aurelia", "Aurelie", "Aurore", "Autumn", "Ava", "Avis", "Ayana", "Ayla", "Aylin", + "Baby", "Bailee", "Barbara", "Beatrice", "Beaulah", "Bella", "Belle", "Berenice", "Bernadette", "Bernadine", "Berneice", "Bernice", "Berniece", "Bernita", "Bert", "Beryl", "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty", "Bettye", "Beulah", "Beverly", "Bianka", "Billie", "Birdie", "Blanca", "Blanche", "Bonita", "Bonnie", "Brandi", "Brandy", "Brandyn", "Breana", "Breanna", "Breanne", "Brenda", "Brenna", "Bria", "Briana", "Brianne", "Bridget", "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney", "Brittany", "Brooke", "Brooklyn", "Bryana", "Bulah", "Burdette", "Burnice", + "Caitlyn", "Caleigh", "Cali", "Calista", "Callie", "Camila", "Camilla", "Camille", "Camylle", "Candace", "Candice", "Candida", "Cara", "Carissa", "Carlee", "Carley", "Carli", "Carlie", "Carlotta", "Carmela", "Carmella", "Carmen", "Carolanne", "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Casandra", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina", "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla", "Cecelia", "Cecile", "Cecilia", "Celestine", "Celia", "Celine", "Chanel", "Chanelle", "Charity", "Charlene", "Charlotte", "Chasity", "Chaya", "Chelsea", "Chelsie", "Cheyanne", "Cheyenne", "Chloe", "Christa", "Christelle", "Christiana", "Christina", "Christine", "Christy", "Chyna", "Ciara", "Cierra", "Cindy", "Citlalli", "Claire", "Clara", "Clarabelle", "Clare", "Clarissa", "Claudia", "Claudie", "Claudine", "Clementina", "Clementine", "Clemmie", "Cleora", "Cleta", "Clotilde", "Colleen", "Concepcion", "Connie", "Constance", "Cora", "Coralie", "Cordia", "Cordie", "Corene", "Corine", "Corrine", "Cortney", "Courtney", "Creola", "Cristal", "Crystal", "Crystel", "Cydney", "Cynthia", + "Dahlia", "Daija", "Daisha", "Daisy", "Dakota", "Damaris", "Dana", "Dandre", "Daniela", "Daniella", "Danielle", "Danika", "Dannie", "Danyka", "Daphne", "Daphnee", "Daphney", "Darby", "Dariana", "Darlene", "Dasia", "Dawn", "Dayana", "Dayna", "Deanna", "Deborah", "Deja", "Dejah", "Delfina", "Delia", "Delilah", "Della", "Delores", "Delpha", "Delphia", "Delphine", "Delta", "Demetris", "Dena", "Desiree", "Dessie", "Destany", "Destinee", "Destiney", "Destini", "Destiny", "Diana", "Dianna", "Dina", "Dixie", "Dolly", "Dolores", "Domenica", "Dominique", "Donna", "Dora", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dovie", "Drew", "Duane", "Dulce", + "Earlene", "Earline", "Earnestine", "Ebba", "Ebony", "Eda", "Eden", "Edna", "Edwina", "Edyth", "Edythe", "Effie", "Eileen", "Elaina", "Elda", "Eldora", "Eldridge", "Eleanora", "Eleanore", "Electa", "Elena", "Elenor", "Elenora", "Eleonore", "Elfrieda", "Eliane", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elmira", "Elna", "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Elsa", "Else", "Elsie", "Elta", "Elva", "Elvera", "Elvie", "Elyse", "Elyssa", "Elza", "Emelia", "Emelie", "Emely", "Emie", "Emilia", "Emilie", "Emily", "Emma", "Emmalee", "Emmanuelle", "Emmie", "Emmy", "Ena", "Enola", "Era", "Erica", "Ericka", "Erika", "Erna", "Ernestina", "Ernestine", "Eryn", "Esmeralda", "Esperanza", "Esta", "Estefania", "Estel", "Estell", "Estella", "Estelle", "Esther", "Estrella", "Etha", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eva", "Evalyn", "Evangeline", "Eve", "Eveline", "Evelyn", "Everette", "Evie", + "Fabiola", "Fae", "Fannie", "Fanny", "Fatima", "Fay", "Faye", "Felicia", "Felicita", "Felicity", "Felipa", "Filomena", "Fiona", "Flavie", "Fleta", "Flo", "Florence", "Florida", "Florine", "Flossie", "Frances", "Francesca", "Francisca", "Freda", "Frederique", "Freeda", "Freida", "Frida", "Frieda", + "Gabriella", "Gabrielle", "Gail", "Genesis", "Genevieve", "Genoveva", "Georgette", "Georgiana", "Georgianna", "Geraldine", "Gerda", "Germaine", "Gerry", "Gertrude", "Gia", "Gilda", "Gina", "Giovanna", "Gisselle", "Gladyce", "Gladys", "Glenda", "Glenna", "Gloria", "Golda", "Grace", "Gracie", "Graciela", "Gregoria", "Greta", "Gretchen", "Guadalupe", "Gudrun", "Gwen", "Gwendolyn", + "Hailee", "Hailie", "Halie", "Hallie", "Hanna", "Hannah", "Harmony", "Hassie", "Hattie", "Haven", "Haylee", "Haylie", "Heath", "Heather", "Heaven", "Heidi", "Helen", "Helena", "Helene", "Helga", "Hellen", "Heloise", "Henriette", "Hermina", "Herminia", "Herta", "Hertha", "Hettie", "Hilda", "Hildegard", "Hillary", "Hilma", "Hollie", "Holly", "Hope", "Hortense", "Hosea", "Hulda", + "Icie", "Ida", "Idell", "Idella", "Ila", "Ilene", "Iliana", "Ima", "Imelda", "Imogene", "Ines", "Irma", "Isabel", "Isabell", "Isabella", "Isabelle", "Isobel", "Itzel", "Iva", "Ivah", "Ivory", "Ivy", "Izabella", + "Jacinthe", "Jackeline", "Jackie", "Jacklyn", "Jacky", "Jaclyn", "Jacquelyn", "Jacynthe", "Jada", "Jade", "Jadyn", "Jaida", "Jailyn", "Jakayla", "Jalyn", "Jammie", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet", "Janice", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquelin", "Jaqueline", "Jaunita", "Jayda", "Jayne", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne", "Jeanette", "Jeanie", "Jeanne", "Jena", "Jenifer", "Jennie", "Jennifer", "Jennyfer", "Jermaine", "Jessica", "Jessika", "Jessyca", "Jewel", "Jewell", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Jodie", "Jody", "Joelle", "Johanna", "Jolie", "Jordane", "Josefa", "Josefina", "Josephine", "Josiane", "Josianne", "Josie", "Joy", "Joyce", "Juana", "Juanita", "Jude", "Judy", "Julia", "Juliana", "Julianne", "Julie", "Juliet", "June", "Justina", "Justine", + "Kaci", "Kacie", "Kaela", "Kaelyn", "Kaia", "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kali", "Kallie", "Kamille", "Kara", "Karelle", "Karen", "Kari", "Kariane", "Karianne", "Karina", "Karine", "Karlee", "Karli", "Karlie", "Karolann", "Kasandra", "Kasey", "Kassandra", "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine", "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn", "Katrina", "Katrine", "Kattie", "Kavon", "Kaya", "Kaycee", "Kayla", "Kaylah", "Kaylee", "Kayli", "Kaylie", "Kaylin", "Keara", "Keely", "Keira", "Kelli", "Kellie", "Kelly", "Kelsi", "Kelsie", "Kendra", "Kenna", "Kenya", "Kenyatta", "Kiana", "Kianna", "Kiara", "Kiarra", "Kiera", "Kimberly", "Kira", "Kirsten", "Kirstin", "Kitty", "Krista", "Kristin", "Kristina", "Kristy", "Krystal", "Krystel", "Krystina", "Kyla", "Kylee", "Kylie", "Kyra", + "Lacey", "Lacy", "Laila", "Laisha", "Laney", "Larissa", "Laura", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie", "Laurine", "Laury", "Lauryn", "Lavada", "Lavina", "Lavinia", "Lavonne", "Layla", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda", "Leila", "Leilani", "Lela", "Lelah", "Lelia", "Lempi", "Lenna", "Lenora", "Lenore", "Leola", "Leonie", "Leonor", "Leonora", "Leora", "Lera", "Leslie", "Lesly", "Lessie", "Leta", "Letha", "Letitia", "Lexi", "Lexie", "Lia", "Liana", "Libbie", "Libby", "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana", "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Linda", "Lindsay", "Linnea", "Linnie", "Lisa", "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Lois", "Lola", "Lolita", "Loma", "Lonie", "Lora", "Loraine", "Loren", "Lorena", "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Loyce", "Lucie", "Lucienne", "Lucile", "Lucinda", "Lucy", "Ludie", "Lue", "Luella", "Luisa", "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luz", "Lyda", "Lydia", "Lyla", "Lynn", "Lysanne", + "Mabel", "Mabelle", "Mable", "Maci", "Macie", "Macy", "Madaline", "Madalyn", "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn", "Madisyn", "Madonna", "Mae", "Maegan", "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia", "Maia", "Maida", "Maiya", "Makayla", "Makenzie", "Malika", "Malinda", "Mallie", "Malvina", "Mandy", "Mara", "Marcelina", "Marcella", "Marcelle", "Marcia", "Margaret", "Margarete", "Margarett", "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot", "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana", "Mariane", "Marianna", "Marianne", "Maribel", "Marie", "Mariela", "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory", "Marlee", "Marlen", "Marlene", "Marquise", "Marta", "Martina", "Martine", "Mary", "Maryam", "Maryjane", "Maryse", "Mathilde", "Matilda", "Matilde", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurine", "Maxie", "Maximillia", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Mayra", "Mazie", "Mckayla", "Meagan", "Meaghan", "Meda", "Megane", "Meggie", "Meghan", "Melba", "Melisa", "Melissa", "Mellie", "Melody", "Melyna", "Melyssa", "Mercedes", "Meredith", "Mertie", "Meta", "Mia", "Micaela", "Michaela", "Michele", "Michelle", "Mikayla", "Millie", "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Missouri", "Misty", "Mittie", "Modesta", "Mollie", "Molly", "Mona", "Monica", "Monique", "Mossie", "Mozell", "Mozelle", "Muriel", "Mya", "Myah", "Mylene", "Myra", "Myriam", "Myrna", "Myrtice", "Myrtie", "Myrtis", "Myrtle", + "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Natalia", "Natalie", "Natasha", "Nayeli", "Nedra", "Neha", "Nelda", "Nella", "Nelle", "Nellie", "Neoma", "Nettie", "Neva", "Nia", "Nichole", "Nicole", "Nicolette", "Nikita", "Nikki", "Nina", "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nona", "Nora", "Norene", "Norma", "Nova", "Novella", "Nya", "Nyah", "Nyasia", + "Oceane", "Ocie", "Octavia", "Odessa", "Odie", "Ofelia", "Oleta", "Olga", "Ollie", "Oma", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Orie", "Orpha", "Otha", "Otilia", "Ottilie", "Ova", "Ozella", + "Paige", "Palma", "Pamela", "Pansy", "Pascale", "Pasquale", "Pat", "Patience", "Patricia", "Patsy", "Pattie", "Paula", "Pauline", "Pearl", "Pearlie", "Pearline", "Peggie", "Penelope", "Petra", "Phoebe", "Phyllis", "Pink", "Pinkie", "Piper", "Polly", "Precious", "Princess", "Priscilla", "Providenci", "Prudence", + "Queen", "Queenie", + "Rachael", "Rachel", "Rachelle", "Rae", "Raegan", "Rafaela", "Rahsaan", "Raina", "Ramona", "Raphaelle", "Raquel", "Reanna", "Reba", "Rebeca", "Rebecca", "Rebeka", "Rebekah", "Reina", "Renee", "Ressie", "Reta", "Retha", "Retta", "Reva", "Reyna", "Rhea", "Rhianna", "Rhoda", "Rita", "River", "Roberta", "Robyn", "Roma", "Romaine", "Rosa", "Rosalee", "Rosalia", "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosetta", "Rosie", "Rosina", "Roslyn", "Rossie", "Rowena", "Roxane", "Roxanne", "Rozella", "Rubie", "Ruby", "Rubye", "Ruth", "Ruthe", "Ruthie", "Rylee", + "Sabina", "Sabrina", "Sabryna", "Sadie", "Sadye", "Sallie", "Sally", "Salma", "Samanta", "Samantha", "Samara", "Sandra", "Sandrine", "Sandy", "Santina", "Sarah", "Sarai", "Sarina", "Sasha", "Savanah", "Savanna", "Savannah", "Scarlett", "Selena", "Selina", "Serena", "Serenity", "Shaina", "Shakira", "Shana", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna", "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shawna", "Shaylee", "Shayna", "Shea", "Sheila", "Shemar", "Shirley", "Shyann", "Shyanne", "Sibyl", "Sienna", "Sierra", "Simone", "Sincere", "Sister", "Skyla", "Sonia", "Sonya", "Sophia", "Sophie", "Stacey", "Stacy", "Stefanie", "Stella", "Stephania", "Stephanie", "Stephany", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie", "Suzanne", "Syble", "Sydnee", "Sydni", "Sydnie", "Sylvia", + "Tabitha", "Talia", "Tamara", "Tamia", "Tania", "Tanya", "Tara", "Taryn", "Tatyana", "Taya", "Teagan", "Telly", "Teresa", "Tess", "Tessie", "Thalia", "Thea", "Thelma", "Theodora", "Theresa", "Therese", "Theresia", "Thora", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany", "Tina", "Tomasa", "Tracy", "Tressa", "Tressie", "Treva", "Trinity", "Trisha", "Trudie", "Trycia", "Twila", "Tyra", + "Una", "Ursula", + "Vada", "Valentina", "Valentine", "Valerie", "Vallie", "Vanessa", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena", "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Verna", "Vernice", "Vernie", "Verona", "Veronica", "Vesta", "Vicenta", "Vickie", "Vicky", "Victoria", "Vida", "Vilma", "Vincenza", "Viola", "Violet", "Violette", "Virgie", "Virginia", "Virginie", "Vita", "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", + "Wanda", "Wava", "Wendy", "Whitney", "Wilhelmine", "Willa", "Willie", "Willow", "Wilma", "Winifred", "Winnifred", "Winona", + "Xiu-Mei", "Xio", + "Yadira", "Yasmeen", "Yasmin", "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette", "Yvonne", + "Zaria", "Zelda", "Zella", "Zelma", "Zena", "Zetta", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola", "Zora", "Zula", +} + +var firstNames = append(firstNamesMale, firstNamesFemale...) + +var lastNames = []string{ + "Abbott", "Abernathy", "Abshire", "Adams", "Altenwerth", "Anderson", "Ankunding", "Armstrong", "Auer", "Aufderhar", + "Bahringer", "Bailey", "Balistreri", "Barrows", "Bartell", "Bartoletti", "Barton", "Bashirian", "Batz", "Bauch", "Baumbach", "Bayer", "Beahan", "Beatty", "Bechtelar", "Becker", "Bednar", "Beer", "Beier", "Berge", "Bergnaum", "Bergstrom", "Bernhard", "Bernier", "Bins", "Blanda", "Blick", "Block", "Bode", "Boehm", "Bogan", "Bogisich", "Borer", "Bosco", "Botsford", "Boyer", "Boyle", "Bradtke", "Brakus", "Braun", "Breitenberg", "Brekke", "Brown", "Bruen", "Buckridge", + "Carroll", "Carter", "Cartwright", "Casper", "Cassin", "Champlin", "Christiansen", "Cole", "Collier", "Collins", "Conn", "Connelly", "Conroy", "Considine", "Corkery", "Cormier", "Corwin", "Cremin", "Crist", "Crona", "Cronin", "Crooks", "Cruickshank", "Cummerata", "Cummings", + "Dach", "D'Amore", "Daniel", "Dare", "Daugherty", "Davis", "Deckow", "Denesik", "Dibbert", "Dickens", "Dicki", "Dickinson", "Dietrich", "Donnelly", "Dooley", "Douglas", "Doyle", "DuBuque", "Durgan", + "Ebert", "Effertz", "Eichmann", "Emard", "Emmerich", "Erdman", "Ernser", "Fadel", + "Fahey", "Farrell", "Fay", "Feeney", "Feest", "Feil", "Ferry", "Fisher", "Flatley", "Frami", "Franecki", "Friesen", "Fritsch", "Funk", + "Gaylord", "Gerhold", "Gerlach", "Gibson", "Gislason", "Gleason", "Gleichner", "Glover", "Goldner", "Goodwin", "Gorczany", "Gottlieb", "Goyette", "Grady", "Graham", "Grant", "Green", "Greenfelder", "Greenholt", "Grimes", "Gulgowski", "Gusikowski", "Gutkowski", "Gutmann", + "Haag", "Hackett", "Hagenes", "Hahn", "Haley", "Halvorson", "Hamill", "Hammes", "Hand", "Hane", "Hansen", "Harber", "Harris", "Hartmann", "Harvey", "Hauck", "Hayes", "Heaney", "Heathcote", "Hegmann", "Heidenreich", "Heller", "Herman", "Hermann", "Hermiston", "Herzog", "Hessel", "Hettinger", "Hickle", "Hilll", "Hills", "Hilpert", "Hintz", "Hirthe", "Hodkiewicz", "Hoeger", "Homenick", "Hoppe", "Howe", "Howell", "Hudson", "Huel", "Huels", "Hyatt", + "Jacobi", "Jacobs", "Jacobson", "Jakubowski", "Jaskolski", "Jast", "Jenkins", "Jerde", "Johns", "Johnson", "Johnston", "Jones", + "Kassulke", "Kautzer", "Keebler", "Keeling", "Kemmer", "Kerluke", "Kertzmann", "Kessler", "Kiehn", "Kihn", "Kilback", "King", "Kirlin", "Klein", "Kling", "Klocko", "Koch", "Koelpin", "Koepp", "Kohler", "Konopelski", "Koss", "Kovacek", "Kozey", "Krajcik", "Kreiger", "Kris", "Kshlerin", "Kub", "Kuhic", "Kuhlman", "Kuhn", "Kulas", "Kunde", "Kunze", "Kuphal", "Kutch", "Kuvalis", + "Labadie", "Lakin", "Lang", "Langosh", "Langworth", "Larkin", "Larson", "Leannon", "Lebsack", "Ledner", "Leffler", "Legros", "Lehner", "Lemke", "Lesch", "Leuschke", "Lind", "Lindgren", "Littel", "Little", "Lockman", "Lowe", "Lubowitz", "Lueilwitz", "Luettgen", "Lynch", + "Macejkovic", "Maggio", "Mann", "Mante", "Marks", "Marquardt", "Marvin", "Mayer", "Mayert", "McClure", "McCullough", "McDermott", "McGlynn", "McKenzie", "McLaughlin", "Medhurst", "Mertz", "Metz", "Miller", "Mills", "Mitchell", "Moen", "Mohr", "Monahan", "Moore", "Morar", "Morissette", "Mosciski", "Mraz", "Mueller", "Muller", "Murazik", "Murphy", "Murray", + "Nader", "Nicolas", "Nienow", "Nikolaus", "Nitzsche", "Nolan", + "Oberbrunner", "O'Connell", "O'Conner", "O'Hara", "O'Keefe", "O'Kon", "Okuneva", "Olson", "Ondricka", "O'Reilly", "Orn", "Ortiz", "Osinski", + "Pacocha", "Padberg", "Pagac", "Parisian", "Parker", "Paucek", "Pfannerstill", "Pfeffer", "Pollich", "Pouros", "Powlowski", "Predovic", "Price", "Prohaska", "Prosacco", "Purdy", + "Quigley", "Quitzon", + "Rath", "Ratke", "Rau", "Raynor", "Reichel", "Reichert", "Reilly", "Reinger", "Rempel", "Renner", "Reynolds", "Rice", "Rippin", "Ritchie", "Robel", "Roberts", "Rodriguez", "Rogahn", "Rohan", "Rolfson", "Romaguera", "Roob", "Rosenbaum", "Rowe", "Ruecker", "Runolfsdottir", "Runolfsson", "Runte", "Russel", "Rutherford", "Ryan", "Sanford", "Satterfield", "Sauer", "Sawayn", + "Schaden", "Schaefer", "Schamberger", "Schiller", "Schimmel", "Schinner", "Schmeler", "Schmidt", "Schmitt", "Schneider", "Schoen", "Schowalter", "Schroeder", "Schulist", "Schultz", "Schumm", "Schuppe", "Schuster", "Senger", "Shanahan", "Shields", "Simonis", "Sipes", "Skiles", "Smith", "Smitham", "Spencer", "Spinka", "Sporer", "Stamm", "Stanton", "Stark", "Stehr", "Steuber", "Stiedemann", "Stokes", "Stoltenberg", "Stracke", "Streich", "Stroman", "Strosin", "Swaniawski", "Swift", + "Terry", "Thiel", "Thompson", "Tillman", "Torp", "Torphy", "Towne", "Toy", "Trantow", "Tremblay", "Treutel", "Tromp", "Turcotte", "Turner", + "Ullrich", "Upton", "Vandervort", "Veum", "Volkman", "Von", "VonRueden", "Waelchi", "Walker", "Walsh", "Walter", "Ward", "Waters", "Watsica", "Weber", "Wehner", "Weimann", "Weissnat", "Welch", "West", "White", "Wiegand", "Wilderman", "Wilkinson", "Will", "Williamson", "Willms", "Windler", "Wintheiser", "Wisoky", "Wisozk", "Witting", "Wiza", "Wolf", "Wolff", "Wuckert", "Wunsch", "Wyman", + "Yost", "Yundt", "Zboncak", "Zemlak", "Ziemann", "Zieme", "Zulauf", +} + +var randNameFlag int + +var genders = []string{"Male", "Female", "Prefer to skip"} + +var chineseFirstNames = []string{ + "赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许", + "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", + "云", "苏", "潘", "葛", "奚", "范", "彭", "郎", "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", + "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷", "罗", "毕", "郝", "邬", "安", "常", + "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和", "穆", "萧", "尹", + "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", + "熊", "纪", "舒", "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季", "麻", "强", "贾", "路", "娄", "危", + "江", "童", "颜", "郭", "梅", "盛", "林", "刁", "钟", "徐", "邱", "骆", "高", "夏", "蔡", "田", "樊", "胡", "凌", "霍", + "虞", "万", "支", "柯", "昝", "管", "卢", "莫", "经", "房", "裘", "缪", "干", "解", "应", "宗", "丁", "宣", "贲", "邓", + "郁", "单", "杭", "洪", "包", "诸", "左", "石", "崔", "吉", "钮", "龚", "程", "嵇", "邢", "滑", "裴", "陆", "荣", "翁", + "荀", "羊", "於", "惠", "甄", "麴", "家", "封", "芮", "羿", "储", "靳", "汲", "邴", "糜", "松", "井", "段", "富", "巫", + "乌", "焦", "巴", "弓", "牧", "隗", "山", "谷", "车", "侯", "宓", "蓬", "全", "郗", "班", "仰", "秋", "仲", "伊", "宫", + "宁", "仇", "栾", "暴", "甘", "钭", "厉", "戎", "祖", "武", "符", "刘", "景", "詹", "束", "龙", "叶", "幸", "司", "韶", + "郜", "黎", "蓟", "薄", "印", "宿", "白", "怀", "蒲", "邰", "从", "鄂", "索", "咸", "籍", "赖", "卓", "蔺", "屠", "蒙", + "池", "乔", "阴", "郁", "胥", "能", "苍", "双", "闻", "莘", "党", "翟", "谭", "贡", "劳", "逄", "姬", "申", "扶", "堵", + "冉", "宰", "郦", "雍", "舄", "璩", "桑", "桂", "濮", "牛", "寿", "通", "边", "扈", "燕", "冀", "郏", "浦", "尚", "农", + "温", "别", "庄", "晏", "柴", "瞿", "阎", "充", "慕", "连", "茹", "习", "宦", "艾", "鱼", "容", "向", "古", "易", "慎", + "戈", "廖", "庾", "终", "暨", "居", "衡", "步", "都", "耿", "满", "弘", "匡", "国", "文", "寇", "广", "禄", "阙", "东", + "殴", "殳", "沃", "利", "蔚", "越", "夔", "隆", "师", "巩", "厍", "聂", "晁", "勾", "敖", "融", "冷", "訾", "辛", "阚", + "那", "简", "饶", "空", "曾", "毋", "沙", "乜", "养", "鞠", "须", "丰", "巢", "关", "蒯", "相", "查", "後", "荆", "红", + "游", "竺", "权", "逯", "盖", "益", "桓", "公", "司马", "上官", "欧阳", "夏侯", "诸葛", +} + +var chineseLastNames = []string{ + "澄邈", "德泽", "海超", "海阳", "海荣", "海逸", "海昌", "瀚钰", "瀚文", "涵亮", "涵煦", "明宇", + "涵衍", "浩皛", "浩波", "浩博", "浩初", "浩宕", "浩歌", "浩广", "浩邈", "浩气", "浩思", "浩言", + "鸿宝", "鸿波", "鸿博", "鸿才", "鸿畅", "鸿畴", "鸿达", "鸿德", "鸿飞", "鸿风", "鸿福", "鸿光", + "鸿晖", "鸿朗", "鸿文", "鸿轩", "鸿煊", "鸿骞", "鸿远", "鸿云", "鸿哲", "鸿祯", "鸿志", "鸿卓", + "嘉澍", "光济", "澎湃", "彭泽", "鹏池", "鹏海", "浦和", "浦泽", "瑞渊", "越泽", "博耘", "德运", + "辰宇", "辰皓", "辰钊", "辰铭", "辰锟", "辰阳", "辰韦", "辰良", "辰沛", "晨轩", "晨涛", "晨濡", + "晨潍", "鸿振", "吉星", "铭晨", "起运", "运凡", "运凯", "运鹏", "运浩", "运诚", "运良", "运鸿", + "运锋", "运盛", "运升", "运杰", "运珧", "运骏", "运凯", "运乾", "维运", "运晟", "运莱", "运华", + "耘豪", "星爵", "星腾", "星睿", "星泽", "星鹏", "星然", "震轩", "震博", "康震", "震博", "振强", + "振博", "振华", "振锐", "振凯", "振海", "振国", "振平", "昂然", "昂雄", "昂杰", "昂熙", "昌勋", + "昌盛", "昌淼", "昌茂", "昌黎", "昌燎", "昌翰", "晨朗", "德明", "德昌", "德曜", "范明", "飞昂", + "高旻", "晗日", "昊然", "昊天", "昊苍", "昊英", "昊宇", "昊嘉", "昊明", "昊伟", "昊硕", "昊磊", + "昊东", "鸿晖", "鸿朗", "华晖", "金鹏", "晋鹏", "敬曦", "景明", "景天", "景浩", "俊晖", "君昊", + "昆锐", "昆卉", "昆峰", "昆颉", "昆谊", "昆皓", "昆鹏", "昆明", "昆杰", "昆雄", "昆纶", "鹏涛", + "依秋", "依波", "香巧", "紫萱", "涵易", "忆之", "幻巧", "美倩", "安寒", "白亦", "惜玉", "碧春", + "怜雪", "听南", "念蕾", "紫夏", "凌旋", "芷梦", "凌寒", "梦竹", "千凡", "丹蓉", "慧贞", "思菱", + "平卉", "笑柳", "雪卉", "南蓉", "谷梦", "巧兰", "绿蝶", "飞荷", "佳蕊", "芷荷", "怀瑶", "慕易", + "若芹", "紫安", "曼冬", "寻巧", "雅昕", "尔槐", "以旋", "初夏", "依丝", "怜南", "傲菡", "谷蕊", + "笑槐", "飞兰", "笑卉", "迎荷", "佳音", "梦君", "妙绿", "觅雪", "寒安", "沛凝", "白容", "乐蓉", + "映安", "依云", "映冬", "凡雁", "梦秋", "梦凡", "秋巧", "若云", "元容", "怀蕾", "灵寒", "天薇", + "翠安", "乐琴", "宛南", "怀蕊", "白风", "访波", "亦凝", "易绿", "夜南", "曼凡", "亦巧", "青易", + "冰真", "白萱", "友安", "海之", "小蕊", "又琴", "天风", "若松", "盼菡", "秋荷", "香彤", "语梦", + "惜蕊", "迎彤", "沛白", "雁彬", "易蓉", "雪晴", "诗珊", "春冬", "晴钰", "冰绿", "半梅", "笑容", + "沛凝", "映秋", "盼烟", "晓凡", "涵雁", "问凝", "冬萱", "晓山", "雁蓉", "梦蕊", "山菡", "南莲", + "飞双", "凝丝", "思萱", "怀梦", "雨梅", "冷霜", "向松", "迎丝", "迎梅", "雅彤", "香薇", "以山", + "碧萱", "寒云", "向南", "书雁", "怀薇", "思菱", "忆文", "翠巧", "书文", "若山", "向秋", "凡白", + "绮烟", "从蕾", "天曼", "又亦", "从语", "绮彤", "之玉", "凡梅", "依琴", "沛槐", "又槐", "元绿", +} + +var russianFirstNamesMale = []string{ + "Авдей", "Авксентий", "Агафон", "Акакий", "Александр", "Алексей", "Альберт", "Альвиан", "Анатолий", "Андрей", "Аникита", + "Антон", "Антонин", "Анфим", "Аристарх", "Аркадий", "Арсений", "Артём", "Артемий", "Артур", "Архипп", "Афанасий", "Богдан", + "Борис", "Вавила", "Вадим", "Валентин", "Валерий", "Валерьян", "Варлам", "Варсонофий", "Варфоломей", "Василий", "Венедикт", + "Вениамин", "Викентий", "Виктор", "Виссарион", "Виталий", "Владимир", "Владислав", "Владлен", "Влас", "Всеволод", + "Вячеслав", "Гавриил", "Галактион", "Геласий", "Геннадий", "Георгий", "Герасим", "Герман", "Германн", "Глеб", "Гордей", + "Григорий", "Данакт", "Даниил", "Демид", "Демьян", "Денис", "Дмитрий", "Добрыня", "Донат", "Дорофей", "Евгений", + "Евграф", "Евдоким", "Евсей", "Евстафий", "Егор", "Емельян", "Еремей", "Ермолай", "Ерофей", "Ефим", "Ефрем", "Ждан", + "Зиновий", "Иакинф", "Иван", "Игнатий", "Игорь", "Илья", "Иннокентий", "Ираклий", "Ириней", "Исидор", "Иуда", "Иулиан", + "Капитон", "Ким", "Кир", "Кирилл", "Климент", "Кондрат", "Конон", "Константин", "Корнилий", "Кузьма", "Куприян", + "Лаврентий", "Лев", "Леонид", "Леонтий", "Логгин", "Лука", "Лукий", "Лукьян", "Магистриан", "Макар", "Максим", "Марк", + "Мартын", "Матвей", "Мелентий", "Мина", "Мирон", "Мирослав", "Митрофан", "Михаил", "Мстислав", "Назар", "Нестор", + "Никанор", "Никита", "Никифор", "Никодим", "Николай", "Никон", "Олег", "Онисим", "Онуфрий", "Павел", "Паисий", "Панкратий", + "Пантелеймон", "Парфений", "Пафнутий", "Пахомий", "Пётр", "Платон", "Поликарп", "Порфирий", "Потап", "Пров", "Прокопий", + "Протасий", "Прохор", "Родион", "Родослав", "Роман", "Ростислав", "Руслан", "Савва", "Савелий", "Самуил", "Святополк", + "Святослав", "Севастьян", "Семён", "Серафим", "Сергей", "Сила", "Сильвестр", "Созон", "Софрон", "Спиридон", "Станислав", + "Степан", "Тарас", "Тимофей", "Тимур", "Тит", "Тихон", "Трифон", "Трофим", "Фаддей", "Фёдор", "Федосей", "Федот", "Феликс", + "Феоктист", "Филат", "Филимон", "Филипп", "Фирс", "Фока", "Фома", "Фотий", "Фрол", "Харитон", "Хрисанф", "Христофор", + "Эдуард", "Эраст", "Юлиан", "Юрий", "Юстин", "Яков", "Якун", "Ярослав", "Иосиф", +} + +var russianMiddleNamesMale = []string{ + "Авдеевич", "Авксентиевич", "Агафонович", "Акакиевич", "Александрович", "Алексеевич", "Альбертович", "Альвианович", "Анатольевич", "Андреевич", "Аникитич", + "Антонович", "Антонинович", "Анфимович", "Аристархович", "Аркадьевич", "Арсеньевич", "Артёмович", "Артемьевич", "Артурович", "Архипович", "Афанасьевич", "Богданович", + "Борисович", "Вавилович", "Вадимович", "Валентинович", "Валерьевич", "Валерьянович", "Варламович", "Варсонофиевич", "Варфоломеевич", "Васильевич", "Венедиктович", + "Вениаминович", "Викентьевич", "Викторович", "Виссарионович", "Витальевич", "Владимирович", "Владиславович", "Владленович", "Власович", "Всеволодович", + "Вячеславович", "Гавриилович", "Галактионович", "Геласиевич", "Геннадьевич", "Георгиевич", "Герасимович", "Германович", "Глебович", "Гордеевич", + "Григорьевич", "Данактович", "Даниилович", "Демидович", "Демьянович", "Денисович", "Дмитриевич", "Добрынич", "Донатович", "Дорофеевич", "Евгеньевич", + "Евграфович", "Евдокимович", "Евсеевич", "Евстафьевич", "Егорович", "Емельянович", "Еремеевич", "Ермолаевич", "Ерофеевич", "Ефимович", "Ефремович", "Жданович", + "Зиновьевич", "Иакинфович", "Иванович", "Игнатович", "Игоревич", "Ильич", "Иннокентьевич", "Ираклиевич", "Иринеевич", "Исидорович", "Иудич", "Иулианович", + "Капитонович", "Кимович", "Кирович", "Кириллович", "Климентович", "Кондратович", "Кононович", "Константинович", "Корнилиевич", "Кузьмич", "Куприянович", + "Лаврентиевич", "Львович", "Леонидович", "Леонтьевич", "Логгинович", "Лукич", "Лукиевич", "Лукьянович", "Магистрианович", "Макарович", "Максимович", "Маркович", + "Мартынович", "Матвеевич", "Мелентиевич", "Минич", "Миронович", "Мирославович", "Митрофанович", "Михайлович", "Мстиславович", "Назарович", "Несторович", + "Никанорович", "Никитич", "Никифорович", "Никодимович", "Николаевич", "Никонович", "Олегович", "Онисимович", "Онуфриевич", "Павлович", "Паисиевич", "Панкратиевич", + "Пантелеймонович", "Парфеньевич", "Пафнутиевич", "Пахомиевич", "Петрович", "Платонович", "Поликарпович", "Порфирьевич", "Потапович", "Прович", "Прокопьевич", + "Протасиевич", "Прохорович", "Родионович", "Родославович", "Романович", "Ростиславович", "Русланович", "Саввич", "Савельевич", "Самуилович", "Святополкович", + "Святославович", "Севастьянович", "Семёнович", "Серафимович", "Сергеевич", "Силыч", "Сильвестрович", "Созонович", "Софронович", "Спиридонович", "Станиславович", + "Степанович", "Тарасович", "Тимофеевич", "Тимурович", "Титович", "Тихонович", "Трифонович", "Трофимович", "Фаддеевич", "Фёдорович", "Федосеевич", "Федотович", "Феликсович", + "Феоктистович", "Филатович", "Филимонович", "Филиппович", "Фирсович", "Фокич", "Фомич", "Фотичевич", "Фролович", "Харитонович", "Хрисанович", "Христофорович", + "Эдуардович", "Эрастович", "Юлианович", "Юрьевич", "Юстинович", "Яковлевич", "Якунович", "Ярославович", "Иосифович", +} + +var russianLastNamesMale = []string{ + "Абакумов", "Абдуллаев", "Абрамов", "Абрикосов", "Абросимов", "Абузяров", "Авакумов", "Аввакум", "Авдеев", "Авдеенко", + "Авдиев", "Авен", "Аверкиев", "Аверков", "Аверченко", "Авилин", "Авилов", "Авксентьев", "Аврамов", "Авсеев", "Авченко", + "Агапеев", "Агапов", "Агапьев", "Агафонов", "Агеев", "Агутин", "Адамович", "Адрианов", "Ажаев", "Азаров", "Азарьев", + "Азарьин", "Азольский", "Айзман", "Айтматов", "Акатов", "Акатьев", "Акбулатов", "Акимов", "Акиндинов", "Акинфиев", + "Акинфов", "Аксенов", "Аксентьев", "Аксёнов", "Акулин", "Акулов", "Алданов", "Алейников", "Александров", "Алексеев", + "Алексиевич", "Алексин", "Алехин", "Алешковский", "Алимпиев", "Алипов", "Алипьев", "Алисов", "Алпатов", "Алтухов", + "Алферьев", "Алфимов", "Алфёров", "Алябьев", "Амарантов", "Амвросов", "Амвросьев", "Аммосов", "Амосов", "Амфитеатров", + "Ананьев", "Ананьин", "Анастасов", "Анастасьев", "Андреев", "Андрианов", "Андроников", "Андронов", "Андропов", + "Андрусов", "Анемподистов", "Аникеев", "Анисимов", "Анискин", "Анкидинов", "Анкудинов", "Анненков", "Аннинский", + "Антипин", "Антипов", "Антипьев", "Антонов", "Антоньев", "Ануров", "Анурьев", "Анфимов", "Анхимов", "Анцыферов", + "Анчаров", "Анюков", "Апарин", "Арабов", "Арановский", "Арбатов", "Арбитман", "Арбузов", "Ардалионов", "Аренский", + "Арепьев", "Арефин", "Арефов", "Арефьев", "Аристархов", "Аристов", "Аркадов", "Аркадьев", "Аркадьин", "Арро", "Арсенов", + "Арсеньев", "Артамонов", "Артемьев", "Артёмов", "Архангельский", "Архипов", "Архипьев", "Арцыбашев", "Арцыбушев", + "Асафов", "Асафьев", "Асеев", "Астапов", "Астафьев", "Астахов", "Асташин", "Аствацатуров", "Атаманов", "Афанасов", + "Афанасьев", "Афлатуни", "Афремов", "Африканов", "Африкантов", "Афросимов", "Ахадов", "Ахмедов", "Бабаевский", + "Бабаченко", "Бабель", "Бабиков", "Бабуров", "Бабченко", "Бавильский", "Багиров", "Багринцев", "Багрянцев", "Бажов", + "Байбородин", "Бакланов", "Бакунин", "Балдин", "Балков", "Банников", "Банщиков", "Баранов", "Бартенев", "Басинский", + "Баскаков", "Басманов", "Басыров", "Бацкалевич", "Бачило", "Безбатько", "Бездетко", "Беззубенко", "Безрученко", + "Безручко", "Белезянский", "Беленко", "Беленький", "Белинский", "Белобоцкий", "Белобровко", "Белов", "Белозеров", + "Белозёров", "Белоиван", "Белокуров", "Беломлинский", "Белоножко", "Белооченко", "Белоруков", "Белорусец", "Белоусов", + "Белошапко", "Белый", "Белых", "Беляев", "Беляков", "Белянкин", "Бенедиктов", "Бенигсен", "Березин", "Березовский", + "Берестов", "Берсенев", "Берсенёв", "Берёза", "Берёзин", "Беседин", "Беспаленко", "Беспалов", "Беспалько", "Беспутин", + "Бессараб", "Бестужев", "Марлинский", "Бианки", "Бирюков", "Битов", "Блинов", "Блок", "Блохин", "Бобков", "Боборыкин", + "Бобров", "Бобылёв", "Богатченко", "Богданов", "Богданович", "Боголюбский", "Богомолов", "Богомяков", "Богословский", + "Богоявленский", "Богуславский", "Бодров", "Бодылев", "Боженко", "Бойко", "Болмат", "Болотов", "Болтышев", "Болучевский", + "Большаков", "Бондарев", "Бондарь", "Борисенко", "Борисов", "Борищенко", "Бормор", "Борн", "Боровой", "Бородин", + "Бортников", "Борцов", "Босов", "Боченков", "Бочков", "Бочоришвили", "Бояндин", "Боярский", "Бояшов", "Брагин", "Брасс", + "Брежнев", "Брешковский", "Бровцев", "Бродский", "Бруштейн", "Брюсов", "Бугрименко", "Бузин", "Буйда", "Букша", "Булатов", + "Булгаков", "Булганин", "Булгарин", "Булочников", "Булычев", "Бундур", "Бунин", "Буняченко", "Бураченко", "Буркатовский", + "Бурмистров", "Буров", "Буровский", "Буряченко", "Бутин", "Бутов", "Буторин", "Бушин", "Быков", "Быченко", "Бычков", + "Вавилин", "Вавилов", "Вайман", "Вайнеры", "Вайсбеккер", "Вакуленко", "Вакулин", "Вакулов", "Валентинов", "Валетов", + "Варавва", "Варламов", "Варнавин", "Варченко", "Варшавский", "Васечкин", "Васечко", "Василев", "Василенко", "Василов", + "Васильев", "Васильевич", "Васькин", "Васюченко", "Вахтин", "Веденский", "Веллер", "Вельтман", "Веневитинов", + "Венедиктов", "Вепрев", "Верзилов", "Веркин", "Верников", "Вершинин", "Веселов", "Веселый", "Ветров", "Визбор", + "Викентьев", "Виккерс", "Викторов", "Вильмонт", "Виноградов", "Винтилов", "Вирхов", "Витковский", "Витушев", "Витязев", + "Вихров", "Вишневский", "Вишняков", "Владимиров", "Владимирский", "Владимов", "Власов", "Власьев", "Внифатьев", + "Вовчок", "Воддеников", "Водолазкин", "Войнов", "Войнович", "Волков", "Володарский", "Володихин", "Волос", "Волочков", + "Вонифатов", "Вонифатьев", "Воробьев", "Воробьёв", "Воронов", "Воронцов", "Воротников", "Воскобойников", "Востряков", + "Вотрин", "Всеволожский", "Вяземский", "Габышев", "Гаврилин", "Гаврилов", "Гагарин", "Газданов", "Гай", "Гайдар", + "Гайдук", "Галактионов", "Галкин", "Галковский", "Галктионов", "Гальего", "Гальцов", "Гаммер", "Гандлевский", "Ганиев", + "Ганичев", "Гарасимов", "Гаррос", "Гатапов", "Гедеонов", "Геласимов", "Геннадиев", "Геогиевский", "Герасимов", + "Гераскин", "Геращенко", "Герман", "Германов", "Гермогенов", "Герцен", "Гершанов", "Гиваргизов", "Гиляровский", + "Гиршович", "Гладилин", "Гладков", "Гладышев", "Глинка", "Глуховский", "Глушик", "Гляделкин", "Гнатюк", "Гнедич", + "Гнилорыбов", "Гоголь", "Гогуа", "Голиков", "Головачёв", "Голофтеев", "Голубев", "Голунов", "Гомзиков", "Гончаров", + "Горалик", "Горбачёв", "Горбунов", "Гордеев", "Горелов", "Горенштейн", "Горланов", "Горлов", "Горчев", "Горшков", + "Горький", "Гостев", "Гранин", "Графинин", "Гребенщиков", "Гриб", "Грибанов", "Григоров", "Григорович", "Григорьев", + "Грин", "Гришин", "Гришковец", "Грозный", "Громов", "Гроссман", "Грунин", "Грязев", "Губерман", "Гуляев", "Гумилёв", + "Гуревич", "Гурский", "Гурьев", "Гусев", "Гусельников", "Гутенёв", "Гуцко", "Гущин", "Давыдов", "Далин", "Далматов", + "Даль", "Данилин", "Данилкин", "Данилов", "Данильчук", "Данихнов", "Даниэль", "Данов", "Даньков", "Дашкевич", "Дашков", + "Девяткин", "Дегтев", "Дедов", "Деев", "Дежнев", "Дежнёв", "Дементьев", "Демидов", "Денежкин", "Денисенко", "Денисов", + "Денисьев", "Деревенский", "Дзержинский", "Дижур", "Диксон", "Димитриев", "Дмитриев", "Дмитрук", "Добродеев", + "Добролюбов", "Доброхотов", "Добычин", "Довлатов", "Додолев", "Долгих", "Долгопят", "Долженко", "Долин", "Долинский", + "Долиняк", "Долотин", "Домбровский", "Домников", "Донецкий", "Донцов", "Доримедонтов", "Дормедонтов", "Дормидонтов", + "Доронин", "Дорофеев", "Дорошенко", "Достоевский", "Драгунский", "Дракохурст", "Дриянский", "Дроздов", "Дружаев", + "Дружинин", "Дружников", "Дубаев", "Дубин", "Дубинин", "Дубинянский", "Дубов", "Дудин", "Дудинцев", "Дышев", "Дьяконов", + "Дьячков", "Дёготь", "Дёмушкин", "Евгенов", "Евгеньев", "Евдокимов", "Евлампиев", "Евменов", "Евменьев", "Евплов", + "Евсеев", "Евстафьев", "Евстигнеев", "Евстифеев", "Евстратов", "Евсюков", "Евтифеев", "Евтихеев", "Евтушенко", "Егоров", + "Егорьев", "Ежов", "Екимов", "Елагин", "Еланцев", "Елеазаров", "Елеферьев", "Елизаров", "Елизарьев", "Елисеев", "Елфимов", + "Ельчин", "Ельшин", "Емельянов", "Емец", "Ененко", "Епенетов", "Епимахов", "Епинетов", "Епифанов", "Епифаньев", "Ерастов", + "Еремеев", "Ермаков", "Ермилин", "Ермилов", "Ермошин", "Ерофеев", "Ерошкин", "Ершов", "Ерёмин", "Есенин", "Есин", "Есипов", + "Естамонов", "Ефимов", "Ефимьев", "Ефремов", "Ефросинов", "Ешкилев", "Жаринов", "Жарковский", "Жбанов", "Жвалевский", + "Жвалов", "Жданов", "Жемчужников", "Жеребцов", "Жерихов", "Живаго", "Живетьев", "Жириновский", "Житинский", "Житков", + "Жук", "Жуков", "Жуковский", "Жуликов", "Жулин", "Журавлёв", "Журавский", "Заболотских", "Заболоцкий", "Заборов", + "Заволокин", "Загорцев", "Задорнов", "Задоров", "Зайончковский", "Зайцев", "Зализняк", "Залотуха", "Залыгин", "Замуткин", + "Замыслов", "Замятин", "Заостровцев", "Заплетин", "Зарубин", "Затворник", "Захаров", "Захарьев", "Захарьин", "Збруев", + "Зверев", "Звоницкий", "Звягин", "Зеленин", "Земляной", "Земсков", "Зиганшин", "Зикунов", "Зимин", "Зиновьев", + "Златовратский", "Златогорский", "Златоустский", "Знаменский", "Золотцев", "Золотько", "Зондберг", "Зонис", "Зорин", + "Зорич", "Зосимов", "Зотеев", "Зотов", "Зотьев", "Зощенко", "Зудин", "Зуев", "Зыкин", "Зыков", "Зюганов", "Зюзюкин", + "Зябликов", "Ивакин", "Иваницкий", "Иванкин", "Иванов", "Иванченко", "Ивлев", "Ивонин", "Ивонов", "Игнатов", "Игнатьев", + "Игнашев", "Игумнов", "Идиатуллин", "Идов", "Иевлев", "Иженяков", "Измайлов", "Изосимов", "Изотов", "Иличевский", + "Ильенков", "Ильин", "Ильницкий", "Инин", "Иовлев", "Ионин", "Ионов", "Ипатов", "Ипатьев", "Ипполитов", "Иринеев", + "Исаев", "Исаин", "Исаков", "Искандер", "Кабаков", "Кабанов", "Каверин", "Каганов", "Казакевич", "Казаков", "Казанцев", + "Казимиров", "Казинцев", "Калашников", "Каледин", "Калинин", "Каминов", "Каминский", "Камша", "Канаев", "Кандауров", + "Кандель", "Каневский", "Канович", "Кантор", "Капитонов", "Каплан", "Капнист", "Капустин", "Карабанов", "Карагодин", + "Карамзин", "Карасев", "Карасёв", "Караулов", "Каренин", "Карив", "Карионов", "Карлов", "Карпеев", "Карпенков", "Карпов", + "Картофельников", "Каруселин", "Касимов", "Кассиль", "Катаев", "Катерли", "Катишонок", "Катков", "Кац", "Кашафутдинов", + "Кашин", "Каштанов", "Квартальнов", "Кедрин", "Кенжеев", "Кердан", "Кетро", "Киктенко", "Ким", "Киприанов", "Кириков", + "Кирилин", "Кириллов", "Кирилов", "Киркиж", "Киров", "Кирпиченко", "Кирсанов", "Киселёв", "Кисин", "Кислицын", "Китов", + "Клеников", "Клеопин", "Клеопов", "Клепиков", "Клепов", "Клех", "Климентов", "Климентьев", "Клюев", "Кнабенгоф", "Князев", + "Кобах", "Кобзев", "Кобрин", "Ковалев", "Коваленко", "Коваль", "Ковальджи", "Ковалёв", "Ковшов", "Кожевников", "Козел", + "Козлачков", "Козлов", "Козырев", "Козьмин", "Коклюшкин", "Колесников", "Колин", "Колобов", "Колокольцев", "Колпакиди", + "Колпаков", "Колядин", "Комаров", "Комиссаров", "Кондратов", "Кондратьев", "Коновалов", "Кононов", "Кононыхин", + "Константинов", "Конторович", "Контровский", "Конюков", "Конюшевский", "Коняев", "Копелев", "Копылов", "Корабальников", + "Корецкий", "Коржавин", "Коркищенко", "Кормильцев", "Корнилов", "Корнильев", "Коровин", "Королев", "Короленко", + "Королюк", "Королёв", "Коростелёв", "Корчагин", "Корявин", "Косник", "Косой", "Костин", "Косьмин", "Котляревский", + "Котов", "Котовский", "Кофанов", "Кох", "Кочергин", "Кошелев", "Кошелёв", "Кравченко", "Крамаренко", "Крапивин", + "Красильников", "Красник", "Кривомазов", "Кривцов", "Кругосветов", "Круз", "Крупин", "Крупник", "Крупнов", "Крусанов", + "Крутихин", "Кручёных", "Крылов", "Крюков", "Крячко", "Куваев", "Кувалдин", "Кудинов", "Кудрявцев", "Кудряшов", + "Кузечкин", "Кузиков", "Кузнецов", "Кузьмин", "Кулагин", "Кулаков", "Куликов", "Купреянов", "Куприн", "Купряшин", + "Куратов", "Курилов", "Курков", "Курочкин", "Курчаткин", "Кучерский", "Лаврентьев", "Лаврин", "Лавров", "Лагин", + "Лагунов", "Лазарев", "Лайдон", "Лактионов", "Ланьков", "Лапин", "Лапицкий", "Лапутин", "Ларионов", "Латынин", "Лахтионов", + "Лебедев", "Лебедь", "Леванидов", "Левин", "Левитас", "Левитин", "Левонов", "Левонтьев", "Леонидов", "Леонов", + "Леонтьев", "Лепёхин", "Лермонтов", "Лесин", "Лесков", "Ливадный", "Ливанов", "Ливри", "Лигачёв", "Лидский", "Лимонов", + "Липатов", "Липкин", "Липовецкий", "Липскеров", "Листьев", "Литаврин", "Литвинов", "Лиханов", "Лихачёв", "Личутин", + "Лобанов", "Лобков", "Ловчиков", "Логинов", "Ложкомоев", "Лойко", "Ломакин", "Ломов", "Ломоносов", "Лорченков", + "Лоскутов", "Лошкомоев", "Лощиц", "Лугинов", "Лужин", "Лукин", "Лукошин", "Лукьяненко", "Лукьянов", "Лунц", "Луппов", + "Луппол", "Лутьянов", "Лыжин", "Лыткин", "Любимов", "Люкин", "Люсин", "Лялин", "Мавров", "Мазин", "Маканин", "Макаревич", + "Макаренко", "Макаров", "Макарьев", "Макин", "Максимишин", "Максимов", "Максимушкин", "Малафеев", "Малахеев", + "Малахов", "Малецкий", "Маликов", "Малинин", "Малкин", "Малышев", "Маляров", "Мамантов", "Мамедов", + "Мамлеев", "Мамонтов", "Мандельштам", "Мануйлов", "Манулкин", "Манылин", "Манылов", "Марамзин", "Маргелов", "Маринин", + "Маркелов", "Маркианов", "Марков", "Марковчин", "Мартемьянов", "Мартынов", "Мартытов", "Мартьянов", "Маршак", "Маслов", + "Матвеев", "Маханенко", "Махнач", "Машкин", "Маяковский", "Маямсин", "Маятников", "Медведев", "Медков", "Мелитонов", "Мелихов", + "Мельников", "Мень", "Мережковский", "Мерецков", "Меркулов", "Меркульев", "Меркуров", "Меркурьев", "Меркушев", + "Метлицкий", "Мигулёв", "Микитов", "Микушевич", "Милов", "Минаев", "Минин", "Мирер", "Миронов", "Мирошников", "Мисайлов", + "Митрофанов", "Митрофаньев", "Мифтахутдинов", "Михаилов", "Михайлин", "Михайлов", "Михайловский", "Михаленко", + "Михальченко", "Михеев", "Мишин", "Мишкин", "Мишнев", "Мишустин", "Могила", "Могутин", "Модестов", "Можаев", "Мозгов", + "Мозговой", "Мозжухин", "Моисеев", "Мойсеев", "Молчанов", "Монастырский", "Мордовцев", "Морковин", "Морозов", + "Морщаков", "Мосеев", "Москвин", "Моторин", "Мохнаткин", "Муравьёв", "Мурман", "Мурманенко", "Мурманец", "Мурманин", + "Мурманов", "Мурмановский", "Мурманский", "Мурманцев", "Мурманчук", "Мурманюк", "Муромский", "Мухин", "Мышкин", "Мягков", + "Мясников", "Набоков", "Навальный", "Нагибин", "Нагорный", "Надсон", "Назаров", "Назарьев", "Найман", "Нарбиков", + "Нарежный", "Нарицин", "Наседкин", "Насонов", "Наугольный", "Наумов", "Нахапетов", "Невзоров", "Негин", "Незнанский", + "Неклюдов", "Некрасов", "Немиров", "Немцов", "Немчинов", "Ненароков", "Несмеянов", "Неспанов", "Нестеров", "Нетребо", + "Нетёсов", "Нефедьев", "Нефёдов", "Нехлюдов", "Нехорошев", "Нечаев", "Никандров", "Никаноров", "Никитин", "Никифоров", + "Никодимов", "Николаев", "Николаевич", "Николаенко", "Николин", "Никонов", "Никтитин", "Никулин", "Новгородцев", + "Новиков", "Новодворский", "Новосельцев", "Новосёлов", "Норов", "Носков", "Носов", "Обросимов", "Обухов", "Овдокимов", + "Овечкин", "Овросимов", "Овсеев", "Овчинников", "Огарев", "Оглоблин", "Одинцов", "Одоевский", "Окатов", "Окулов", + "Окунев", "Олейников", "Олефир", "Олеша", "Олимпиев", "Олисов", "Олсуфьев", "Олтухов", "Олферьев", "Ольбик", "Омельчук", + "Омельянов", "Онисимов", "Опимахов", "Орехов", "Орлов", "Орловский", "Осеев", "Осинский", "Осипов", "Осокин", "Осоргин", + "Остальский", "Останин", "Остапов", "Остафьев", "Остратов", "Островский", "Офросимов", "Охотин", "Очин", "Павлинов", + "Павлов", "Павловский", "Павлюк", "Палей", "Палицин", "Пальцев", "Памфилов", "Панаев", "Панкеев", "Панкратов", + "Панкратьев", "Панов", "Пантелеев", "Панфилов", "Панфильев", "Панюшкин", "Парамонов", "Парменьев", "Пармёнов", + "Парфенчиков", "Парфеньев", "Парфёнов", "Паршов", "Парщиков", "Пасечник", "Пастернак", "Пастухов", "Патрикеев", + "Паустовский", "Паушкин", "Пафнутьев", "Пафомов", "Пахмутов", "Пахомов", "Пахомьев", "Пашков", "Пашковский", "Певзнер", + "Пелевин", "Пепперштейн", "Первушин", "Пересторин", "Пермяков", "Перумов", "Перфильев", "Перфишин", "Перхуров", + "Перхурьев", "Перцев", "Песков", "Пестов", "Петелин", "Петкевич", "Петров", "Петрушевский", "Петухов", "Пивоваров", + "Пигасов", "Пигасьев", "Пикуль", "Пильняк", "Пименов", "Писарев", "Писемский", "Питиримов", "Пишенко", "Пияшев", + "Плавильщиков", "Плакидин", "Платов", "Платонов", "Платухин", "Плотников", "Плющев", "Победоносцев", "Подгородецкий", + "Подистов", "Подколзин", "Подушков", "Позамантир", "Позгалёв", "Покровский", "Полевой", "Поливанов", "Полиевктов", + "Поликарпов", "Полоков", "Полоцкий", "Полуектов", "Полуехтов", "Полукарпов", "Полуянов", "Полуяхтов", "Поляков", + "Поляновский", "Полянский", "Померанцев", "Помяловский", "Пономарев", "Пономарёв", "Поплавский", "Попов", "Попугаев", + "Порфирьев", "Потапов", "Потапьев", "Прашкевич", "Привалов", "Пригов", "Пригожин", "Прилепин", "Приставкин", "Пришвин", + "Проклов", "Прокопивич", "Прокопов", "Прокопьев", "Прокофьев", "Пророков", "Просвирнин", "Протасов", "Протасьев", + "Протоклитов", "Проханов", "Прохоров", "Прошин", "Прудников", "Прутков", "Пудеев", "Пудов", "Пупкин", "Путин", "Пучков", + "Пушкин", "Пчёлкин", "Пьецух", "Пьянов", "Работников", "Радзинский", "Радивонов", "Радищев", "Радугин", "Развожаев", + "Раков", "Ранцов", "Распутин", "Расторгуев", "Ратников", "Рахматуллин", "Рачков", "Рекемчук", "Ремезов", "Ремизов", + "Ремнёв", "Репников", "Ржевский", "Римский", "Робски", "Рогов", "Родивонов", "Родионов", "Родченков", "Рожков", + "Розанов", "Ромазанов", "Романов", "Ростов", "Рубанов", "Рубин", "Русаков", "Рыбаков", "Рыжонок", "Рылеев", "Рыльников", + "Рысев", "Рябов", "Саблин", "Саватеев", "Саватьев", "Саввович", "Савельев", "Савин", "Савинов", "Савкин", "Савостьянов", + "Савченко", "Савёлов", "Садофов", "Садофьев", "Садулаев", "Садур", "Сажин", "Сазонов", "Сакин", "Саломатов", "Сальников", + "Самойлов", "Самсонов", "Самылин", "Самылов", "Санаев", "Сапронов", "Сапрыкин", "Сараскин", "Сафонов", "Сафронов", + "Сахарнов", "Сахновский", "Сбитнев", "Сбруев", "Светлов", "Свечин", "Свинаренко", "Свиридов", "Свитнев", "Свободных", + "Севастьянов", "Севела", "Северьянов", "Северянин", "Сегал", "Сегень", "Сейдов", "Секацкий", "Селезнёв", "Селиверстов", + "Селин", "Семенов", "Семёнов", "Сенчин", "Серафимович", "Сергеев", "Серебренников", "Серебрянский", "Серенко", "Серов", + "Сид", "Сиднин", "Сидоркин", "Сидоров", "Силин", "Симбирский", "Симеонов", "Симонов", "Синявский", "Синякин", "Ситников", + "Скапидаров", "Скатов", "Скворцов", "Скидан", "Скоренко", "Скоробогатов", "Скороходов", "Скульский", "Скуратов", + "Славин", "Славников", "Слаповский", "Слепнев", "Слепнёв", "Слепухин", "Слюньков", "Слюсаренко", "Смехов", "Смирнов", + "Смоленский", "Смолин", "Смольников", "Смородинский", "Снегирев", "Собакин", "Соболев", "Соболь", "Собчак", "Советов", + "Согрин", "Созонов", "Созонтов", "Соков", "Соколов", "Сокуров", "Солженицин", "Солнцев", "Соловьев", "Соловьёв", + "Сологуб", "Солодников", "Соломатин", "Солопов", "Сопронов", "Сорбатский", "Сорокин", "Соротокин", "Соснора", + "Сотников", "Софонов", "Софронов", "Софроньев", "Сошников", "Спивак", "Спиридонов", "Спиридоньев", "Ставецкий", + "Ставрогин", "Стариков", "Старков", "Старобинец", "Стародубцев", "Старостенко", "Старченко", "Стельмах", "Степанов", + "Степной", "Стефашин", "Стогниенко", "Стогов", "Стратоников", "Стрелков", "Стругацкие", "Субботин", "Суворов", + "Сударушкин", "Сумароков", "Супрунов", "Суров", "Суханов", "Сухилин", "Сухов", "Сысоев", "Сычев", "Сычин", "Сычёв", + "Табаков", "Табатчиков", "Таланов", "Таралов", "Тарасов", "Тарасьев", "Тарковский", "Тарн", "Тарусов", "Тархов", + "Тасбулатов", "Тендряков", "Терентьев", "Терехов", "Терешков", "Тесаков", "Тетерин", "Тимофеев", "Титов", "Титовых", + "Тиханин", "Тихомиров", "Тихон", "Тихонов", "Тованичев", "Токарев", "Токарь", "Толстой", "Толстых", "Топчиев", + "Торлопов", "Третьяков", "Трефилов", "Трефильев", "Трифонов", "Тропин", "Трофимов", "Троцкий", "Трудолюбов", + "Труфанов", "Тургенев", "Туркул", "Туров", "Туровский", "Тучков", "Тынянов", "Тюльпанов", "Тютчев", "Тёмкин", + "Уваров", "Углев", "Удалов", "Удальцов", "Удачин", "Удодов", "Улицкий", "Ульянов", "Упатов", "Успенский", "Устинов", + "Устьянов", "Уткин", "Утёсов", "Фавстов", "Фадеев", "Фалалеев", "Фандеев", "Фатеев", "Фатьянов", "Федин", "Федоров", + "Федосеев", "Федосов", "Федосьев", "Федотов", "Федотьев", "Федулеев", "Федулин", "Федулов", "Феклисов", "Фенев", + "Феоктистов", "Феонин", "Феофанов", "Феофилактов", "Феофилов", "Фетисов", "Фефилов", "Филаретов", "Филатов", + "Филатьев", "Филахтов", "Филимонихин", "Филимонов", "Филипов", "Филиппов", "Филиппьев", "Филипьев", "Филков", + "Филонов", "Философов", "Фионин", "Фирсов", "Флегонтов", "Флегонтьев", "Фокин", "Фомин", "Фомичёв", "Фонвизин", + "Фортунатов", "Фотеев", "Фотиев", "Фотьев", "Фофанов", "Фраерманн", "Фрай", "Фролов", "Фурман", "Фурманов", "Фурсов", + "Фурцев", "Фёдоров", "Хадеев", "Хаецкий", "Хазанов", "Хазин", "Харитонов", "Харламов", "Харлампиев", "Хармс", "Хаустов", + "Хемлин", "Херасков", "Хлестаков", "Хлопонин", "Хлумов", "Ходасевич", "Хохлов", "Хрисогонов", "Христофоров", + "Цветанков", "Цветков", "Цепов", "Цыганов", "Цыпкин", "Чаплин", "Чаплыгин", "Чарский", "Чарушников", "Чванов", + "Чебышёв", "Чекмаев", "Черепанов", "Черепенников", "Черкашин", "Чернев", "Чернов", "Черноусов", "Чернышев", + "Чернышевский", "Чертанов", "Черчесов", "Чехов", "Чивилихин", "Чиж", "Чижов", "Чиков", "Чипчиков", "Чирков", "Чистов", + "Чичваркин", "Чудаков", "Чудинов", "Чуковский", "Чулаки", "Чумаков", "Чуприянов", "Чурилов", "Чуров", "Шабалов", + "Шакиров", "Шаламов", "Шаликов", "Шалыганов", "Шамбаров", "Шапошников", "Шарапов", "Шаргунов", "Шаров", "Шатыренок", + "Шахмагонов", "Шашков", "Шварц", "Шевкун", "Шевцов", "Шевченко", "Шемякин", "Шепилов", "Шерстобитов", "Шестаков", + "Шестинский", "Шестков", "Шеянов", "Шилов", "Ширяев", "Шишкин", "Шишков", "Шмелев", "Шолохов", "Шпанов", "Шубин", + "Шукшин", "Шуртаков", "Шутко", "Щеглов", "Щекин", "Щекочихин", "Щелконогов", "Щепа", "Щепило", "Щепкин", "Щербаков", + "Щербин", "Щукин", "Эйсмонт", "Эмин", "Эренбург", "Юдин", "Юдов", "Юзефович", "Юппи", "Юровских", "Юрский", "Юхновский", + "Яворский", "Ягужинский", "Ядов", "Язов", "Якимов", "Яковлев", "Якушев", "Янин", "Янковский", "Янов", "Ярин", "Ярок", + "Яськов", "Яхин", +} + +var russianFirstNamesFemale = []string{ + "Ава", "Августа", "Августина", "Авдотья", "Аврора", "Агапия", "Агата", "Агафья", "Аглая", "Агния", "Агунда", "Ада", + "Аделаида", "Аделина", "Адель", "Адиля", "Адриана", "Аза", "Азалия", "Азиза", "Аида", "Аиша", "Ай", "Айару", "Айгерим", + "Айгуль", "Айлин", "Айнагуль", "Айнур", "Айсель", "Айсун", "Айсылу", "Аксинья", "Алана", "Алевтина", "Александра", + "Алексия", "Алеста", "Алина", "Алиса", "Алия", "Алла", "Алсу", "Алтын", "Альба", "Альбина", "Альфия", "Аля", "Алёна", + "Амалия", "Амаль", "Амина", "Амира", "Анабель", "Анаит", "Анастасия", "Ангелина", "Анжела", "Анжелика", "Анисья", "Анита", + "Анна", "Антонина", "Анфиса", "Аполлинария", "Арабелла", "Ариадна", "Ариана", "Арианда", "Арина", "Ария", "Асель", "Асия", + "Астрид", "Ася", "Афина", "Аэлита", "Ая", "Аяна", "Бажена", "Беатрис", "Бела", "Белинда", "Белла", "Берта", "Богдана", + "Божена", "Бьянка", "Бэлла", "Валентина", "Валерия", "Ванда", "Ванесса", "Варвара", "Василина", "Василиса", "Венера", + "Вера", "Вероника", "Веста", "Вета", "Викторина", "Виктория", "Вилена", "Виола", "Виолетта", "Вита", "Виталина", "Виталия", + "Влада", "Владана", "Владислава", "Габриэлла", "Галина", "Галия", "Гаяна", "Гаянэ", "Генриетта", "Глафира", "Гоар", + "Грета", "Гульзира", "Гульмира", "Гульназ", "Гульнара", "Гульшат", "Гюзель", "Далида", "Дамира", "Дана", "Даниэла", + "Дания", "Дара", "Дарина", "Дарья", "Даяна", "Джамиля", "Дженна", "Дженнифер", "Джессика", "Джиневра", "Диана", "Дильназ", + "Дильнара", "Диля", "Дилярам", "Дина", "Динара", "Долорес", "Доминика", "Домна", "Домника", "Ева", "Евангелина", + "Евгения", "Евдокия", "Екатерина", "Елена", "Елизавета", "Есения", "Ея", "Жаклин", "Жанна", "Жансая", "Жасмин", "Жозефина", + "Жоржина", "Забава", "Заира", "Залина", "Замира", "Зара", "Зарема", "Зарина", "Земфира", "Зинаида", "Зита", "Злата", + "Златослава", "Зоряна", "Зоя", "Зульфия", "Зухра", "Ивета", "Иветта", "Изабелла", "Илина", "Иллирика", "Илона", "Ильзира", + "Илюза", "Инга", "Индира", "Инесса", "Инна", "Иоанна", "Ира", "Ирада", "Ираида", "Ирина", "Ирма", "Искра", "Ия", "Камила", + "Камилла", "Кара", "Каре", "Карима", "Карина", "Каролина", "Кира", "Клавдия", "Клара", "Констанция", "Кора", "Корнелия", + "Кристина", "Ксения", "Лада", "Лана", "Лара", "Лариса", "Лаура", "Лейла", "Леона", "Лера", "Леся", "Лета", "Лиана", "Лидия", + "Лиза", "Лика", "Лили", "Лилиана", "Лилит", "Лилия", "Лина", "Линда", "Лиора", "Лира", "Лия", "Лола", "Лолита", "Лора", + "Луиза", "Лукерья", "Лукия", "Луна", "Любава", "Любовь", "Людмила", "Люсиль", "Люсьена", "Люция", "Люче", "Ляйсан", "Ляля", + "Мавиле", "Мавлюда", "Магда", "Магдалена", "Мадина", "Мадлен", "Майя", "Макария", "Малика", "Мара", "Маргарита", "Марианна", + "Марика", "Марина", "Мария", "Мариям", "Марта", "Марфа", "Мелания", "Мелисса", "Мехри", "Мика", "Мила", "Милада", "Милана", + "Милен", "Милена", "Милица", "Милослава", "Мина", "Мира", "Мирослава", "Мирра", "Михримах", "Мишель", "Мия", "Моника", + "Муза", "Надежда", "Наиля", "Наима", "Нана", "Наоми", "Наргиза", "Наталья", "Нелли", "Нея", "Ника", "Николь", "Нина", + "Нинель", "Номина", "Нонна", "Нора", "Нурия", "Одетта", "Оксана", "Октябрина", "Олеся", "Оливия", "Ольга", "Офелия", + "Павлина", "Памела", "Патриция", "Паула", "Пейтон", "Пелагея", "Перизат", "Платонида", "Полина", "Прасковья", "Равшана", + "Рада", "Разина", "Раиля", "Раиса", "Раифа", "Ралина", "Рамина", "Раяна", "Ребекка", "Регина", "Резеда", "Рена", "Рената", + "Риана", "Рианна", "Рикарда", "Римма", "Рина", "Рита", "Роберта", "Рогнеда", "Роза", "Роксана", "Роксолана", "Рузалия", + "Рузанна", "Русалина", "Руслана", "Руфина", "Руфь", "Сабина", "Сабрина", "Сажида", "Саида", "Салима", "Саломея", "Сальма", + "Самира", "Сандра", "Сания", "Сара", "Сати", "Сауле", "Сафия", "Сафура", "Саяна", "Светлана", "Севара", "Селена", "Сельма", + "Серафима", "Сесилия", "Сиара", "Сильвия", "Симона", "Снежана", "Соня", "Софья", "Стелла", "Стефания", "Сусанна", "Таисия", + "Тамара", "Тамила", "Тара", "Татьяна", "Тая", "Таяна", "Теона", "Тереза", "Тея", "Тина", "Тиффани", "Томирис", "Тора", + "Тэмми", "Ульяна", "Ума", "Урсула", "Устинья", "Фазиля", "Фаина", "Фарида", "Фариза", "Фатима", "Федора", "Фелисити", + "Фелиция", "Феруза", "Физалия", "Фируза", "Флора", "Флоренс", "Флорентина", "Флоренция", "Флориана", "Фредерика", + "Фрида", "Фёкла", "Хадия", "Хилари", "Хлоя", "Хюррем", "Цагана", "Цветана", "Цецилия", "Циара", "Челси", "Чеслава", + "Чулпан", "Шакира", "Шарлотта", "Шахина", "Шейла", "Шелли", "Шерил", "Эвелина", "Эвита", "Элеонора", "Элиана", "Элиза", + "Элина", "Элла", "Эльвина", "Эльвира", "Эльмира", "Эльнара", "Эля", "Эмили", "Эмилия", "Эмма", "Энже", "Эрика", "Эрмина", + "Эсмеральда", "Эсмира", "Эстер", "Этель", "Этери", "Юлианна", "Юлия", "Юна", "Юния", "Юнона", "Ядвига", "Яна", "Янина", + "Ярина", "Ярослава", "Ясмина"} + +var russianMiddleNamesFemale = []string{ + "Авдеевна", "Авксентиевна", "Агафоновна", "Акакиевна", "Александровна", "Алексеевна", "Альбертовна", "Альвиановна", "Анатольевна", "Андреевна", "Аникитична", + "Антоновна", "Антониновна", "Анфим", "Аристарховна", "Аркадьевна", "Арсеньевна", "Артёмовна", "Артемьевна", "Артуровна", "Архиповна", "Афанасьевна", "Богдановна", + "Борисовна", "Вавиловна", "Вадимовна", "Валентиновна", "Валерьевна", "Валерьяновна", "Варламовна", "Варсонофиевна", "Варфоломеевна", "Васильевна", "Венедиктовна", + "Вениаминовна", "Викентьевна", "Викторовна", "Виссарионовна", "Витальевна", "Владимировна", "Владиславовна", "Владленовна", "Власовна", "Всеволодовна", + "Вячеславовна", "Гаврииловна", "Галактионовна", "Геласиевна", "Геннадьевна", "Георгиевна", "Герасимовна", "Германовна", "Глебовна", "Гордеевна", + "Григорьевна", "Данактовна", "Данииловна", "Демидовна", "Демьяновна", "Денисовна", "Дмитриевна", "Добрыневна", "Донатовна", "Дорофеевна", "Евгеньевна", + "Евграфовна", "Евдокимовна", "Евсеевна", "Евстафьевна", "Егоровна", "Емельяновна", "Еремеевна", "Ермолаевна", "Ерофеевна", "Ефимовна", "Ефремовна", "Ждановна", + "Зиновьевна", "Иакинфовна", "Ивановна", "Игнатовна", "Игорьевна", "Ильинична", "Иннокентьевна", "Ираклиевна", "Иринеевна", "Исидоровна", "Иудична", "Иулиановна", + "Капитоновна", "Кимовна", "Кировна", "Кирилловна", "Климентовна", "Кондратовна", "Кононовна", "Константиновна", "Корнилиевна", "Кузьминична", "Куприяновна", + "Лаврентиевна", "Львовна", "Леонидовна", "Леонтьевна", "Логгиновна", "Лукинична", "Лукиевна", "Лукьянновна", "Магистриановна", "Макаровна", "Максимовна", "Марковна", + "Мартыновна", "Матвеевна", "Мелентиевна", "Минична", "Мироновна", "Мирославовна", "Митрофановна", "Михайловна", "Мстиславовна", "Назаровна", "Несторовна", + "Никаноровна", "Никитична", "Никифоровна", "Никодимовна", "Николаевна", "Никоновна", "Олеговна", "Онисимовна", "Онуфриевна", "Павловна", "Паисиевна", "Панкратовна", + "Пантелеймоновна", "Парфеньевна", "Пафнутьевна", "Пахомиевна", "Петровна", "Платоновна", "Поликарповна", "Порфирьевна", "Потаповна", "Провна", "Прокопьевна", + "Протасиевна", "Прохоровна", "Родионович", "Родославовна", "Романовна", "Ростиславовна", "Руслановна", "Саввична", "Савельевна", "Самуиловна", "Святополковна", + "Святославовна", "Севастьяновна", "Семёновна", "Серафимовна", "Сергеевна", "Силовна", "Сильвестровна", "Созоновна", "Софроновна", "Спиридоновна", "Станиславовна", + "Степановна", "Тарасовна", "Тимофеевна", "Тимуровна", "Титовна", "Тихоновна", "Трифоновна", "Трофимовна", "Фаддеевна", "Фёдоровна", "Федосеевна", "Федотовна", "Феликсовна", + "Феоктистовна", "Филатовна", "Филимоновна", "Филипповна", "Фирсовна", "Фокична", "Фомична", "Фотичевна", "Фроловна", "Харитоновна", "Хрисановна", "Христофоровна", + "Эдуардовна", "Эрастовна", "Юлиановна", "Юрьевна", "Юстиновна", "Яковлевна", "Якуновна", "Ярославовна", "Иосифовна", +} + +var russianLastNamesFemale = []string{ + "Абакумова", "Абдуллаева", "Абрамова", "Абрикосова", "Абросимова", "Абузярова", "Авакумова", "Авдеева", "Авдиева", + "Аверкиева", "Аверкова", "Авилина", "Авилова", "Авксентьева", "Аврамова", "Авсеева", "Агапеева", "Агапова", "Агапьева", + "Агафонова", "Агеева", "Агутина", "Адрианова", "Ажаева", "Азарова", "Азарьева", "Азарьина", "Азольская", "Айтматова", + "Акатова", "Акатьева", "Акбулатова", "Акимова", "Акиндинова", "Акинфиева", "Акинфова", "Аксенова", "Аксентьева", + "Аксёнова", "Акулина", "Акулова", "Алданова", "Алейникова", "Александрова", "Алексеева", "Алексина", "Алехина", + "Алешковская", "Алимпиева", "Алипова", "Алипьева", "Алисова", "Алпатова", "Алтухова", "Алферьева", "Алфимова", + "Алфёрова", "Алябьева", "Амарантова", "Амвросова", "Амвросьева", "Аммосова", "Амосова", "Амфитеатрова", "Ананьева", + "Ананьина", "Анастасова", "Анастасьева", "Андреева", "Андрианова", "Андроникова", "Андронова", "Андропова", "Андрусова", + "Анемподистова", "Аникеева", "Анисимова", "Анискина", "Анкидинова", "Анкудинова", "Анненкова", "Аннинская", "Антипина", + "Антипова", "Антипьева", "Антонова", "Антоньева", "Анурова", "Анурьева", "Анфимова", "Анхимова", "Анцыферова", "Анчарова", + "Анюкова", "Апарина", "Арабова", "Арановская", "Арбатова", "Арбузова", "Ардалионова", "Аренская", "Арепьева", "Арефина", + "Арефова", "Арефьева", "Аристархова", "Аристова", "Аркадова", "Аркадьева", "Аркадьина", "Арсенова", "Арсеньева", + "Артамонова", "Артемьева", "Артёмова", "Архангельская", "Архипова", "Архипьева", "Арцыбашева", "Арцыбушева", "Асафова", + "Асафьева", "Асеева", "Астапова", "Астафьева", "Астахова", "Асташина", "Аствацатурова", "Атаманова", "Афанасова", + "Афанасьева", "Афремова", "Африканова", "Африкантова", "Афросимова", "Ахадова", "Ахмедова", "Бабаевская", "Бабикова", + "Бабурова", "Бавильская", "Багирова", "Багринцева", "Багрянцева", "Бажова", "Байбородина", "Бакланова", "Бакунина", + "Балдина", "Балкова", "Банникова", "Банщикова", "Баранова", "Бартенева", "Басинская", "Баскакова", "Басманова", + "Басырова", "Белезянская", "Белинская", "Белова", "Белозерова", "Белозёрова", "Белокурова", "Беломлинская", + "Белорукова", "Белоусова", "Беляева", "Белякова", "Белянкина", "Бенедиктова", "Березина", "Березовская", "Берестова", + "Берсенева", "Берёзина", "Беседина", "Беспалова", "Беспутина", "Бестужева", "Марлинская", "Бирюкова", "Битова", "Блинова", + "Блохина", "Бобкова", "Боборыкина", "Боброва", "Богданова", "Боголюбская", "Богомолова", "Богомякова", "Богословская", + "Богоявленская", "Богуславская", "Бодрова", "Бодылева", "Болотова", "Болтышева", "Болучевская", "Большакова", + "Бондарева", "Борисова", "Боровая", "Бородина", "Бортникова", "Борцова", "Босова", "Боченкова", "Бочкова", "Бояндина", + "Боярская", "Бояшова", "Брагина", "Брежнева", "Брешковская", "Бровцева", "Бродская", "Брюсова", "Бузина", "Булатова", + "Булгакова", "Булганина", "Булгарина", "Булочникова", "Булычева", "Бунина", "Буркатовская", "Бурмистрова", "Бурова", + "Буровская", "Бутина", "Бутова", "Буторина", "Бушина", "Быкова", "Бычкова", "Вавилина", "Вавилова", "Вакулина", + "Вакулова", "Валентинова", "Валетова", "Варламова", "Варнавина", "Варшавская", "Васечкина", "Василева", "Василова", + "Васильева", "Васькина", "Вахтина", "Веденская", "Веневитинова", "Венедиктова", "Вепрева", "Верзилова", "Веркина", + "Верникова", "Вершинина", "Веселова", "Ветрова", "Викентьева", "Викторова", "Виноградова", "Винтилова", "Вирхова", + "Витковская", "Витушева", "Витязева", "Вихрова", "Вишневская", "Вишнякова", "Владимирова", "Владимирская", "Владимова", + "Власова", "Власьева", "Внифатьева", "Водденикова", "Водолазкина", "Войнова", "Волкова", "Володарская", "Володихина", + "Волочкова", "Вонифатова", "Вонифатьева", "Воробьева", "Воронова", "Воронцова", "Воротникова", "Воскобойникова", + "Вострякова", "Вотрина", "Всеволожская", "Вяземская", "Габышева", "Гаврилина", "Гаврилова", "Гагарина", "Газданова", + "Галактионова", "Галкина", "Галковская", "Галктионова", "Гальцова", "Гандлевская", "Ганиева", "Ганичева", "Гарасимова", + "Гатапова", "Гедеонова", "Геласимова", "Геннадиева", "Геогиевская", "Герасимова", "Гераскина", "Германова", + "Гермогенова", "Гершанова", "Гиваргизова", "Гиляровская", "Гладилина", "Гладкова", "Гладышева", "Глуховская", + "Гляделкина", "Гнилорыбова", "Голикова", "Голофтеева", "Голубева", "Голунова", "Гомзикова", "Гончарова", "Горбунова", + "Гордеева", "Горелова", "Горланова", "Горлова", "Горчева", "Горшкова", "Гостева", "Гранина", "Графинина", "Гребенщикова", + "Грибанова", "Григорова", "Григорьева", "Грина", "Гришина", "Громова", "Грунина", "Грязева", "Гуляева", "Гурская", + "Гурьева", "Гусева", "Гусельникова", "Гущина", "Давыдова", "Далина", "Далматова", "Данилина", "Данилкина", "Данилова", + "Данихнова", "Данова", "Данькова", "Дашкова", "Девяткина", "Дегтева", "Дедова", "Деева", "Дежнева", "Дементьева", + "Демидова", "Денежкина", "Денисова", "Денисьева", "Деревенская", "Дзержинская", "Димитриева", "Дмитриева", "Добродеева", + "Добролюбова", "Доброхотова", "Добычина", "Довлатова", "Додолева", "Долина", "Долинская", "Долотина", "Домбровская", + "Домникова", "Донцова", "Доримедонтова", "Дормедонтова", "Дормидонтова", "Доронина", "Дорофеева", "Достоевская", + "Драгунская", "Дриянская", "Дроздова", "Дружаева", "Дружинина", "Дружникова", "Дубаева", "Дубина", "Дубинина", + "Дубинянская", "Дубова", "Дудина", "Дудинцева", "Дышева", "Дьяконова", "Дьячкова", "Дёмушкина", "Евгенова", "Евгеньева", + "Евдокимова", "Евлампиева", "Евменова", "Евменьева", "Евплова", "Евсеева", "Евстафьева", "Евстигнеева", "Евстифеева", + "Евстратова", "Евсюкова", "Евтифеева", "Евтихеева", "Егорова", "Егорьева", "Ежова", "Екимова", "Елагина", "Еланцева", + "Елеазарова", "Елеферьева", "Елизарова", "Елизарьева", "Елисеева", "Елфимова", "Ельчина", "Ельшина", "Емельянова", + "Епенетова", "Епимахова", "Епинетова", "Епифанова", "Епифаньева", "Ерастова", "Еремеева", "Ермакова", "Ермилина", + "Ермилова", "Ермошина", "Ерофеева", "Ерошкина", "Ершова", "Ерёмина", "Есенина", "Есина", "Есипова", "Естамонова", + "Ефимова", "Ефимьева", "Ефремова", "Ефросинова", "Ешкилева", "Жаринова", "Жарковская", "Жбанова", "Жвалевская", + "Жвалова", "Жданова", "Жемчужникова", "Жеребцова", "Жерихова", "Живетьева", "Жириновская", "Житинская", "Житкова", + "Жукова", "Жуковская", "Жуликова", "Жулина", "Журавская", "Заборова", "Заволокина", "Загорцева", "Задорнова", "Задорова", + "Зайончковская", "Зайцева", "Залыгина", "Замуткина", "Замыслова", "Замятина", "Заостровцева", "Заплетина", "Зарубина", + "Захарова", "Захарьева", "Захарьина", "Збруева", "Зверева", "Звягина", "Зеленина", "Земляная", "Земскова", "Зиганшина", + "Зикунова", "Зимина", "Зиновьева", "Златовратская", "Златогорская", "Златоустская", "Знаменская", "Золотцева", + "Зорина", "Зосимова", "Зотеева", "Зотова", "Зотьева", "Зудина", "Зуева", "Зыкина", "Зыкова", "Зюганова", "Зюзюкина", + "Зябликова", "Ивакина", "Иванкина", "Иванова", "Ивлева", "Ивонина", "Ивонова", "Игнатова", "Игнатьева", "Игнашева", + "Игумнова", "Идиатуллина", "Идова", "Иевлева", "Иженякова", "Измайлова", "Изосимова", "Изотова", "Иличевская", + "Ильенкова", "Ильина", "Инина", "Иовлева", "Ионина", "Ионова", "Ипатова", "Ипатьева", "Ипполитова", "Иринеева", + "Исаева", "Исаина", "Исакова", "Кабакова", "Кабанова", "Каверина", "Каганова", "Казакова", "Казанцева", "Казимирова", + "Казинцева", "Калашникова", "Каледина", "Калинина", "Каминова", "Каминская", "Канаева", "Кандаурова", "Каневская", + "Капитонова", "Капустина", "Карабанова", "Карагодина", "Карамзина", "Карасева", "Караулова", "Каренина", "Карионова", + "Карлова", "Карпеева", "Карпенкова", "Карпова", "Картофельникова", "Каруселина", "Касимова", "Катаева", "Каткова", + "Кашафутдинова", "Кашина", "Каштанова", "Квартальнова", "Кедрина", "Кенжеева", "Киприанова", "Кирикова", "Кирилина", + "Кириллова", "Кирилова", "Кирова", "Кирсанова", "Кисина", "Китова", "Кленикова", "Клеопина", "Клеопова", "Клепикова", + "Клепова", "Климентова", "Климентьева", "Клюева", "Князева", "Кобзева", "Кобрина", "Ковалева", "Ковшова", "Кожевникова", + "Козлачкова", "Козлова", "Козырева", "Козьмина", "Коклюшкина", "Колесникова", "Колина", "Колобова", "Колокольцева", + "Колпакова", "Колядина", "Комарова", "Комиссарова", "Кондратова", "Кондратьева", "Коновалова", "Кононова", "Кононыхина", + "Константинова", "Контровская", "Конюкова", "Конюшевская", "Коняева", "Копелева", "Копылова", "Корабальникова", + "Коржавина", "Кормильцева", "Корнилова", "Корнильева", "Коровина", "Королева", "Корчагина", "Корявина", "Косая", + "Костина", "Косьмина", "Котляревская", "Котова", "Котовская", "Кофанова", "Кочергина", "Кошелева", "Крапивина", + "Красильникова", "Кривомазова", "Кривцова", "Кругосветова", "Крупина", "Крупнова", "Крусанова", "Крутихина", "Крылова", + "Крюкова", "Куваева", "Кувалдина", "Кудинова", "Кудрявцева", "Кудряшова", "Кузечкина", "Кузикова", "Кузнецова", + "Кузьмина", "Кулагина", "Кулакова", "Куликова", "Купреянова", "Куприна", "Купряшина", "Куратова", "Курилова", "Куркова", + "Курочкина", "Курчаткина", "Кучерская", "Лаврентьева", "Лаврина", "Лаврова", "Лагина", "Лагунова", "Лазарева", + "Лактионова", "Ланькова", "Лапина", "Лапутина", "Ларионова", "Латынина", "Лахтионова", "Лебедева", "Леванидова", + "Левина", "Левитина", "Левонова", "Левонтьева", "Леонидова", "Леонова", "Леонтьева", "Лепёхина", "Лермонтова", + "Лесина", "Лескова", "Ливанова", "Лидская", "Лимонова", "Липатова", "Липкина", "Липскерова", "Листьева", "Литаврина", + "Литвинова", "Лиханова", "Личутина", "Лобанова", "Лобкова", "Ловчикова", "Логинова", "Ложкомоева", "Ломакина", "Ломова", + "Ломоносова", "Лорченкова", "Лоскутова", "Лошкомоева", "Лугинова", "Лужина", "Лукина", "Лукошина", "Лукьянова", + "Луппова", "Лутьянова", "Лыжина", "Лыткина", "Любимова", "Люкина", "Люсина", "Лялина", "Маврова", "Мазина", "Маканина", + "Макарова", "Макарьева", "Макина", "Максимишина", "Максимова", "Максимушкина", "Малафеева", "Малахеева", "Малахова", + "Маликова", "Малинина", "Малкина", "Малышева", "Малярова", "Мамантова", "Мамедова", "Мамлеева", "Мамонтова", "Мануйлова", + "Манулкина", "Манылина", "Манылова", "Марамзина", "Маргелова", "Маринина", "Маркелова", "Маркианова", "Маркова", + "Марковчина", "Мартемьянова", "Мартынова", "Мартытова", "Мартьянова", "Маслова", "Матвеева", "Машкина", "Маяковская", + "Маятникова", "Медведева", "Медкова", "Мелитонова", "Мелихова", "Мельникова", "Мережковская", "Мерецкова", "Меркулова", + "Меркульева", "Меркурова", "Меркурьева", "Меркушева", "Микитова", "Милова", "Минаева", "Минина", "Миронова", + "Мирошникова", "Мисайлова", "Митрофанова", "Митрофаньева", "Мифтахутдинова", "Михаилова", "Михайлина", "Михайлова", + "Михайловская", "Михеева", "Мишина", "Мишкина", "Мишнева", "Мишустина", "Могутина", "Модестова", "Можаева", "Мозгова", + "Мозговая", "Мозжухина", "Моисеева", "Мойсеева", "Молчанова", "Монастырская", "Мордовцева", "Морковина", "Морозова", + "Морщакова", "Мосеева", "Москвина", "Моторина", "Мохнаткина", "Мурманина", "Мурманова", "Мурмановская", "Мурманская", + "Мурманцева", "Муромская", "Мухина", "Мышкина", "Мягкова", "Мясникова", "Набокова", "Нагибина", "Назарова", "Назарьева", + "Нарбикова", "Нарицина", "Наседкина", "Насонова", "Наумова", "Нахапетова", "Невзорова", "Негина", "Незнанская", + "Неклюдова", "Некрасова", "Немирова", "Немцова", "Немчинова", "Ненарокова", "Несмеянова", "Неспанова", "Нестерова", + "Нетёсова", "Нефедьева", "Нефёдова", "Нехлюдова", "Нехорошева", "Нечаева", "Никандрова", "Никанорова", "Никитина", + "Никифорова", "Никодимова", "Николаева", "Николина", "Никонова", "Никтитина", "Никулина", "Новгородцева", "Новикова", + "Новодворская", "Новосельцева", "Новосёлова", "Норова", "Носкова", "Носова", "Обросимова", "Обухова", "Овдокимова", + "Овечкина", "Овросимова", "Овсеева", "Овчинникова", "Огарева", "Оглоблина", "Одинцова", "Одоевская", "Окатова", + "Окулова", "Окунева", "Олейникова", "Олимпиева", "Олисова", "Олсуфьева", "Олтухова", "Олферьева", "Омельянова", + "Онисимова", "Опимахова", "Орехова", "Орлова", "Орловская", "Осеева", "Осинская", "Осипова", "Осокина", "Осоргина", + "Остальская", "Останина", "Остапова", "Остафьева", "Остратова", "Островская", "Офросимова", "Охотина", "Очина", + "Павлинова", "Павлова", "Павловская", "Палицина", "Пальцева", "Памфилова", "Панаева", "Панкеева", "Панкратова", + "Панкратьева", "Панова", "Пантелеева", "Панфилова", "Панфильева", "Панюшкина", "Парамонова", "Парменьева", "Пармёнова", + "Парфенчикова", "Парфеньева", "Парфёнова", "Паршова", "Парщикова", "Пастухова", "Патрикеева", "Паустовская", + "Паушкина", "Пафнутьева", "Пафомова", "Пахмутова", "Пахомова", "Пахомьева", "Пашкова", "Пашковская", "Пелевина", + "Первушина", "Пересторина", "Пермякова", "Перумова", "Перфильева", "Перфишина", "Перхурова", "Перхурьева", "Перцева", + "Пескова", "Пестова", "Петелина", "Петрова", "Петрушевская", "Петухова", "Пивоварова", "Пигасова", "Пигасьева", + "Пименова", "Писарева", "Писемская", "Питиримова", "Пияшева", "Плавильщикова", "Плакидина", "Платова", "Платонова", + "Платухина", "Плотникова", "Плющева", "Победоносцева", "Подистова", "Подколзина", "Подушкова", "Покровская", "Полевая", + "Поливанова", "Полиевктова", "Поликарпова", "Полокова", "Полуектова", "Полуехтова", "Полукарпова", "Полуянова", + "Полуяхтова", "Полякова", "Поляновская", "Полянская", "Померанцева", "Помяловская", "Пономарева", "Поплавская", + "Попова", "Попугаева", "Порфирьева", "Потапова", "Потапьева", "Привалова", "Пригова", "Пригожина", "Прилепина", + "Приставкина", "Пришвина", "Проклова", "Прокопова", "Прокопьева", "Прокофьева", "Пророкова", "Просвирнина", "Протасова", + "Протасьева", "Протоклитова", "Проханова", "Прохорова", "Прошина", "Прудникова", "Пруткова", "Пудеева", "Пудова", + "Пупкина", "Путина", "Пучкова", "Пушкина", "Пчёлкина", "Пьянова", "Работникова", "Радзинская", "Радивонова", "Радищева", + "Радугина", "Развожаева", "Ракова", "Ранцова", "Распутина", "Расторгуева", "Ратникова", "Рахматуллина", "Рачкова", + "Ремезова", "Ремизова", "Репникова", "Ржевская", "Римская", "Рогова", "Родивонова", "Родионова", "Родченкова", + "Рожкова", "Розанова", "Ромазанова", "Романова", "Ростова", "Рубанова", "Рубина", "Русакова", "Рыбакова", "Рылеева", + "Рыльникова", "Рысева", "Рябова", "Саблина", "Саватеева", "Саватьева", "Савельева", "Савина", "Савинова", "Савкина", + "Савостьянова", "Савёлова", "Садофова", "Садофьева", "Садулаева", "Сажина", "Сазонова", "Сакина", "Саломатова", + "Сальникова", "Самойлова", "Самсонова", "Самылина", "Самылова", "Санаева", "Сапронова", "Сапрыкина", "Сараскина", + "Сафонова", "Сафронова", "Сахарнова", "Сахновская", "Сбитнева", "Сбруева", "Светлова", "Свечина", "Свиридова", "Свитнева", + "Севастьянова", "Северьянова", "Северянина", "Сейдова", "Селиверстова", "Селина", "Семенова", "Семёнова", "Сенчина", + "Сергеева", "Серебренникова", "Серебрянская", "Серова", "Сиднина", "Сидоркина", "Сидорова", "Силина", "Симбирская", + "Симеонова", "Симонова", "Синявская", "Синякина", "Ситникова", "Скапидарова", "Скатова", "Скворцова", "Скоробогатова", + "Скороходова", "Скульская", "Скуратова", "Славина", "Славникова", "Слаповская", "Слепнева", "Слепухина", "Слюнькова", + "Смехова", "Смирнова", "Смоленская", "Смолина", "Смольникова", "Смородинская", "Снегирева", "Собакина", "Соболева", + "Советова", "Согрина", "Созонова", "Созонтова", "Сокова", "Соколова", "Сокурова", "Солженицина", "Солнцева", + "Соловьева", "Солодникова", "Соломатина", "Солопова", "Сопронова", "Сорбатская", "Сорокина", "Соротокина", + "Сотникова", "Софонова", "Софронова", "Софроньева", "Сошникова", "Спиридонова", "Спиридоньева", "Ставрогина", + "Старикова", "Старкова", "Стародубцева", "Степанова", "Степная", "Стефашина", "Стогова", "Стратоникова", "Стрелкова", + "Субботина", "Суворова", "Сударушкина", "Сумарокова", "Супрунова", "Сурова", "Суханова", "Сухилина", "Сухова", + "Сысоева", "Сычева", "Сычина", "Табакова", "Табатчикова", "Таланова", "Таралова", "Тарасова", "Тарасьева", + "Тарковская", "Тарусова", "Тархова", "Тасбулатова", "Тендрякова", "Терентьева", "Терехова", "Терешкова", "Тесакова", + "Тетерина", "Тимофеева", "Титова", "Тиханина", "Тихомирова", "Тихонова", "Тованичева", "Токарева", "Толстая", + "Топчиева", "Торлопова", "Третьякова", "Трефилова", "Трефильева", "Трифонова", "Тропина", "Трофимова", "Трудолюбова", + "Труфанова", "Тургенева", "Турова", "Туровская", "Тучкова", "Тынянова", "Тюльпанова", "Тютчева", "Тёмкина", "Уварова", + "Углева", "Удалова", "Удальцова", "Удачина", "Удодова", "Ульянова", "Упатова", "Успенская", "Устинова", "Устьянова", + "Уткина", "Утёсова", "Фавстова", "Фадеева", "Фалалеева", "Фандеева", "Фатеева", "Фатьянова", "Федина", "Федорова", + "Федосеева", "Федосова", "Федосьева", "Федотова", "Федотьева", "Федулеева", "Федулина", "Федулова", "Феклисова", + "Фенева", "Феоктистова", "Феонина", "Феофанова", "Феофилактова", "Феофилова", "Фетисова", "Фефилова", "Филаретова", + "Филатова", "Филатьева", "Филахтова", "Филимонихина", "Филимонова", "Филипова", "Филиппова", "Филиппьева", "Филипьева", + "Филкова", "Филонова", "Философова", "Фионина", "Фирсова", "Флегонтова", "Флегонтьева", "Фокина", "Фомина", "Фонвизина", + "Фортунатова", "Фотеева", "Фотиева", "Фотьева", "Фофанова", "Фролова", "Фурманова", "Фурсова", "Фурцева", "Фёдорова", + "Хадеева", "Хазанова", "Хазина", "Харитонова", "Харламова", "Харлампиева", "Хаустова", "Хемлина", "Хераскова", + "Хлестакова", "Хлопонина", "Хлумова", "Хохлова", "Хрисогонова", "Христофорова", "Цветанкова", "Цветкова", "Цепова", + "Цыганова", "Цыпкина", "Чаплина", "Чаплыгина", "Чарская", "Чарушникова", "Чванова", "Чекмаева", "Черепанова", + "Черепенникова", "Черкашина", "Чернева", "Чернова", "Черноусова", "Чернышева", "Чернышевская", "Чертанова", + "Черчесова", "Чехова", "Чивилихина", "Чижова", "Чикова", "Чипчикова", "Чиркова", "Чистова", "Чичваркина", "Чудакова", + "Чудинова", "Чуковская", "Чумакова", "Чуприянова", "Чурилова", "Чурова", "Шабалова", "Шакирова", "Шаламова", "Шаликова", + "Шалыганова", "Шамбарова", "Шапошникова", "Шарапова", "Шаргунова", "Шарова", "Шахмагонова", "Шашкова", "Шевцова", + "Шемякина", "Шепилова", "Шерстобитова", "Шестакова", "Шестинская", "Шесткова", "Шеянова", "Шилова", "Ширяева", "Шишкина", + "Шишкова", "Шмелева", "Шолохова", "Шпанова", "Шубина", "Шукшина", "Шуртакова", "Щеглова", "Щекина", "Щекочихина", + "Щелконогова", "Щепкина", "Щербакова", "Щербина", "Щукина", "Эмина", "Юдина", "Юдова", "Юрская", "Юхновская", "Яворская", + "Ягужинская", "Ядова", "Язова", "Якимова", "Яковлева", "Якушева", "Янина", "Янковская", "Янова", "Ярина", + "Яськова", "Яхина", +} + +// GetPerson returns a new Dowser interface of Person struct +func GetPerson() Dowser { + person := &Person{} + return person +} + +// Person struct +type Person struct { +} + +func (p Person) titlemale() string { + return randomElementFromSliceString(titlesMale) +} + +// TitleMale generates random titles for males +func (p Person) TitleMale(v reflect.Value) (any, error) { + return p.titlemale(), nil +} + +// TitleMale get a title male randomly in string ("Mr.", "Dr.", "Prof.", "Lord", "King", "Prince") +func TitleMale(opts ...options.OptionFunc) string { + return singleFakeData(TitleMaleTag, func() any { + p := Person{} + return p.titlemale() + }, opts...).(string) +} + +func (p Person) titleFemale() string { + return randomElementFromSliceString(titlesFemale) +} + +// TitleFeMale generates random titles for females +func (p Person) TitleFeMale(v reflect.Value) (any, error) { + return p.titleFemale(), nil +} + +// TitleFemale get a title female randomly in string ("Mrs.", "Ms.", "Miss", "Dr.", "Prof.", "Lady", "Queen", "Princess") +func TitleFemale(opts ...options.OptionFunc) string { + return singleFakeData(TitleFemaleTag, func() any { + p := Person{} + return p.titleFemale() + }, opts...).(string) +} + +func (p Person) firstname() string { + return randomElementFromSliceString(firstNames) +} + +// FirstName returns first names +func (p Person) FirstName(v reflect.Value) (any, error) { + return p.firstname(), nil +} + +// FirstName get fake firstname +func FirstName(opts ...options.OptionFunc) string { + return singleFakeData(FirstNameTag, func() any { + p := Person{} + return p.firstname() + }, opts...).(string) +} + +func (p Person) firstnamemale() string { + return randomElementFromSliceString(firstNamesMale) +} + +// FirstNameMale returns first names for males +func (p Person) FirstNameMale(v reflect.Value) (any, error) { + return p.firstnamemale(), nil +} + +// FirstNameMale get fake firstname for male +func FirstNameMale(opts ...options.OptionFunc) string { + return singleFakeData(FirstNameMaleTag, func() any { + p := Person{} + return p.firstnamemale() + }, opts...).(string) +} + +func (p Person) firstnamefemale() string { + return randomElementFromSliceString(firstNamesFemale) +} + +// FirstNameFemale returns first names for females +func (p Person) FirstNameFemale(v reflect.Value) (any, error) { + return p.firstnamefemale(), nil +} + +// FirstNameFemale get fake firstname for female +func FirstNameFemale(opts ...options.OptionFunc) string { + return singleFakeData(FirstNameFemaleTag, func() any { + p := Person{} + return p.firstnamefemale() + }, opts...).(string) +} + +func (p Person) lastname() string { + return randomElementFromSliceString(lastNames) +} + +// LastName returns last name +func (p Person) LastName(v reflect.Value) (any, error) { + return p.lastname(), nil +} + +// LastName get fake lastname +func LastName(opts ...options.OptionFunc) string { + return singleFakeData(LastNameTag, func() any { + p := Person{} + return p.lastname() + }, opts...).(string) +} + +func (p Person) name() string { + if randNameFlag > 50 { + return fmt.Sprintf("%s %s %s", randomElementFromSliceString(titlesFemale), randomElementFromSliceString(firstNamesFemale), randomElementFromSliceString(lastNames)) + } + return fmt.Sprintf("%s %s %s", randomElementFromSliceString(titlesMale), randomElementFromSliceString(firstNamesMale), randomElementFromSliceString(lastNames)) +} + +// Name returns a random name +func (p Person) Name(v reflect.Value) (any, error) { + return p.name(), nil +} + +// Name get fake name +func Name(opts ...options.OptionFunc) string { + return singleFakeData(NAME, func() any { + p := Person{} + return p.name() + }, opts...).(string) +} + +// Gender returns a random gender +func (p Person) Gender(v reflect.Value) (any, error) { + return p.gender(), nil +} + +func (p Person) gender() string { + return randomElementFromSliceString(genders) +} + +// Gender get fake gender +func Gender(opts ...options.OptionFunc) string { + return singleFakeData(GENDER, func() any { + p := Person{} + return p.gender() + }, opts...).(string) +} + +// ChineseFirstName returns a random chinese first name +func (p Person) ChineseFirstName(v reflect.Value) (any, error) { + return p.chineseFirstName(), nil +} + +func (p Person) chineseFirstName() string { + return randomElementFromSliceString(chineseFirstNames) +} + +// ChineseFirstName get chinese first name +func ChineseFirstName(opts ...options.OptionFunc) string { + return singleFakeData(ChineseFirstNameTag, func() any { + p := Person{} + return p.chineseFirstName() + }, opts...).(string) +} + +// ChineseLastName returns a random chinese last name +func (p Person) ChineseLastName(v reflect.Value) (any, error) { + return p.chineseLastName(), nil +} + +func (p Person) chineseLastName() string { + return randomElementFromSliceString(chineseLastNames) +} + +// ChineseLastName get chinese lsst name +func ChineseLastName(opts ...options.OptionFunc) string { + return singleFakeData(ChineseLastNameTag, func() any { + p := Person{} + return p.chineseLastName() + }, opts...).(string) +} + +// ChineseName returns a random nhinese name +func (p Person) ChineseName(v reflect.Value) (any, error) { + return p.chineseName(), nil +} + +func (p Person) chineseName() string { + return fmt.Sprintf("%s%s", randomElementFromSliceString(chineseFirstNames), randomElementFromSliceString(chineseLastNames)) +} + +// ChineseName get chinese lsst name +func ChineseName(opts ...options.OptionFunc) string { + return singleFakeData(ChineseNameTag, func() any { + p := Person{} + return p.chineseName() + }, opts...).(string) +} + +func (p Person) russianFirstNameMale() string { + return randomElementFromSliceString(russianFirstNamesMale) +} + +func (p Person) russianMiddleNameMale() string { + return randomElementFromSliceString(russianMiddleNamesMale) +} + +func (p Person) russianLastNameMale() string { + return randomElementFromSliceString(russianLastNamesMale) +} + +func (p Person) russianFirstNameFemale() string { + return randomElementFromSliceString(russianFirstNamesFemale) +} + +func (p Person) russianMiddleNameFemale() string { + return randomElementFromSliceString(russianMiddleNamesFemale) +} + +func (p Person) russianLastNameFemale() string { + return randomElementFromSliceString(russianLastNamesFemale) +} + +// RussianFirstNameMale returns russian male firstname +func (p Person) RussianFirstNameMale(v reflect.Value) (any, error) { + return p.russianFirstNameMale(), nil +} + +// RussianMiddleNameMale returns russian male middlename +func (p Person) RussianMiddleNameMale(v reflect.Value) (any, error) { + return p.russianMiddleNameMale(), nil +} + +// RussianLastNameMale returns russian male lastname +func (p Person) RussianLastNameMale(v reflect.Value) (any, error) { + return p.russianLastNameMale(), nil +} + +// RussianFirstNameFemale returns russian female firstname +func (p Person) RussianFirstNameFemale(v reflect.Value) (any, error) { + return p.russianFirstNameFemale(), nil +} + +// RussianMiddleNameFemale returns russian female middlename +func (p Person) RussianMiddleNameFemale(v reflect.Value) (any, error) { + return p.russianMiddleNameFemale(), nil +} + +// RussianLastNameFemale returns russian female lastname +func (p Person) RussianLastNameFemale(v reflect.Value) (any, error) { + return p.russianLastNameFemale(), nil +} diff --git a/vendor/github.com/go-faker/faker/v4/phone.go b/vendor/github.com/go-faker/faker/v4/phone.go new file mode 100644 index 0000000..87e8bc2 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/phone.go @@ -0,0 +1,97 @@ +package faker + +import ( + "fmt" + "reflect" + "strings" + + "github.com/go-faker/faker/v4/pkg/options" + "github.com/go-faker/faker/v4/pkg/slice" +) + +// GetPhoner serves as a constructor for Phoner interface +func GetPhoner() Phoner { + phone := &Phone{} + return phone +} + +// Phoner serves overall tele-phonic contact generator +type Phoner interface { + PhoneNumber(v reflect.Value) (any, error) + TollFreePhoneNumber(v reflect.Value) (any, error) + E164PhoneNumber(v reflect.Value) (any, error) +} + +// Phone struct +type Phone struct { +} + +func (p Phone) phonenumber() string { + randInt, _ := RandomInt(1, 10) + str := strings.Join(slice.IntToString(randInt), "") + return fmt.Sprintf("%s-%s-%s", str[:3], str[3:6], str[6:10]) +} + +// PhoneNumber generates phone numbers of type: "201-886-0269" +func (p Phone) PhoneNumber(v reflect.Value) (any, error) { + return p.phonenumber(), nil +} + +// Phonenumber get fake phone number +func Phonenumber(opts ...options.OptionFunc) string { + return singleFakeData(PhoneNumber, func() any { + p := Phone{} + return p.phonenumber() + }, opts...).(string) +} + +func (p Phone) tollfreephonenumber() string { + var out strings.Builder + boxDigitsStart := []string{"777", "888"} + + ints, _ := RandomInt(1, 9) + for index, v := range slice.IntToString(ints) { + if index == 3 { + out.WriteString("-") + } + out.WriteString(v) + } + return fmt.Sprintf("(%s) %s", boxDigitsStart[rand.Intn(len(boxDigitsStart))], out.String()) +} + +// TollFreePhoneNumber generates phone numbers of type: "(888) 937-7238" +func (p Phone) TollFreePhoneNumber(v reflect.Value) (any, error) { + return p.tollfreephonenumber(), nil +} + +// TollFreePhoneNumber get fake TollFreePhoneNumber +func TollFreePhoneNumber(opts ...options.OptionFunc) string { + return singleFakeData(TollFreeNumber, func() any { + p := Phone{} + return p.tollfreephonenumber() + }, opts...).(string) +} + +func (p Phone) e164PhoneNumber() string { + out := "" + boxDigitsStart := []string{"7", "8"} + ints, _ := RandomInt(1, 10) + + for _, v := range slice.IntToString(ints) { + out += v + } + return fmt.Sprintf("+%s%s", boxDigitsStart[rand.Intn(len(boxDigitsStart))], strings.Join(slice.IntToString(ints), "")) +} + +// E164PhoneNumber generates phone numbers of type: "+27113456789" +func (p Phone) E164PhoneNumber(v reflect.Value) (any, error) { + return p.e164PhoneNumber(), nil +} + +// E164PhoneNumber get fake E164PhoneNumber +func E164PhoneNumber(opts ...options.OptionFunc) string { + return singleFakeData(E164PhoneNumberTag, func() any { + p := Phone{} + return p.e164PhoneNumber() + }, opts...).(string) +} diff --git a/vendor/github.com/go-faker/faker/v4/pkg/errors/generic.go b/vendor/github.com/go-faker/faker/v4/pkg/errors/generic.go new file mode 100644 index 0000000..fc7daf0 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/pkg/errors/generic.go @@ -0,0 +1,49 @@ +package errors + +// Generic Error Messages for tags +// +// ErrUnsupportedKindPtr: Error when get fake from ptr +// ErrUnsupportedKind: Error on passing unsupported kind +// ErrValueNotPtr: Error when value is not pointer +// ErrTagNotSupported: Error when tag is not supported +// ErrTagAlreadyExists: Error when tag exists and call AddProvider +// 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" + ErrValueNotPtr = "Not a pointer value" + ErrTagNotSupported = "Tag unsupported: %s" + ErrTagAlreadyExists = "Tag exists" + ErrTagDoesNotExist = "Tag does not exist" + ErrFieldTagIdentifierInvalid = "Field tag identifier invalid" + ErrMoreArguments = "Passed more arguments than is possible : (%d)" + ErrNotSupportedPointer = "Use sample:=new(%s)\n faker.FakeData(sample) instead" + ErrSmallerThanZero = "Size:%d is smaller than zero." + ErrSmallerThanOne = "Size:%d is smaller than one." + ErrUniqueFailure = "Failed to generate a unique value for field \"%s\"" + + ErrStartValueBiggerThanEnd = "Start value can not be bigger than end value." + ErrWrongFormattedTag = "Tag \"%s\" is not written properly" + ErrUnknownType = "Unknown Type" + ErrNotSupportedTypeForTag = "Type is not supported by tag." + ErrUnsupportedTagArguments = "Tag arguments are not compatible with field type." + ErrDuplicateSeparator = "Duplicate separator for tag arguments." + 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\")" +) diff --git a/vendor/github.com/go-faker/faker/v4/pkg/interfaces/language.go b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/language.go new file mode 100644 index 0000000..dff1859 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/language.go @@ -0,0 +1,24 @@ +package interfaces + +// LangRuneBoundary is for language boundary +type LangRuneBoundary struct { + Start rune + End rune + Exclude []rune +} + +// Language rune boundaries here +var ( + // LangENG is for english language + LangENG = LangRuneBoundary{65, 122, []rune{91, 92, 93, 94, 95, 96}} + // LangCHI is for chinese language + LangCHI = LangRuneBoundary{19968, 40869, nil} + // LangRUS is for russian language + LangRUS = LangRuneBoundary{1025, 1105, nil} + // LangJPN is for japanese Hiragana Katakana language + LangJPN = LangRuneBoundary{12353, 12534, []rune{12436, 12437, 12438, 12439, 12440, 12441, 12442, 12443, 12444, 12445, 12446, 12447, 12448}} + // LangKOR is for korean Hangul language + LangKOR = LangRuneBoundary{44032, 55203, nil} + // EmotEMJ is for emoticons + EmotEMJ = LangRuneBoundary{126976, 129535, nil} +) diff --git a/vendor/github.com/go-faker/faker/v4/pkg/interfaces/number.go b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/number.go new file mode 100644 index 0000000..59dddfb --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/number.go @@ -0,0 +1,18 @@ +package interfaces + +// RandomIntegerBoundary is the struct for random integer boundaries +type RandomIntegerBoundary struct { + Start int + End int +} + +// RandomFloatBoundary is the struct for random float boundaries +type RandomFloatBoundary struct { + Start float64 + End float64 +} + +var ( + DefaultIntBoundary = RandomIntegerBoundary{Start: 0, End: 100} + DefaultFloatBoundary = RandomFloatBoundary{Start: 0, End: 100} +) diff --git a/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go new file mode 100644 index 0000000..61da7c4 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/pkg/interfaces/type.go @@ -0,0 +1,10 @@ +package interfaces + +import "reflect" + +// CustomProviderFunction used as the standard layout function for custom providers +type CustomProviderFunction func() (any, error) + +// TaggedFunction used as the standard layout function for tag providers in struct. +// This type also can be used for custom provider. +type TaggedFunction func(v reflect.Value) (any, error) diff --git a/vendor/github.com/go-faker/faker/v4/pkg/options/options.go b/vendor/github.com/go-faker/faker/v4/pkg/options/options.go new file mode 100644 index 0000000..cf68aaa --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/pkg/options/options.go @@ -0,0 +1,409 @@ +package options + +import ( + "errors" + "fmt" + "math/rand" + "reflect" + "sync/atomic" + "time" + "unsafe" + + fakerErrors "github.com/go-faker/faker/v4/pkg/errors" + "github.com/go-faker/faker/v4/pkg/interfaces" +) + +var ( + // global settings, read/write must be concurrent safe + generateUniqueValues atomic.Value + ignoreInterface atomic.Value + randomStringLen int32 = 25 + lang unsafe.Pointer + randomMaxSize int32 = 100 + randomMinSize int32 + iBoundary unsafe.Pointer +) + +func init() { + generateUniqueValues.Store(false) + ignoreInterface.Store(false) + lang = unsafe.Pointer(&interfaces.LangENG) + iBoundary = unsafe.Pointer(&interfaces.DefaultIntBoundary) +} + +// Options represent all available option for faker. +type Options struct { + // IgnoreFields used for ignoring a field when generating the fake data + IgnoreFields map[string]struct{} + // FieldProviders used for storing the custom provider function + FieldProviders map[string]interfaces.CustomProviderFunction + // StructTypeProviders used for storing the struct type of custom provider function + StructTypeProviders map[reflect.Type]interfaces.CustomProviderFunction + // MaxDepthOption used for configuring the max depth of nested identical structs for faker + MaxDepthOption *MaxDepthOption + // MaxFieldDepthOption used for configuring the max depth of fields that are filled for a struct + MaxFieldDepthOption int + // IgnoreInterface used for ignoring any interface field + IgnoreInterface bool + // StringLanguage used for setting the language for any string in faker + StringLanguage *interfaces.LangRuneBoundary + // GenerateUniqueValues to ensure the generated data is unique + GenerateUniqueValues bool + // RandomStringLength to ensure the generated string is expected as we want + RandomStringLength int + // RandomMaxSliceSize used for setting the maximum of slice size, or map size that will be generated + RandomMaxSliceSize int + // RandomMinSliceSize used for setting the minimum of slize, array, map size that will be generated + RandomMinSliceSize int + // MaxGenerateStringRetries set how much tries for generating random string + MaxGenerateStringRetries int + // SetSliceMapNilIfLenZero allows to set nil for the slice and maps, if size is 0. + SetSliceMapNilIfLenZero bool + // SetSliceMapRandomToZero sets random integer generation to zero for slice and maps + SetSliceMapRandomToZero bool + // RandomIntegerBoundary sets boundary random integer value generation. Boundaries can not exceed integer(4 byte...) + RandomIntegerBoundary *interfaces.RandomIntegerBoundary + // RandomFloatBoundary sets the boundary for random float value generation. Boundaries should comply with float values constraints (IEEE 754) + RandomFloatBoundary *interfaces.RandomFloatBoundary + // SetTagName sets the tag name that should be used + TagName string + // CustomDomain is used for specifying a custom domain when generating email + CustomDomain *string + // OnlyZeroFields skips any field that already holds a non-zero value, leaving it unchanged + OnlyZeroFields bool + // RandomNestedMaxSliceSize controls the max size for slices/maps that are nested inside + // another slice or map. When set, this prevents exponential memory growth when generating + // large outer slices containing structs with nested slice/map fields. + // If unset (0), RandomMaxSliceSize applies at all depths (original behavior). + RandomNestedMaxSliceSize int + // RandomNestedMinSliceSize controls the min size for slices/maps nested inside another + // slice or map. Pair with RandomNestedMaxSliceSize. + RandomNestedMinSliceSize int + // sliceDepth tracks the current nesting depth of slice/map generation. + // Access via IsNested() and Nested(); do not read or write this field directly. + sliceDepth int +} + +// MaxDepthOption used for configuring the max depth of nested struct for faker +type MaxDepthOption struct { + typeSeen map[reflect.Type]int + recursionMaxDepth int +} + +func (o *MaxDepthOption) RememberType(t reflect.Type) { + o.typeSeen[t]++ +} + +func (o *MaxDepthOption) ForgetType(t reflect.Type) { + o.typeSeen[t]-- +} + +func (o *MaxDepthOption) RecursionOutOfLimit(t reflect.Type) bool { + return o.typeSeen[t] > o.recursionMaxDepth +} + +// IsNested reports whether faker is currently generating elements inside an outer +// slice, array, or map. Used by randomSliceAndMapSize to pick nested sizes. +func (o Options) IsNested() bool { + return o.sliceDepth > 0 +} + +// Nested returns a copy of o with the nesting depth incremented by one. +// Call this before recursing into the elements of a slice, array, or map. +// +// The value receiver is intentional: Go copies o on entry, so incrementing +// sliceDepth and returning that copy leaves the caller's Options unchanged. +// A pointer receiver would mutate the original and corrupt depth tracking +// across sibling iterations. +func (o Options) Nested() Options { + o.sliceDepth++ + return o +} + +// BuildOptions build all option functions into one option +func BuildOptions(optFuncs []OptionFunc) *Options { + ops := DefaultOption() + + for _, optFunc := range optFuncs { + optFunc(ops) + } + + return ops +} + +// DefaultOption build the default option +func DefaultOption() *Options { + ops := &Options{} + ops.StructTypeProviders = make(map[reflect.Type]interfaces.CustomProviderFunction) + ops.StructTypeProviders[reflect.TypeFor[time.Time]()] = func() (any, error) { + return time.Now().Add(time.Duration(rand.Int63())), nil + } + ops.MaxDepthOption = &MaxDepthOption{ + typeSeen: make(map[reflect.Type]int, 1), + recursionMaxDepth: 1, + } + ops.MaxFieldDepthOption = -1 + ops.GenerateUniqueValues = generateUniqueValues.Load().(bool) + ops.IgnoreInterface = ignoreInterface.Load().(bool) + ops.StringLanguage = (*interfaces.LangRuneBoundary)(atomic.LoadPointer(&lang)) + ops.RandomStringLength = int(atomic.LoadInt32(&randomStringLen)) + ops.RandomMaxSliceSize = int(atomic.LoadInt32(&randomMaxSize)) + ops.RandomMinSliceSize = int(atomic.LoadInt32(&randomMinSize)) + ops.MaxGenerateStringRetries = 1000000 //default + ops.RandomIntegerBoundary = (*interfaces.RandomIntegerBoundary)(atomic.LoadPointer(&iBoundary)) + ops.RandomFloatBoundary = &interfaces.DefaultFloatBoundary + ops.TagName = "faker" + return ops +} + +// OptionFunc define the options contract +type OptionFunc func(oo *Options) + +// WithFieldsToIgnore used for ignoring a field when generating the fake data +func WithFieldsToIgnore(fieldNames ...string) OptionFunc { + return func(oo *Options) { + if oo.IgnoreFields == nil { + oo.IgnoreFields = make(map[string]struct{}, len(fieldNames)) + } + for _, f := range fieldNames { + oo.IgnoreFields[f] = struct{}{} + } + } +} + +// WithCustomDomain is used to set a custom domain for generating fake email +func WithCustomDomain(domain string) OptionFunc { + return func(oo *Options) { + oo.CustomDomain = &domain + } +} + +// WithCustomFieldProvider used for storing the custom provider function +func WithCustomFieldProvider(fieldName string, provider interfaces.CustomProviderFunction) OptionFunc { + return func(oo *Options) { + if oo.FieldProviders == nil { + oo.FieldProviders = make(map[string]interfaces.CustomProviderFunction, 1) + } + oo.FieldProviders[fieldName] = provider + } +} + +// WithRecursionMaxDepth used for configuring the max depth of recursion struct for faker +func WithRecursionMaxDepth(depth uint) OptionFunc { + return func(oo *Options) { + if oo.MaxDepthOption == nil { + oo.MaxDepthOption = &MaxDepthOption{ + recursionMaxDepth: 1, // default + typeSeen: make(map[reflect.Type]int, 1), + } + } + oo.MaxDepthOption.recursionMaxDepth = int(depth) + } +} + +// WithMaxFieldDepthOption used for configuring the max depth of fields that are filled for a struct +func WithMaxFieldDepthOption(depth int) OptionFunc { + return func(oo *Options) { + oo.MaxFieldDepthOption = depth + } +} + +// WithStructTypeProviders used for configuring the custom provider of struct type +func WithStructTypeProviders(t any, provider interfaces.CustomProviderFunction) OptionFunc { + if reflect.TypeOf(t).Kind() != reflect.Struct { + panic(fakerErrors.ErrOnlyStructTypeSupported) + } + return func(oo *Options) { + oo.StructTypeProviders[reflect.TypeOf(t)] = provider + } +} + +// WithIgnoreInterface allows to set a flag to ignore found interface{}s. +func WithIgnoreInterface(value bool) OptionFunc { + return func(oo *Options) { + oo.IgnoreInterface = value + } +} + +// WithStringLanguage sets language of random string generation (LangENG, LangCHI, LangRUS, LangJPN, LangKOR, EmotEMJ) +func WithStringLanguage(l interfaces.LangRuneBoundary) OptionFunc { + return func(oo *Options) { + oo.StringLanguage = &l + } +} + +// WithGenerateUniqueValues allows to set the single fake data generator functions to generate unique data. +func WithGenerateUniqueValues(unique bool) OptionFunc { + return func(oo *Options) { + oo.GenerateUniqueValues = unique + } +} + +// WithRandomStringLength sets a length for random string generation +func WithRandomStringLength(size uint) OptionFunc { + return func(oo *Options) { + oo.RandomStringLength = int(size) + } +} + +// WithRandomMapAndSliceMaxSize sets the max size for maps and slices for random generation. +func WithRandomMapAndSliceMaxSize(size uint) OptionFunc { + if size < 1 { + err := fmt.Errorf(fakerErrors.ErrSmallerThanOne, size) + panic(err) + } + return func(oo *Options) { + oo.RandomMaxSliceSize = int(size) + } +} + +// WithRandomMapAndSliceMinSize sets the min size for maps and slices for random generation. +func WithRandomMapAndSliceMinSize(size uint) OptionFunc { + return func(oo *Options) { + oo.RandomMinSliceSize = int(size) + } +} + +// WithNestedRandomMapAndSliceSize sets the min and max size for slices and maps that are +// generated as fields inside the elements of an outer slice or map. Use this together with +// WithRandomMapAndSliceMaxSize to avoid exponential memory growth when the generated struct +// contains nested slice/map fields. +// +// Example: generate 1000 users where each user's nested slices stay small: +// +// faker.FakeData(&users, +// options.WithRandomMapAndSliceMaxSize(1000), +// options.WithNestedRandomMapAndSliceSize(1, 5), +// ) +func WithNestedRandomMapAndSliceSize(minSize, maxSize uint) OptionFunc { + if maxSize < 1 { + panic(fmt.Errorf(fakerErrors.ErrSmallerThanOne, maxSize)) + } + if minSize > maxSize { + panic(errors.New(fakerErrors.ErrStartValueBiggerThanEnd)) + } + return func(oo *Options) { + oo.RandomNestedMinSliceSize = int(minSize) + oo.RandomNestedMaxSliceSize = int(maxSize) + } +} + +// WithMaxGenerateStringRetries set how much tries for generating random string +func WithMaxGenerateStringRetries(retries uint) OptionFunc { + return func(oo *Options) { + oo.MaxGenerateStringRetries = int(retries) + } +} + +// WithNilIfLenIsZero allows to set nil for the slice and maps, if size is 0. +func WithNilIfLenIsZero(setNil bool) OptionFunc { + return func(oo *Options) { + oo.SetSliceMapNilIfLenZero = setNil + } +} + +// WithSliceMapRandomToZero Sets random integer generation to zero for slice and maps +func WithSliceMapRandomToZero(setNumberToZero bool) OptionFunc { + return func(oo *Options) { + oo.SetSliceMapRandomToZero = setNumberToZero + } +} + +// WithRandomIntegerBoundaries sets boundary random integer value generation. Boundaries can not exceed integer(4 byte...) +func WithRandomIntegerBoundaries(boundary interfaces.RandomIntegerBoundary) OptionFunc { + if boundary.Start > boundary.End { + err := errors.New(fakerErrors.ErrStartValueBiggerThanEnd) + panic(err) + } + return func(oo *Options) { + oo.RandomIntegerBoundary = &boundary + } +} + +// WithRandomFloatBoundaries sets the boundary for random float value generation. Boundaries should comply with float values constraints (IEEE 754) +func WithRandomFloatBoundaries(boundary interfaces.RandomFloatBoundary) OptionFunc { + if boundary.Start > boundary.End { + err := errors.New(fakerErrors.ErrStartValueBiggerThanEnd) + panic(err) + } + return func(oo *Options) { + oo.RandomFloatBoundary = &boundary + } +} + +// WithOnlyZeroFields makes faker skip any field that already holds a non-zero value. +// Useful for partially pre-initializing a struct before passing it to faker. +func WithOnlyZeroFields() OptionFunc { + return func(oo *Options) { + oo.OnlyZeroFields = true + } +} + +// WithTagName sets the tag name to use. Default tag name is 'faker'. +func WithTagName(tagName string) OptionFunc { + if tagName == "" { + err := errors.New(fakerErrors.ErrFieldTagIdentifierInvalid) + panic(err) + } + return func(oo *Options) { + oo.TagName = tagName + } +} + +// SetGenerateUniqueValues allows to set the single fake data generator functions to generate unique data. +func SetGenerateUniqueValues(unique bool) { + generateUniqueValues.Store(unique) +} + +// SetIgnoreInterface allows to set a flag to ignore found interface{}s. +func SetIgnoreInterface(ignore bool) { + ignoreInterface.Store(ignore) +} + +// SetRandomStringLength sets a length for random string generation +func SetRandomStringLength(size int) error { + if size < 0 { + return fmt.Errorf(fakerErrors.ErrSmallerThanZero, size) + } + atomic.StoreInt32(&randomStringLen, int32(size)) + return nil +} + +// SetStringLang sets language of random string generation (LangENG, LangCHI, LangRUS, LangJPN, LangKOR, EmotEMJ) +func SetStringLang(l interfaces.LangRuneBoundary) { + atomic.StorePointer(&lang, unsafe.Pointer(&l)) +} + +// SetRandomMapAndSliceSize sets the size for maps and slices for random generation. +// deprecates, currently left for old version usage +func SetRandomMapAndSliceSize(size int) error { + return SetRandomMapAndSliceMaxSize(size) +} + +// SetRandomMapAndSliceMaxSize sets the max size for maps and slices for random generation. +func SetRandomMapAndSliceMaxSize(size int) error { + if size < 1 { + return fmt.Errorf(fakerErrors.ErrSmallerThanOne, size) + } + atomic.StoreInt32(&randomMaxSize, int32(size)) + return nil +} + +// SetRandomMapAndSliceMinSize sets the min size for maps and slices for random generation. +func SetRandomMapAndSliceMinSize(size int) error { + if size < 0 { + return fmt.Errorf(fakerErrors.ErrSmallerThanZero, size) + } + atomic.StoreInt32(&randomMinSize, int32(size)) + return nil +} + +// SetRandomNumberBoundaries sets boundary for random number generation +func SetRandomNumberBoundaries(start, end int) error { + if start > end { + return errors.New(fakerErrors.ErrStartValueBiggerThanEnd) + } + ptr := &interfaces.RandomIntegerBoundary{Start: start, End: end} + atomic.StorePointer(&iBoundary, unsafe.Pointer(ptr)) + return nil +} diff --git a/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go b/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go new file mode 100644 index 0000000..a596667 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/pkg/slice/helpers.go @@ -0,0 +1,30 @@ +package slice + +import ( + "slices" + "strconv" +) + +// Contains Check item in slice string type +func Contains(slice []string, item string) bool { + return slices.Contains(slice, item) +} + +// ContainsRune Check item in map rune type +func ContainsRune(set map[rune]struct{}, item rune) bool { + _, ok := set[item] + return ok +} + +// ContainsValue check if value exists in slice, no matter its type +func ContainsValue(slice []any, value any) bool { + return slices.Contains(slice, value) +} + +// IntToString Convert slice int to slice string +func IntToString(intSl []int) (str []string) { + for _, number := range intSl { + str = append(str, strconv.Itoa(number)) + } + return str +} diff --git a/vendor/github.com/go-faker/faker/v4/price.go b/vendor/github.com/go-faker/faker/v4/price.go new file mode 100644 index 0000000..60fc159 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/price.go @@ -0,0 +1,107 @@ +package faker + +import ( + "fmt" + "math" + "reflect" + + "github.com/go-faker/faker/v4/pkg/options" +) + +// Currency Codes | Source: https://en.wikipedia.org/wiki/ISO_4217 +var currencies = []string{ + "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", + "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", + "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", + "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", + "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", + "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", + "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", + "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", + "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", + "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", + "MGA", "MKD", "MMK", "MNT", "MOP", "MRU", "MUR", "MVR", "MWK", + "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", + "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", + "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", + "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STN", "SVC", + "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", + "TWD", "TZS", "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UYW", + "UZS", "VES", "VND", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", + "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", + "XSU", "XTS", "XUA", "XXX", "YER", "ZAR", "ZMW", "ZWL", +} + +// Money provides an interface to generate a custom price with or without a random currency code +type Money interface { + Currency(v reflect.Value) (any, error) + Amount(v reflect.Value) (any, error) + AmountWithCurrency(v reflect.Value) (any, error) +} + +// Price struct +type Price struct { +} + +// GetPrice returns a new Money interface of Price struct +func GetPrice() Money { + return &Price{} +} + +func (p Price) currency() string { + return randomElementFromSliceString(currencies) +} + +// Currency returns a random currency from currencies +func (p Price) Currency(v reflect.Value) (any, error) { + return p.currency(), nil +} + +// Currency get fake Currency (IDR, USD) +func Currency(opts ...options.OptionFunc) string { + return singleFakeData(CurrencyTag, func() any { + p := Price{} + return p.currency() + }, opts...).(string) +} + +func (p Price) amount() float64 { + return precision(rand.Float64()*math.Pow10(rand.Intn(8)), rand.Intn(2)+1) +} + +// Amount returns a random floating price amount +// with a random precision of [1,2] up to (10**8 - 1) +func (p Price) Amount(v reflect.Value) (any, error) { + kind := v.Kind() + val := p.amount() + if kind == reflect.Float32 { + v.Set(reflect.ValueOf(float32(val))) + return float32(val), nil + } + v.Set(reflect.ValueOf(val)) + return val, nil +} + +func (p Price) amountwithcurrency() string { + val := p.amount() + return fmt.Sprintf("%s %f", p.currency(), val) +} + +// AmountWithCurrency combines both price and currency together +func (p Price) AmountWithCurrency(v reflect.Value) (any, error) { + return p.amountwithcurrency(), nil +} + +// AmountWithCurrency get fake AmountWithCurrency USD 49257.100 +func AmountWithCurrency(opts ...options.OptionFunc) string { + return singleFakeData(AmountWithCurrencyTag, func() any { + p := Price{} + return p.amountwithcurrency() + }, opts...).(string) +} + +// precision | a helper function to set precision of price +func precision(val float64, pre int) float64 { + div := math.Pow10(pre) + return float64(int64(val*div)) / div +} diff --git a/vendor/github.com/go-faker/faker/v4/random_source.go b/vendor/github.com/go-faker/faker/v4/random_source.go new file mode 100644 index 0000000..96b7a15 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/random_source.go @@ -0,0 +1,49 @@ +package faker + +import ( + "io" + mathrand "math/rand" + "sync" +) + +var ( + rand *mathrand.Rand + crypto io.Reader +) + +type safeSource struct { + mx sync.Mutex + mathrand.Source +} + +func (s *safeSource) Int63() int64 { + s.mx.Lock() + defer s.mx.Unlock() + + return s.Source.Int63() +} + +// NewSafeSource wraps an unsafe rand.Source with a mutex to guard the random source +// against concurrent access. +func NewSafeSource(in mathrand.Source) mathrand.Source { + return &safeSource{ + Source: in, + } +} + +// SetRandomSource sets a new random source at the package level. +// +// To use a concurrent-safe source, you may wrap it with NewSafeSource, +// e.g. SetRandomSource(NewSafeSource(mysource)). +// +// The default is the global, concurrent-safe source provided by math/rand. +func SetRandomSource(in mathrand.Source) { + rand = mathrand.New(in) +} + +// SetCryptoSource sets a new reader for functions using a cryptographically-safe random generator (e.g. UUID). +// +// The default is the global source provided by crypto/rand. +func SetCryptoSource(in io.Reader) { + crypto = in +} diff --git a/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go b/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go new file mode 100644 index 0000000..55774a0 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/tag_argument_extractor.go @@ -0,0 +1,189 @@ +package faker + +import ( + "fmt" + "strconv" + "strings" + + fakerErrors "github.com/go-faker/faker/v4/pkg/errors" +) + +func extractFloat64FromTagArgs(args []string) (any, error) { + bytes := 64 + var floatValues []float64 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseFloat(k, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, j) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractFloat32FromTagArgs(args []string) (any, error) { + bytes := 32 + var floatValues []float32 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseFloat(k, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, float32(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractInt64FromTagArgs(args []string) (any, error) { + bytes := 64 + var floatValues []int64 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseInt(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, j) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractInt32FromTagArgs(args []string) (any, error) { + bytes := 32 + var floatValues []int32 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseInt(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, int32(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractInt16FromTagArgs(args []string) (any, error) { + bytes := 16 + var floatValues []int16 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseInt(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, int16(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractInt8FromTagArgs(args []string) (any, error) { + bytes := 8 + var floatValues []int8 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseInt(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, int8(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractIntFromTagArgs(args []string) (any, error) { + bytes := 0 + var floatValues []int + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseInt(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, int(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractUint64FromTagArgs(args []string) (any, error) { + bytes := 64 + var floatValues []uint64 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseUint(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, j) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractUint32FromTagArgs(args []string) (any, error) { + bytes := 32 + var floatValues []uint32 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseUint(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, uint32(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractUint16FromTagArgs(args []string) (any, error) { + bytes := 16 + var floatValues []uint16 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseUint(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, uint16(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractUint8FromTagArgs(args []string) (any, error) { + bytes := 8 + var floatValues []uint8 + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseUint(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, uint8(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} + +func extractUintFromTagArgs(args []string) (any, error) { + bytes := 0 + var floatValues []uint + for _, i := range args { + k := strings.TrimSpace(i) + j, err := strconv.ParseUint(k, 10, bytes) + if err != nil { + return nil, fmt.Errorf("%s", fakerErrors.ErrUnsupportedTagArguments) + } + floatValues = append(floatValues, uint(j)) + } + toRet := floatValues[rand.Intn(len(floatValues))] + return toRet, nil +} diff --git a/vendor/github.com/go-faker/faker/v4/template_tag.go b/vendor/github.com/go-faker/faker/v4/template_tag.go new file mode 100644 index 0000000..4256e08 --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/template_tag.go @@ -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(), "-") +} diff --git a/vendor/github.com/go-faker/faker/v4/user_agent.go b/vendor/github.com/go-faker/faker/v4/user_agent.go new file mode 100644 index 0000000..6b5d2eb --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/user_agent.go @@ -0,0 +1,192 @@ +package faker + +import ( + "fmt" + "reflect" + "time" + + "github.com/go-faker/faker/v4/pkg/interfaces" +) + +var ( + browserTypes = []string{"chrome", "firefox", "internetExplorer", "msedge", "opera", "safari"} + windowsPlatformTokens = []string{"Windows NT 6.2", "Windows NT 6.1", "Windows NT 6.0", "Windows NT 5.2", + "Windows NT 5.1", "Windows NT 5.01", "Windows NT 5.0", "Windows NT 4.0", "Windows 98; Win 9x 4.90", + "Windows 98", "Windows 95", "Windows CE", + } + linuxProcessor = []string{"i686", "x86_64"} + macProcessor = []string{"Intel", "PPC", "U; Intel", "U; PPC"} + // langCodes contains language codes extracted from https://gist.github.com/JamieMason/3748498. + langCodes = []string{"af-ZA", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-LY", + "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SY", "ar-TN", "ar-YE", "be-BY", "bg-BG", "ca-ES", "cs-CZ", "cy-GB", + "da-DK", "de-AT", "de-DE", "de-CH", "de-LI", "de-LU", "dv-MV", "el-GR", "en-AU", "en-BZ", "en-CA", "en-GB", + "en-IE", "en-JM", "en-NZ", "en-PH", "en-TT", "en-US", "en-ZA", "en-ZW", "es-AR", "es-BO", "es-CL", "es-CO", + "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", + "es-SV", "es-UY", "es-VE", "et-EE", "eu-ES", "fa-IR", "fi-FI", "fo-FO", "fr-BE", "fr-CA", "fr-FR", "fr-CH", + "fr-LU", "fr-MC", "gl-ES", "gu-IN", "he-IL", "hi-IN", "hr-BA", "hr-HR", "hu-HU", "hy-AM", "id-ID", "is-IS", + "it-CH", "it-IT", "ja-JP", "ka-GE", "kk-KZ", "kn-IN", "ko-KR", "ky-KG", "lt-LT", "lv-LV", "mi-NZ", "mk-MK", + "mn-MN", "mr-IN", "ms-BN", "ms-MY", "mt-MT", "nb-NO", "nl-BE", "nl-NL", "nn-NO", "ns-ZA", "pa-IN", "pl-PL", + "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sa-IN", "se-FI", "se-NO", "se-SE", "sk-SK", "sl-SI", "sq-AL", "sv-FI", + "sv-SE", "sw-KE", "ta-IN", "te-IN", "th-TH", "tn-ZA", "tr-TR", "tt-RU", "uk-UA", "ur-PK", "vi-VN", "xh-ZA", + "zh-CN", "zh-HK", "zh-MO", "zh-SG", "zh-TW", "zu-ZA", + } +) + +func GetUserAgent() UserAgenter { + ua := &UserAgent{} + return ua +} + +type UserAgenter interface { + UserAgent(v reflect.Value) (any, error) +} + +// UserAgent implements logic loosely based on https://fakerphp.org/formatters/user-agent/. +type UserAgent struct{} + +func (ua UserAgent) UserAgent(reflect.Value) (any, error) { + browserType := randomElementFromSliceString(browserTypes) + switch browserType { + case "chrome": + return ua.chrome(), nil + case "firefox": + return ua.firefox(), nil + case "internetExplorer": + return ua.internetExplorer(), nil + case "msedge": + return ua.msEdge(), nil + case "opera": + return ua.opera(), nil + case "safari": + return ua.safari(), nil + } + return nil, fmt.Errorf(`unknown browser type: "%s"`, browserType) +} + +// chrome generates a user agent string that resembles Google Chrome. +// Example: "Mozilla/5.0 (X11; Linux i686) AppleWebKit/532.2 (KHTML, like Gecko) Chrome/69.0.3460.334 Safari/532.2" +func (ua UserAgent) chrome() string { + chromeVer := fmt.Sprintf("%d.0.%d.%d", + ua.intBetween(36, 127), ua.intBetween(0, 6000), ua.intBetween(0, 400), + ) + platformToken := randomElementFromSliceString([]string{ + ua.linuxPlatformToken(), + ua.macPlatformToken("_"), + ua.windowsPlatformToken(), + }) + safariType := randomElementFromSliceString([]string{"Safari", "Mobile Safari"}) + webKitVer := ua.webKitVersion(false) + return fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/%s (KHTML, like Gecko) Chrome/%s %s/%s", + platformToken, webKitVer, chromeVer, safariType, webKitVer, + ) +} + +// firefox generates a user agent string that resembles Firefox. +// Example: "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20130219 Firefox/58.0" +func (ua UserAgent) firefox() string { + firefoxVer := fmt.Sprintf("%d.0", ua.intBetween(35, 129)) + platformToken := randomElementFromSliceString([]string{ + ua.linuxPlatformToken(), + ua.macPlatformToken("."), + ua.windowsPlatformToken(), + }) + return fmt.Sprintf("Mozilla/5.0 (%s; rv:%s) Gecko/%s Firefox/%s", + platformToken, firefoxVer, ua.geckoVersion(), firefoxVer, + ) +} + +// internetExplorer generates a user agent string that resembles Internet Explorer +// Example: "Mozilla/5.0 (compatible; MSIE 9.0; Windows 98; Win 9x 4.90; Trident/5.0)" +func (ua UserAgent) internetExplorer() string { + return fmt.Sprintf("Mozilla/5.0 (compatible; MSIE %d.0; %s; Trident/%d.0)", + ua.intBetween(5, 11), ua.windowsPlatformToken(), ua.intBetween(3, 7), + ) +} + +// msEdge generates a user agent string that resembles MS Edge +// Example: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/533.0 (KHTML, like Gecko) Chrome/86.0.4685.32 Safari/533.0 Edg/86.0.4685.32" +func (ua UserAgent) msEdge() string { + webKitVer := ua.webKitVersion(false) + chromiumVer := fmt.Sprintf("%d.0.%d.%d", ua.intBetween(79, 99), ua.intBetween(4000, 4844), ua.intBetween(10, 99)) + platformToken := randomElementFromSliceString([]string{ + ua.linuxPlatformToken(), + ua.windowsPlatformToken(), + ua.macPlatformToken("_"), + }) + return fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/%s (KHTML, like Gecko) Chrome/%s Safari/%s Edg/%s", + platformToken, webKitVer, chromiumVer, webKitVer, chromiumVer, + ) +} + +// opera generates a user agent string that resembles Opera. +// Example: "Opera/8.40 (X11; Linux i686; zh-TW) Presto/2.12.181 Version/10.57" +func (ua UserAgent) opera() string { + platformToken := randomElementFromSliceString([]string{ + ua.linuxPlatformToken(), + ua.windowsPlatformToken(), + }) + operaVer := fmt.Sprintf("%d.%d", ua.intBetween(8, 9), ua.intBetween(10, 99)) + prestoVer := fmt.Sprintf("2.%d.%d", ua.intBetween(8, 12), ua.intBetween(160, 355)) + ver := fmt.Sprintf("%d.%d", ua.intBetween(10, 12), ua.intBetween(0, 70)) + return fmt.Sprintf("Opera/%s (%s; %s) Presto/%s Version/%s", + operaVer, platformToken, randomElementFromSliceString(langCodes), prestoVer, ver, + ) +} + +// safari generates a user agent string that resembles Safari. +// Example: "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_7_3; bg-BG) AppleWebKit/548.43.16 (KHTML, like Gecko) Version/7.5 Safari/548.43.16" +func (ua UserAgent) safari() string { + webKitVer := ua.webKitVersion(true) + safariVer := fmt.Sprintf("%d.%d", ua.intBetween(4, 17), ua.intBetween(0, 5)) + if ua.intBetween(0, 100) < 50 { + safariVer = fmt.Sprintf("%s.%d", safariVer, ua.intBetween(1, 20)) + } + platform := randomElementFromSliceString([]string{ + fmt.Sprintf("Windows; U; %s; %s", ua.windowsPlatformToken(), randomElementFromSliceString(langCodes)), + fmt.Sprintf("%s; %s", ua.macPlatformToken("_"), randomElementFromSliceString(langCodes)), + }) + + return fmt.Sprintf("Mozilla/5.0 (%s) AppleWebKit/%s (KHTML, like Gecko) Version/%s Safari/%s", + platform, webKitVer, safariVer, webKitVer, + ) +} + +func (ua UserAgent) linuxPlatformToken() string { + return fmt.Sprintf("X11; Linux %s", randomElementFromSliceString(linuxProcessor)) +} + +func (ua UserAgent) macPlatformToken(sep string) string { + return fmt.Sprintf("Macintosh; %s Mac OS X %d%s%d%s%d", + randomElementFromSliceString(macProcessor), ua.intBetween(10, 17), sep, ua.intBetween(5, 8), sep, ua.intBetween(0, 9), + ) +} + +func (ua UserAgent) windowsPlatformToken() string { + return randomElementFromSliceString(windowsPlatformTokens) +} + +// webKitVersion generates a random string that resembles an AppleWebKit version string. +func (ua UserAgent) webKitVersion(withPatchVer bool) string { + majorVer := ua.intBetween(531, 618) + if withPatchVer { + return fmt.Sprintf("%d.%d.%d", majorVer, ua.intBetween(1, 50), ua.intBetween(1, 20)) + } + return fmt.Sprintf("%d.%d", majorVer, ua.intBetween(0, 10)) +} + +// geckoVersion generates a random string that resembles a Gecko version string. +func (ua UserAgent) geckoVersion() string { + const YYYYMMDD = "20060102" + minDate := time.Date(2010, 1, 1, 0, 0, 0, 0, time.UTC) + maxDate := time.Now() + randDuration := time.Duration(rand.Int63n(maxDate.Unix()-minDate.Unix())) * time.Second + return minDate.Add(randDuration).Format(YYYYMMDD) +} + +// intBetween generates a random integer in the range [min, max]. +// +//nolint:revive +func (ua UserAgent) intBetween(min, max int) int { + boundary := interfaces.RandomIntegerBoundary{Start: min, End: max + 1} + return randomIntegerWithBoundary(boundary) +} diff --git a/vendor/github.com/go-faker/faker/v4/uuid.go b/vendor/github.com/go-faker/faker/v4/uuid.go new file mode 100644 index 0000000..d31509d --- /dev/null +++ b/vendor/github.com/go-faker/faker/v4/uuid.go @@ -0,0 +1,83 @@ +package faker + +import ( + "fmt" + "io" + "reflect" + + "github.com/go-faker/faker/v4/pkg/options" +) + +// GetIdentifier returns a new Identifier +func GetIdentifier() Identifier { + return &UUID{} +} + +// Identifier ... +type Identifier interface { + Digit(v reflect.Value) (any, error) + Hyphenated(v reflect.Value) (any, error) +} + +// UUID struct +type UUID struct{} + +// createUUID returns a 16 byte slice with random values +func createUUID() ([]byte, error) { + b := make([]byte, 16) + _, err := io.ReadFull(crypto, b) + if err != nil { + return b, err + } + // variant bits; see section 4.1.1 + b[8] = b[8]&^0xc0 | 0x80 + // version 4 (pseudo-random); see section 4.1.3 + b[6] = b[6]&^0xf0 | 0x40 + return b, nil +} + +func (u UUID) hyphenated() (string, error) { + b, err := createUUID() + if err != nil { + return "", err + } + uuid := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) + return uuid, err +} + +// Hyphenated returns a 36 byte hyphenated UUID +func (u UUID) Hyphenated(v reflect.Value) (any, error) { + return u.hyphenated() +} + +// UUIDHyphenated get fake Hyphenated UUID +func UUIDHyphenated(opts ...options.OptionFunc) string { + return singleFakeData(HyphenatedID, func() any { + u := UUID{} + res, _ := u.hyphenated() + return res + }, opts...).(string) +} + +func (u UUID) digit() (string, error) { + b, err := createUUID() + if err != nil { + return "", err + } + uuid := fmt.Sprintf("%x", b) + return uuid, err +} + +// Digit returns a 32 bytes UUID +func (u UUID) Digit(v reflect.Value) (any, error) { + return u.digit() +} + +// UUIDDigit get fake Digit UUID +func UUIDDigit(opts ...options.OptionFunc) string { + return singleFakeData(ID, func() any { + u := UUID{} + res, _ := u.digit() + return res + }, opts...).(string) +} diff --git a/vendor/github.com/go-logr/logr/.golangci.yaml b/vendor/github.com/go-logr/logr/.golangci.yaml new file mode 100644 index 0000000..0ed62c1 --- /dev/null +++ b/vendor/github.com/go-logr/logr/.golangci.yaml @@ -0,0 +1,28 @@ +version: "2" + +run: + timeout: 1m + tests: true + +linters: + default: none + enable: # please keep this alphabetized + - asasalint + - asciicheck + - copyloopvar + - dupl + - errcheck + - forcetypeassert + - goconst + - gocritic + - govet + - ineffassign + - misspell + - musttag + - revive + - staticcheck + - unused + +issues: + max-issues-per-linter: 0 + max-same-issues: 10 diff --git a/vendor/github.com/go-logr/logr/CHANGELOG.md b/vendor/github.com/go-logr/logr/CHANGELOG.md new file mode 100644 index 0000000..c356960 --- /dev/null +++ b/vendor/github.com/go-logr/logr/CHANGELOG.md @@ -0,0 +1,6 @@ +# CHANGELOG + +## v1.0.0-rc1 + +This is the first logged release. Major changes (including breaking changes) +have occurred since earlier tags. diff --git a/vendor/github.com/go-logr/logr/CONTRIBUTING.md b/vendor/github.com/go-logr/logr/CONTRIBUTING.md new file mode 100644 index 0000000..5d37e29 --- /dev/null +++ b/vendor/github.com/go-logr/logr/CONTRIBUTING.md @@ -0,0 +1,17 @@ +# Contributing + +Logr is open to pull-requests, provided they fit within the intended scope of +the project. Specifically, this library aims to be VERY small and minimalist, +with no external dependencies. + +## Compatibility + +This project intends to follow [semantic versioning](http://semver.org) and +is very strict about compatibility. Any proposed changes MUST follow those +rules. + +## Performance + +As a logging library, logr must be as light-weight as possible. Any proposed +code change must include results of running the [benchmark](./benchmark) +before and after the change. diff --git a/vendor/github.com/go-logr/logr/LICENSE b/vendor/github.com/go-logr/logr/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/vendor/github.com/go-logr/logr/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-logr/logr/README.md b/vendor/github.com/go-logr/logr/README.md new file mode 100644 index 0000000..7c7f0c6 --- /dev/null +++ b/vendor/github.com/go-logr/logr/README.md @@ -0,0 +1,407 @@ +# A minimal logging API for Go + +[![Go Reference](https://pkg.go.dev/badge/github.com/go-logr/logr.svg)](https://pkg.go.dev/github.com/go-logr/logr) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-logr/logr)](https://goreportcard.com/report/github.com/go-logr/logr) +[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/go-logr/logr/badge)](https://securityscorecards.dev/viewer/?platform=github.com&org=go-logr&repo=logr) + +logr offers an(other) opinion on how Go programs and libraries can do logging +without becoming coupled to a particular logging implementation. This is not +an implementation of logging - it is an API. In fact it is two APIs with two +different sets of users. + +The `Logger` type is intended for application and library authors. It provides +a relatively small API which can be used everywhere you want to emit logs. It +defers the actual act of writing logs (to files, to stdout, or whatever) to the +`LogSink` interface. + +The `LogSink` interface is intended for logging library implementers. It is a +pure interface which can be implemented by logging frameworks to provide the actual logging +functionality. + +This decoupling allows application and library developers to write code in +terms of `logr.Logger` (which has very low dependency fan-out) while the +implementation of logging is managed "up stack" (e.g. in or near `main()`.) +Application developers can then switch out implementations as necessary. + +Many people assert that libraries should not be logging, and as such efforts +like this are pointless. Those people are welcome to convince the authors of +the tens-of-thousands of libraries that *DO* write logs that they are all +wrong. In the meantime, logr takes a more practical approach. + +## Typical usage + +Somewhere, early in an application's life, it will make a decision about which +logging library (implementation) it actually wants to use. Something like: + +``` + func main() { + // ... other setup code ... + + // Create the "root" logger. We have chosen the "logimpl" implementation, + // which takes some initial parameters and returns a logr.Logger. + logger := logimpl.New(param1, param2) + + // ... other setup code ... +``` + +Most apps will call into other libraries, create structures to govern the flow, +etc. The `logr.Logger` object can be passed to these other libraries, stored +in structs, or even used as a package-global variable, if needed. For example: + +``` + app := createTheAppObject(logger) + app.Run() +``` + +Outside of this early setup, no other packages need to know about the choice of +implementation. They write logs in terms of the `logr.Logger` that they +received: + +``` + type appObject struct { + // ... other fields ... + logger logr.Logger + // ... other fields ... + } + + func (app *appObject) Run() { + app.logger.Info("starting up", "timestamp", time.Now()) + + // ... app code ... +``` + +## Background + +If the Go standard library had defined an interface for logging, this project +probably would not be needed. Alas, here we are. + +When the Go developers started developing such an interface with +[slog](https://github.com/golang/go/issues/56345), they adopted some of the +logr design but also left out some parts and changed others: + +| Feature | logr | slog | +|---------|------|------| +| High-level API | `Logger` (passed by value) | `Logger` (passed by [pointer](https://github.com/golang/go/issues/59126)) | +| Low-level API | `LogSink` | `Handler` | +| Stack unwinding | done by `LogSink` | done by `Logger` | +| Skipping helper functions | `WithCallDepth`, `WithCallStackHelper` | [not supported by Logger](https://github.com/golang/go/issues/59145) | +| Generating a value for logging on demand | `Marshaler` | `LogValuer` | +| Log levels | >= 0, higher meaning "less important" | positive and negative, with 0 for "info" and higher meaning "more important" | +| Error log entries | always logged, don't have a verbosity level | normal log entries with level >= `LevelError` | +| Passing logger via context | `NewContext`, `FromContext` | no API | +| Adding a name to a logger | `WithName` | no API | +| Modify verbosity of log entries in a call chain | `V` | no API | +| Grouping of key/value pairs | not supported | `WithGroup`, `GroupValue` | +| Pass context for extracting additional values | no API | API variants like `InfoCtx` | + +The high-level slog API is explicitly meant to be one of many different APIs +that can be layered on top of a shared `slog.Handler`. logr is one such +alternative API, with [interoperability](#slog-interoperability) provided by +some conversion functions. + +### Inspiration + +Before you consider this package, please read [this blog post by the +inimitable Dave Cheney][warning-makes-no-sense]. We really appreciate what +he has to say, and it largely aligns with our own experiences. + +### Differences from Dave's ideas + +The main differences are: + +1. Dave basically proposes doing away with the notion of a logging API in favor +of `fmt.Printf()`. We disagree, especially when you consider things like output +locations, timestamps, file and line decorations, and structured logging. This +package restricts the logging API to just 2 types of logs: info and error. + +Info logs are things you want to tell the user which are not errors. Error +logs are, well, errors. If your code receives an `error` from a subordinate +function call and is logging that `error` *and not returning it*, use error +logs. + +2. Verbosity-levels on info logs. This gives developers a chance to indicate +arbitrary grades of importance for info logs, without assigning names with +semantic meaning such as "warning", "trace", and "debug." Superficially this +may feel very similar, but the primary difference is the lack of semantics. +Because verbosity is a numerical value, it's safe to assume that an app running +with higher verbosity means more (and less important) logs will be generated. + +## Implementations (non-exhaustive) + +There are implementations for the following logging libraries: + +- **a function** (can bridge to non-structured libraries): [funcr](https://github.com/go-logr/logr/tree/master/funcr) +- **a testing.T** (for use in Go tests, with JSON-like output): [testr](https://github.com/go-logr/logr/tree/master/testr) +- **github.com/google/glog**: [glogr](https://github.com/go-logr/glogr) +- **k8s.io/klog** (for Kubernetes): [klogr](https://git.k8s.io/klog/klogr) +- **a testing.T** (with klog-like text output): [ktesting](https://git.k8s.io/klog/ktesting) +- **go.uber.org/zap**: [zapr](https://github.com/go-logr/zapr) +- **log** (the Go standard library logger): [stdr](https://github.com/go-logr/stdr) +- **github.com/sirupsen/logrus**: [logrusr](https://github.com/bombsimon/logrusr) +- **github.com/wojas/genericr**: [genericr](https://github.com/wojas/genericr) (makes it easy to implement your own backend) +- **logfmt** (Heroku style [logging](https://www.brandur.org/logfmt)): [logfmtr](https://github.com/iand/logfmtr) +- **github.com/rs/zerolog**: [zerologr](https://github.com/go-logr/zerologr) +- **github.com/go-kit/log**: [gokitlogr](https://github.com/tonglil/gokitlogr) (also compatible with github.com/go-kit/kit/log since v0.12.0) +- **bytes.Buffer** (writing to a buffer): [bufrlogr](https://github.com/tonglil/buflogr) (useful for ensuring values were logged, like during testing) + +## slog interoperability + +Interoperability goes both ways, using the `logr.Logger` API with a `slog.Handler` +and using the `slog.Logger` API with a `logr.LogSink`. `FromSlogHandler` and +`ToSlogHandler` convert between a `logr.Logger` and a `slog.Handler`. +As usual, `slog.New` can be used to wrap such a `slog.Handler` in the high-level +slog API. + +### Using a `logr.LogSink` as backend for slog + +Ideally, a logr sink implementation should support both logr and slog by +implementing both the normal logr interface(s) and `SlogSink`. Because +of a conflict in the parameters of the common `Enabled` method, it is [not +possible to implement both slog.Handler and logr.Sink in the same +type](https://github.com/golang/go/issues/59110). + +If both are supported, log calls can go from the high-level APIs to the backend +without the need to convert parameters. `FromSlogHandler` and `ToSlogHandler` can +convert back and forth without adding additional wrappers, with one exception: +when `Logger.V` was used to adjust the verbosity for a `slog.Handler`, then +`ToSlogHandler` has to use a wrapper which adjusts the verbosity for future +log calls. + +Such an implementation should also support values that implement specific +interfaces from both packages for logging (`logr.Marshaler`, `slog.LogValuer`, +`slog.GroupValue`). logr does not convert those. + +Not supporting slog has several drawbacks: +- Recording source code locations works correctly if the handler gets called + through `slog.Logger`, but may be wrong in other cases. That's because a + `logr.Sink` does its own stack unwinding instead of using the program counter + provided by the high-level API. +- slog levels <= 0 can be mapped to logr levels by negating the level without a + loss of information. But all slog levels > 0 (e.g. `slog.LevelWarning` as + used by `slog.Logger.Warn`) must be mapped to 0 before calling the sink + because logr does not support "more important than info" levels. +- The slog group concept is supported by prefixing each key in a key/value + pair with the group names, separated by a dot. For structured output like + JSON it would be better to group the key/value pairs inside an object. +- Special slog values and interfaces don't work as expected. +- The overhead is likely to be higher. + +These drawbacks are severe enough that applications using a mixture of slog and +logr should switch to a different backend. + +### Using a `slog.Handler` as backend for logr + +Using a plain `slog.Handler` without support for logr works better than the +other direction: +- All logr verbosity levels can be mapped 1:1 to their corresponding slog level + by negating them. +- Stack unwinding is done by the `SlogSink` and the resulting program + counter is passed to the `slog.Handler`. +- Names added via `Logger.WithName` are gathered and recorded in an additional + attribute with `logger` as key and the names separated by slash as value. +- `Logger.Error` is turned into a log record with `slog.LevelError` as level + and an additional attribute with `err` as key, if an error was provided. + +The main drawback is that `logr.Marshaler` will not be supported. Types should +ideally support both `logr.Marshaler` and `slog.Valuer`. If compatibility +with logr implementations without slog support is not important, then +`slog.Valuer` is sufficient. + +### Context support for slog + +Storing a logger in a `context.Context` is not supported by +slog. `NewContextWithSlogLogger` and `FromContextAsSlogLogger` can be +used to fill this gap. They store and retrieve a `slog.Logger` pointer +under the same context key that is also used by `NewContext` and +`FromContext` for `logr.Logger` value. + +When `NewContextWithSlogLogger` is followed by `FromContext`, the latter will +automatically convert the `slog.Logger` to a +`logr.Logger`. `FromContextAsSlogLogger` does the same for the other direction. + +With this approach, binaries which use either slog or logr are as efficient as +possible with no unnecessary allocations. This is also why the API stores a +`slog.Logger` pointer: when storing a `slog.Handler`, creating a `slog.Logger` +on retrieval would need to allocate one. + +The downside is that switching back and forth needs more allocations. Because +logr is the API that is already in use by different packages, in particular +Kubernetes, the recommendation is to use the `logr.Logger` API in code which +uses contextual logging. + +An alternative to adding values to a logger and storing that logger in the +context is to store the values in the context and to configure a logging +backend to extract those values when emitting log entries. This only works when +log calls are passed the context, which is not supported by the logr API. + +With the slog API, it is possible, but not +required. https://github.com/veqryn/slog-context is a package for slog which +provides additional support code for this approach. It also contains wrappers +for the context functions in logr, so developers who prefer to not use the logr +APIs directly can use those instead and the resulting code will still be +interoperable with logr. + +## FAQ + +### Conceptual + +#### Why structured logging? + +- **Structured logs are more easily queryable**: Since you've got + key-value pairs, it's much easier to query your structured logs for + particular values by filtering on the contents of a particular key -- + think searching request logs for error codes, Kubernetes reconcilers for + the name and namespace of the reconciled object, etc. + +- **Structured logging makes it easier to have cross-referenceable logs**: + Similarly to searchability, if you maintain conventions around your + keys, it becomes easy to gather all log lines related to a particular + concept. + +- **Structured logs allow better dimensions of filtering**: if you have + structure to your logs, you've got more precise control over how much + information is logged -- you might choose in a particular configuration + to log certain keys but not others, only log lines where a certain key + matches a certain value, etc., instead of just having v-levels and names + to key off of. + +- **Structured logs better represent structured data**: sometimes, the + data that you want to log is inherently structured (think tuple-link + objects.) Structured logs allow you to preserve that structure when + outputting. + +#### Why V-levels? + +**V-levels give operators an easy way to control the chattiness of log +operations**. V-levels provide a way for a given package to distinguish +the relative importance or verbosity of a given log message. Then, if +a particular logger or package is logging too many messages, the user +of the package can simply change the v-levels for that library. + +#### Why not named levels, like Info/Warning/Error? + +Read [Dave Cheney's post][warning-makes-no-sense]. Then read [Differences +from Dave's ideas](#differences-from-daves-ideas). + +#### Why not allow format strings, too? + +**Format strings negate many of the benefits of structured logs**: + +- They're not easily searchable without resorting to fuzzy searching, + regular expressions, etc. + +- They don't store structured data well, since contents are flattened into + a string. + +- They're not cross-referenceable. + +- They don't compress easily, since the message is not constant. + +(Unless you turn positional parameters into key-value pairs with numerical +keys, at which point you've gotten key-value logging with meaningless +keys.) + +### Practical + +#### Why key-value pairs, and not a map? + +Key-value pairs are *much* easier to optimize, especially around +allocations. Zap (a structured logger that inspired logr's interface) has +[performance measurements](https://github.com/uber-go/zap#performance) +that show this quite nicely. + +While the interface ends up being a little less obvious, you get +potentially better performance, plus avoid making users type +`map[string]string{}` every time they want to log. + +#### What if my V-levels differ between libraries? + +That's fine. Control your V-levels on a per-logger basis, and use the +`WithName` method to pass different loggers to different libraries. + +Generally, you should take care to ensure that you have relatively +consistent V-levels within a given logger, however, as this makes deciding +on what verbosity of logs to request easier. + +#### But I really want to use a format string! + +That's not actually a question. Assuming your question is "how do +I convert my mental model of logging with format strings to logging with +constant messages": + +1. Figure out what the error actually is, as you'd write in a TL;DR style, + and use that as a message. + +2. For every place you'd write a format specifier, look to the word before + it, and add that as a key value pair. + +For instance, consider the following examples (all taken from spots in the +Kubernetes codebase): + +- `klog.V(4).Infof("Client is returning errors: code %v, error %v", + responseCode, err)` becomes `logger.Error(err, "client returned an + error", "code", responseCode)` + +- `klog.V(4).Infof("Got a Retry-After %ds response for attempt %d to %v", + seconds, retries, url)` becomes `logger.V(4).Info("got a retry-after + response when requesting url", "attempt", retries, "after + seconds", seconds, "url", url)` + +If you *really* must use a format string, use it in a key's value, and +call `fmt.Sprintf` yourself. For instance: `log.Printf("unable to +reflect over type %T")` becomes `logger.Info("unable to reflect over +type", "type", fmt.Sprintf("%T"))`. In general though, the cases where +this is necessary should be few and far between. + +#### How do I choose my V-levels? + +This is basically the only hard constraint: increase V-levels to denote +more verbose or more debug-y logs. + +Otherwise, you can start out with `0` as "you always want to see this", +`1` as "common logging that you might *possibly* want to turn off", and +`10` as "I would like to performance-test your log collection stack." + +Then gradually choose levels in between as you need them, working your way +down from 10 (for debug and trace style logs) and up from 1 (for chattier +info-type logs). For reference, slog pre-defines -4 for debug logs +(corresponds to 4 in logr), which matches what is +[recommended for Kubernetes](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md#what-method-to-use). + +#### How do I choose my keys? + +Keys are fairly flexible, and can hold more or less any string +value. For best compatibility with implementations and consistency +with existing code in other projects, there are a few conventions you +should consider. + +- Make your keys human-readable. +- Constant keys are generally a good idea. +- Be consistent across your codebase. +- Keys should naturally match parts of the message string. +- Use lower case for simple keys and + [lowerCamelCase](https://en.wiktionary.org/wiki/lowerCamelCase) for + more complex ones. Kubernetes is one example of a project that has + [adopted that + convention](https://github.com/kubernetes/community/blob/HEAD/contributors/devel/sig-instrumentation/migration-to-structured-logging.md#name-arguments). + +While key names are mostly unrestricted (and spaces are acceptable), +it's generally a good idea to stick to printable ascii characters, or at +least match the general character set of your log lines. + +#### Why should keys be constant values? + +The point of structured logging is to make later log processing easier. Your +keys are, effectively, the schema of each log message. If you use different +keys across instances of the same log line, you will make your structured logs +much harder to use. `Sprintf()` is for values, not for keys! + +#### Why is this not a pure interface? + +The Logger type is implemented as a struct in order to allow the Go compiler to +optimize things like high-V `Info` logs that are not triggered. Not all of +these implementations are implemented yet, but this structure was suggested as +a way to ensure they *can* be implemented. All of the real work is behind the +`LogSink` interface. + +[warning-makes-no-sense]: http://dave.cheney.net/2015/11/05/lets-talk-about-logging diff --git a/vendor/github.com/go-logr/logr/SECURITY.md b/vendor/github.com/go-logr/logr/SECURITY.md new file mode 100644 index 0000000..1ca756f --- /dev/null +++ b/vendor/github.com/go-logr/logr/SECURITY.md @@ -0,0 +1,18 @@ +# Security Policy + +If you have discovered a security vulnerability in this project, please report it +privately. **Do not disclose it as a public issue.** This gives us time to work with you +to fix the issue before public exposure, reducing the chance that the exploit will be +used before a patch is released. + +You may submit the report in the following ways: + +- send an email to go-logr-security@googlegroups.com +- send us a [private vulnerability report](https://github.com/go-logr/logr/security/advisories/new) + +Please provide the following information in your report: + +- A description of the vulnerability and its impact +- How to reproduce the issue + +We ask that you give us 90 days to work on a fix before public exposure. diff --git a/vendor/github.com/go-logr/logr/context.go b/vendor/github.com/go-logr/logr/context.go new file mode 100644 index 0000000..de8bcc3 --- /dev/null +++ b/vendor/github.com/go-logr/logr/context.go @@ -0,0 +1,33 @@ +/* +Copyright 2023 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +// contextKey is how we find Loggers in a context.Context. With Go < 1.21, +// the value is always a Logger value. With Go >= 1.21, the value can be a +// Logger value or a slog.Logger pointer. +type contextKey struct{} + +// notFoundError exists to carry an IsNotFound method. +type notFoundError struct{} + +func (notFoundError) Error() string { + return "no logr.Logger was present" +} + +func (notFoundError) IsNotFound() bool { + return true +} diff --git a/vendor/github.com/go-logr/logr/context_noslog.go b/vendor/github.com/go-logr/logr/context_noslog.go new file mode 100644 index 0000000..0a3d1a1 --- /dev/null +++ b/vendor/github.com/go-logr/logr/context_noslog.go @@ -0,0 +1,48 @@ +//go:build !go1.21 + +/* +Copyright 2019 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +import ( + "context" +) + +// FromContext returns a Logger from ctx or an error if no Logger is found. +func FromContext(ctx context.Context) (Logger, error) { + if v, ok := ctx.Value(contextKey{}).(Logger); ok { + return v, nil + } + + return Logger{}, notFoundError{} +} + +// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this +// returns a Logger that discards all log messages. +func FromContextOrDiscard(ctx context.Context) Logger { + if v, ok := ctx.Value(contextKey{}).(Logger); ok { + return v + } + + return Discard() +} + +// NewContext returns a new Context, derived from ctx, which carries the +// provided Logger. +func NewContext(ctx context.Context, logger Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} diff --git a/vendor/github.com/go-logr/logr/context_slog.go b/vendor/github.com/go-logr/logr/context_slog.go new file mode 100644 index 0000000..c69eb01 --- /dev/null +++ b/vendor/github.com/go-logr/logr/context_slog.go @@ -0,0 +1,82 @@ +//go:build go1.21 + +/* +Copyright 2019 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +import ( + "context" + "fmt" + "log/slog" +) + +// FromContext returns a Logger from ctx or an error if no Logger is found. +func FromContext(ctx context.Context) (Logger, error) { + v := ctx.Value(contextKey{}) + if v == nil { + return Logger{}, notFoundError{} + } + + switch v := v.(type) { + case Logger: + return v, nil + case *slog.Logger: + return FromSlogHandler(v.Handler()), nil + default: + // Not reached. + panic(fmt.Sprintf("unexpected value type for logr context key: %T", v)) + } +} + +// FromContextAsSlogLogger returns a slog.Logger from ctx or nil if no such Logger is found. +func FromContextAsSlogLogger(ctx context.Context) *slog.Logger { + v := ctx.Value(contextKey{}) + if v == nil { + return nil + } + + switch v := v.(type) { + case Logger: + return slog.New(ToSlogHandler(v)) + case *slog.Logger: + return v + default: + // Not reached. + panic(fmt.Sprintf("unexpected value type for logr context key: %T", v)) + } +} + +// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this +// returns a Logger that discards all log messages. +func FromContextOrDiscard(ctx context.Context) Logger { + if logger, err := FromContext(ctx); err == nil { + return logger + } + return Discard() +} + +// NewContext returns a new Context, derived from ctx, which carries the +// provided Logger. +func NewContext(ctx context.Context, logger Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} + +// NewContextWithSlogLogger returns a new Context, derived from ctx, which carries the +// provided slog.Logger. +func NewContextWithSlogLogger(ctx context.Context, logger *slog.Logger) context.Context { + return context.WithValue(ctx, contextKey{}, logger) +} diff --git a/vendor/github.com/go-logr/logr/discard.go b/vendor/github.com/go-logr/logr/discard.go new file mode 100644 index 0000000..99fe8be --- /dev/null +++ b/vendor/github.com/go-logr/logr/discard.go @@ -0,0 +1,24 @@ +/* +Copyright 2020 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +// Discard returns a Logger that discards all messages logged to it. It can be +// used whenever the caller is not interested in the logs. Logger instances +// produced by this function always compare as equal. +func Discard() Logger { + return New(nil) +} diff --git a/vendor/github.com/go-logr/logr/funcr/funcr.go b/vendor/github.com/go-logr/logr/funcr/funcr.go new file mode 100644 index 0000000..7f4996e --- /dev/null +++ b/vendor/github.com/go-logr/logr/funcr/funcr.go @@ -0,0 +1,939 @@ +/* +Copyright 2021 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package funcr implements formatting of structured log messages and +// optionally captures the call site and timestamp. +// +// The simplest way to use it is via its implementation of a +// github.com/go-logr/logr.LogSink with output through an arbitrary +// "write" function. See New and NewJSON for details. +// +// # Custom LogSinks +// +// For users who need more control, a funcr.Formatter can be embedded inside +// your own custom LogSink implementation. This is useful when the LogSink +// needs to implement additional methods, for example. +// +// # Formatting +// +// This will respect logr.Marshaler, fmt.Stringer, and error interfaces for +// values which are being logged. When rendering a struct, funcr will use Go's +// standard JSON tags (all except "string"). +package funcr + +import ( + "bytes" + "encoding" + "encoding/json" + "fmt" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "time" + + "github.com/go-logr/logr" +) + +// New returns a logr.Logger which is implemented by an arbitrary function. +func New(fn func(prefix, args string), opts Options) logr.Logger { + return logr.New(newSink(fn, NewFormatter(opts))) +} + +// NewJSON returns a logr.Logger which is implemented by an arbitrary function +// and produces JSON output. +func NewJSON(fn func(obj string), opts Options) logr.Logger { + fnWrapper := func(_, obj string) { + fn(obj) + } + return logr.New(newSink(fnWrapper, NewFormatterJSON(opts))) +} + +// Underlier exposes access to the underlying logging function. Since +// callers only have a logr.Logger, they have to know which +// implementation is in use, so this interface is less of an +// abstraction and more of a way to test type conversion. +type Underlier interface { + GetUnderlying() func(prefix, args string) +} + +func newSink(fn func(prefix, args string), formatter Formatter) logr.LogSink { + l := &fnlogger{ + Formatter: formatter, + write: fn, + } + // For skipping fnlogger.Info and fnlogger.Error. + l.AddCallDepth(1) // via Formatter + return l +} + +// Options carries parameters which influence the way logs are generated. +type Options struct { + // LogCaller tells funcr to add a "caller" key to some or all log lines. + // This has some overhead, so some users might not want it. + LogCaller MessageClass + + // LogCallerFunc tells funcr to also log the calling function name. This + // has no effect if caller logging is not enabled (see Options.LogCaller). + LogCallerFunc bool + + // LogTimestamp tells funcr to add a "ts" key to log lines. This has some + // overhead, so some users might not want it. + LogTimestamp bool + + // TimestampFormat tells funcr how to render timestamps when LogTimestamp + // is enabled. If not specified, a default format will be used. For more + // details, see docs for Go's time.Layout. + TimestampFormat string + + // LogInfoLevel tells funcr what key to use to log the info level. + // If not specified, the info level will be logged as "level". + // If this is set to "", the info level will not be logged at all. + LogInfoLevel *string + + // Verbosity tells funcr which V logs to produce. Higher values enable + // more logs. Info logs at or below this level will be written, while logs + // above this level will be discarded. + Verbosity int + + // RenderBuiltinsHook allows users to mutate the list of key-value pairs + // while a log line is being rendered. The kvList argument follows logr + // conventions - each pair of slice elements is comprised of a string key + // and an arbitrary value (verified and sanitized before calling this + // hook). The value returned must follow the same conventions. This hook + // can be used to audit or modify logged data. For example, you might want + // to prefix all of funcr's built-in keys with some string. This hook is + // only called for built-in (provided by funcr itself) key-value pairs. + // Equivalent hooks are offered for key-value pairs saved via + // logr.Logger.WithValues or Formatter.AddValues (see RenderValuesHook) and + // for user-provided pairs (see RenderArgsHook). + RenderBuiltinsHook func(kvList []any) []any + + // RenderValuesHook is the same as RenderBuiltinsHook, except that it is + // only called for key-value pairs saved via logr.Logger.WithValues. See + // RenderBuiltinsHook for more details. + RenderValuesHook func(kvList []any) []any + + // RenderArgsHook is the same as RenderBuiltinsHook, except that it is only + // called for key-value pairs passed directly to Info and Error. See + // RenderBuiltinsHook for more details. + RenderArgsHook func(kvList []any) []any + + // MaxLogDepth tells funcr how many levels of nested fields (e.g. a struct + // that contains a struct, etc.) it may log. Every time it finds a struct, + // slice, array, or map the depth is increased by one. When the maximum is + // reached, the value will be converted to a string indicating that the max + // depth has been exceeded. If this field is not specified, a default + // value will be used. + MaxLogDepth int +} + +// MessageClass indicates which category or categories of messages to consider. +type MessageClass int + +const ( + // None ignores all message classes. + None MessageClass = iota + // All considers all message classes. + All + // Info only considers info messages. + Info + // Error only considers error messages. + Error +) + +// fnlogger inherits some of its LogSink implementation from Formatter +// and just needs to add some glue code. +type fnlogger struct { + Formatter + write func(prefix, args string) +} + +func (l fnlogger) WithName(name string) logr.LogSink { + l.AddName(name) // via Formatter + return &l +} + +func (l fnlogger) WithValues(kvList ...any) logr.LogSink { + l.AddValues(kvList) // via Formatter + return &l +} + +func (l fnlogger) WithCallDepth(depth int) logr.LogSink { + l.AddCallDepth(depth) // via Formatter + return &l +} + +func (l fnlogger) Info(level int, msg string, kvList ...any) { + prefix, args := l.FormatInfo(level, msg, kvList) + l.write(prefix, args) +} + +func (l fnlogger) Error(err error, msg string, kvList ...any) { + prefix, args := l.FormatError(err, msg, kvList) + l.write(prefix, args) +} + +func (l fnlogger) GetUnderlying() func(prefix, args string) { + return l.write +} + +// Assert conformance to the interfaces. +var _ logr.LogSink = &fnlogger{} +var _ logr.CallDepthLogSink = &fnlogger{} +var _ Underlier = &fnlogger{} + +// NewFormatter constructs a Formatter which emits a JSON-like key=value format. +func NewFormatter(opts Options) Formatter { + return newFormatter(opts, outputKeyValue) +} + +// NewFormatterJSON constructs a Formatter which emits strict JSON. +func NewFormatterJSON(opts Options) Formatter { + return newFormatter(opts, outputJSON) +} + +// Defaults for Options. +const defaultTimestampFormat = "2006-01-02 15:04:05.000000" +const defaultMaxLogDepth = 16 + +func newFormatter(opts Options, outfmt outputFormat) Formatter { + if opts.TimestampFormat == "" { + opts.TimestampFormat = defaultTimestampFormat + } + if opts.MaxLogDepth == 0 { + opts.MaxLogDepth = defaultMaxLogDepth + } + if opts.LogInfoLevel == nil { + opts.LogInfoLevel = new(string) + *opts.LogInfoLevel = "level" + } + f := Formatter{ + outputFormat: outfmt, + prefix: "", + values: nil, + depth: 0, + opts: &opts, + } + return f +} + +// Formatter is an opaque struct which can be embedded in a LogSink +// implementation. It should be constructed with NewFormatter. Some of +// its methods directly implement logr.LogSink. +type Formatter struct { + outputFormat outputFormat + prefix string + values []any + valuesStr string + depth int + opts *Options + groupName string // for slog groups + groups []groupDef +} + +// outputFormat indicates which outputFormat to use. +type outputFormat int + +const ( + // outputKeyValue emits a JSON-like key=value format, but not strict JSON. + outputKeyValue outputFormat = iota + // outputJSON emits strict JSON. + outputJSON +) + +// groupDef represents a saved group. The values may be empty, but we don't +// know if we need to render the group until the final record is rendered. +type groupDef struct { + name string + values string +} + +// PseudoStruct is a list of key-value pairs that gets logged as a struct. +type PseudoStruct []any + +// render produces a log line, ready to use. +func (f Formatter) render(builtins, args []any) string { + // Empirically bytes.Buffer is faster than strings.Builder for this. + buf := bytes.NewBuffer(make([]byte, 0, 1024)) + + if f.outputFormat == outputJSON { + buf.WriteByte('{') // for the whole record + } + + // Render builtins + vals := builtins + if hook := f.opts.RenderBuiltinsHook; hook != nil { + vals = hook(f.sanitize(vals)) + } + f.flatten(buf, vals, false) // keys are ours, no need to escape + continuing := len(builtins) > 0 + + // Turn the inner-most group into a string + argsStr := func() string { + buf := bytes.NewBuffer(make([]byte, 0, 1024)) + + vals = args + if hook := f.opts.RenderArgsHook; hook != nil { + vals = hook(f.sanitize(vals)) + } + f.flatten(buf, vals, true) // escape user-provided keys + + return buf.String() + }() + + // Render the stack of groups from the inside out. + bodyStr := f.renderGroup(f.groupName, f.valuesStr, argsStr) + for i := len(f.groups) - 1; i >= 0; i-- { + grp := &f.groups[i] + if grp.values == "" && bodyStr == "" { + // no contents, so we must elide the whole group + continue + } + bodyStr = f.renderGroup(grp.name, grp.values, bodyStr) + } + + if bodyStr != "" { + if continuing { + buf.WriteByte(f.comma()) + } + buf.WriteString(bodyStr) + } + + if f.outputFormat == outputJSON { + buf.WriteByte('}') // for the whole record + } + + return buf.String() +} + +// renderGroup returns a string representation of the named group with rendered +// values and args. If the name is empty, this will return the values and args, +// joined. If the name is not empty, this will return a single key-value pair, +// where the value is a grouping of the values and args. If the values and +// args are both empty, this will return an empty string, even if the name was +// specified. +func (f Formatter) renderGroup(name string, values string, args string) string { + buf := bytes.NewBuffer(make([]byte, 0, 1024)) + + needClosingBrace := false + if name != "" && (values != "" || args != "") { + buf.WriteString(f.quoted(name, true)) // escape user-provided keys + buf.WriteByte(f.colon()) + buf.WriteByte('{') + needClosingBrace = true + } + + continuing := false + if values != "" { + buf.WriteString(values) + continuing = true + } + + if args != "" { + if continuing { + buf.WriteByte(f.comma()) + } + buf.WriteString(args) + } + + if needClosingBrace { + buf.WriteByte('}') + } + + return buf.String() +} + +// flatten renders a list of key-value pairs into a buffer. If escapeKeys is +// true, the keys are assumed to have non-JSON-compatible characters in them +// and must be evaluated for escapes. +// +// This function returns a potentially modified version of kvList, which +// ensures that there is a value for every key (adding a value if needed) and +// that each key is a string (substituting a key if needed). +func (f Formatter) flatten(buf *bytes.Buffer, kvList []any, escapeKeys bool) []any { + // This logic overlaps with sanitize() but saves one type-cast per key, + // which can be measurable. + if len(kvList)%2 != 0 { + kvList = append(kvList, noValue) + } + copied := false + for i := 0; i < len(kvList); i += 2 { + k, ok := kvList[i].(string) + if !ok { + if !copied { + newList := make([]any, len(kvList)) + copy(newList, kvList) + kvList = newList + copied = true + } + k = f.nonStringKey(kvList[i]) + kvList[i] = k + } + v := kvList[i+1] + + if i > 0 { + if f.outputFormat == outputJSON { + buf.WriteByte(f.comma()) + } else { + // In theory the format could be something we don't understand. In + // practice, we control it, so it won't be. + buf.WriteByte(' ') + } + } + + buf.WriteString(f.quoted(k, escapeKeys)) + buf.WriteByte(f.colon()) + buf.WriteString(f.pretty(v)) + } + return kvList +} + +func (f Formatter) quoted(str string, escape bool) string { + if escape { + return prettyString(str) + } + // this is faster + return `"` + str + `"` +} + +func (f Formatter) comma() byte { + if f.outputFormat == outputJSON { + return ',' + } + return ' ' +} + +func (f Formatter) colon() byte { + if f.outputFormat == outputJSON { + return ':' + } + return '=' +} + +func (f Formatter) pretty(value any) string { + return f.prettyWithFlags(value, 0, 0, 0, nil) +} + +const ( + flagRawStruct = 0x1 // do not print braces on structs +) + +// TODO: This is not fast. Most of the overhead goes here. +// value: The value to render +// flags: Bitmask of flags (see above) +// depth: The current depth of nested structs, slices, arrays, and maps +// ptrDepth: The current depth of including pointer dereferences +// ptrMap: A map of pointers already seen, to avoid infinite recursion (usually +// nil unless ptrDepth is large) +func (f Formatter) prettyWithFlags(value any, flags uint32, depth int, ptrDepth int, ptrMap map[uintptr]bool) string { + if depth > f.opts.MaxLogDepth { + return `""` + } + + // Handle types that take full control of logging. + if v, ok := value.(logr.Marshaler); ok { + // Replace the value with what the type wants to get logged. + // That then gets handled below via reflection. + value = invokeMarshaler(v) + } + + // Handle types that want to format themselves. + switch v := value.(type) { + case fmt.Stringer: + value = invokeStringer(v) + case error: + value = invokeError(v) + } + + // Handling the most common types without reflect is a small perf win. + switch v := value.(type) { + case bool: + return strconv.FormatBool(v) + case string: + return prettyString(v) + case int: + return strconv.FormatInt(int64(v), 10) + case int8: + return strconv.FormatInt(int64(v), 10) + case int16: + return strconv.FormatInt(int64(v), 10) + case int32: + return strconv.FormatInt(int64(v), 10) + case int64: + return strconv.FormatInt(int64(v), 10) + case uint: + return strconv.FormatUint(uint64(v), 10) + case uint8: + return strconv.FormatUint(uint64(v), 10) + case uint16: + return strconv.FormatUint(uint64(v), 10) + case uint32: + return strconv.FormatUint(uint64(v), 10) + case uint64: + return strconv.FormatUint(v, 10) + case uintptr: + return strconv.FormatUint(uint64(v), 10) + case float32: + return strconv.FormatFloat(float64(v), 'f', -1, 32) + case float64: + return strconv.FormatFloat(v, 'f', -1, 64) + case complex64: + return `"` + strconv.FormatComplex(complex128(v), 'f', -1, 64) + `"` + case complex128: + return `"` + strconv.FormatComplex(v, 'f', -1, 128) + `"` + case PseudoStruct: + buf := bytes.NewBuffer(make([]byte, 0, 1024)) + v = f.sanitize(v) + if flags&flagRawStruct == 0 { + buf.WriteByte('{') + } + for i := 0; i < len(v); i += 2 { + if i > 0 { + buf.WriteByte(f.comma()) + } + k, _ := v[i].(string) // sanitize() above means no need to check success + // arbitrary keys might need escaping + buf.WriteString(prettyString(k)) + buf.WriteByte(f.colon()) + buf.WriteString(f.prettyWithFlags(v[i+1], 0, depth+1, ptrDepth+1, ptrMap)) + } + if flags&flagRawStruct == 0 { + buf.WriteByte('}') + } + return buf.String() + } + + buf := bytes.NewBuffer(make([]byte, 0, 256)) + t := reflect.TypeOf(value) + if t == nil { + return "null" + } + v := reflect.ValueOf(value) + switch t.Kind() { + case reflect.Bool: + return strconv.FormatBool(v.Bool()) + case reflect.String: + return prettyString(v.String()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return strconv.FormatInt(int64(v.Int()), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return strconv.FormatUint(uint64(v.Uint()), 10) + case reflect.Float32: + return strconv.FormatFloat(float64(v.Float()), 'f', -1, 32) + case reflect.Float64: + return strconv.FormatFloat(v.Float(), 'f', -1, 64) + case reflect.Complex64: + return `"` + strconv.FormatComplex(complex128(v.Complex()), 'f', -1, 64) + `"` + case reflect.Complex128: + return `"` + strconv.FormatComplex(v.Complex(), 'f', -1, 128) + `"` + case reflect.Struct: + if flags&flagRawStruct == 0 { + buf.WriteByte('{') + } + printComma := false // testing i>0 is not enough because of JSON omitted fields + for i := 0; i < t.NumField(); i++ { + fld := t.Field(i) + if fld.PkgPath != "" { + // reflect says this field is only defined for non-exported fields. + continue + } + if !v.Field(i).CanInterface() { + // reflect isn't clear exactly what this means, but we can't use it. + continue + } + name := "" + omitempty := false + if tag, found := fld.Tag.Lookup("json"); found { + if tag == "-" { + continue + } + if comma := strings.Index(tag, ","); comma != -1 { + if n := tag[:comma]; n != "" { + name = n + } + rest := tag[comma:] + if strings.Contains(rest, ",omitempty,") || strings.HasSuffix(rest, ",omitempty") { + omitempty = true + } + } else { + name = tag + } + } + if omitempty && isEmpty(v.Field(i)) { + continue + } + if printComma { + buf.WriteByte(f.comma()) + } + printComma = true // if we got here, we are rendering a field + if fld.Anonymous && fld.Type.Kind() == reflect.Struct && name == "" { + buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), flags|flagRawStruct, depth+1, ptrDepth+1, ptrMap)) + continue + } + if name == "" { + name = fld.Name + } + // field names can't contain characters which need escaping + buf.WriteString(f.quoted(name, false)) + buf.WriteByte(f.colon()) + buf.WriteString(f.prettyWithFlags(v.Field(i).Interface(), 0, depth+1, ptrDepth+1, ptrMap)) + } + if flags&flagRawStruct == 0 { + buf.WriteByte('}') + } + return buf.String() + case reflect.Slice, reflect.Array: + // If this is outputing as JSON make sure this isn't really a json.RawMessage. + // If so just emit "as-is" and don't pretty it as that will just print + // it as [X,Y,Z,...] which isn't terribly useful vs the string form you really want. + if f.outputFormat == outputJSON { + if rm, ok := value.(json.RawMessage); ok { + // If it's empty make sure we emit an empty value as the array style would below. + if len(rm) > 0 { + buf.Write(rm) + } else { + buf.WriteString("null") + } + return buf.String() + } + } + buf.WriteByte('[') + for i := 0; i < v.Len(); i++ { + if i > 0 { + buf.WriteByte(f.comma()) + } + e := v.Index(i) + buf.WriteString(f.prettyWithFlags(e.Interface(), 0, depth+1, ptrDepth+1, ptrMap)) + } + buf.WriteByte(']') + return buf.String() + case reflect.Map: + buf.WriteByte('{') + // This does not sort the map keys, for best perf. + it := v.MapRange() + i := 0 + for it.Next() { + if i > 0 { + buf.WriteByte(f.comma()) + } + // If a map key supports TextMarshaler, use it. + keystr := "" + if m, ok := it.Key().Interface().(encoding.TextMarshaler); ok { + txt, err := m.MarshalText() + if err != nil { + keystr = fmt.Sprintf("", err.Error()) + } else { + keystr = string(txt) + } + keystr = prettyString(keystr) + } else { + // prettyWithFlags will produce already-escaped values + // key depth is unrelated to overall depth + keystr = f.prettyWithFlags(it.Key().Interface(), 0, 0, ptrDepth, ptrMap) + if t.Key().Kind() != reflect.String { + // JSON only does string keys. Unlike Go's standard JSON, we'll + // convert just about anything to a string. + keystr = prettyString(keystr) + } + } + buf.WriteString(keystr) + buf.WriteByte(f.colon()) + buf.WriteString(f.prettyWithFlags(it.Value().Interface(), 0, depth+1, ptrDepth+1, ptrMap)) + i++ + } + buf.WriteByte('}') + return buf.String() + case reflect.Pointer, reflect.Interface: + if v.IsNil() { + return "null" + } + // Special case: recursive pointers. For normal use we do not want to + // count pointer dereferences as depth, but if we see the same pointer + // again we have a recursion and need to stop. After a large number of + // pointer dereferences we will start tracking pointers to avoid the + // perf hit of doing it in the normal path. + // + // This should not happen accidentally (e.g. json decoding should never + // do this) but we can handle it gracefully. + if ptrMap != nil && ptrMap[uintptr(v.Pointer())] { + depth = f.opts.MaxLogDepth + 1 // force a depth error + } + const maxDepthFactor = 4 // arbitrary, but we want it large enough to not false-alert + if ptrDepth > f.opts.MaxLogDepth*maxDepthFactor && ptrMap == nil { + ptrMap = map[uintptr]bool{} + } + if ptrMap != nil { + ptrMap[(uintptr)(v.Pointer())] = true + } + return f.prettyWithFlags(v.Elem().Interface(), 0, depth, ptrDepth+1, ptrMap) + } + return fmt.Sprintf(`""`, t.Kind().String()) +} + +func prettyString(s string) string { + // Avoid escaping (which does allocations) if we can. + if needsEscape(s) { + return strconv.Quote(s) + } + b := bytes.NewBuffer(make([]byte, 0, 1024)) + b.WriteByte('"') + b.WriteString(s) + b.WriteByte('"') + return b.String() +} + +// needsEscape determines whether the input string needs to be escaped or not, +// without doing any allocations. +func needsEscape(s string) bool { + for _, r := range s { + if !strconv.IsPrint(r) || r == '\\' || r == '"' { + return true + } + } + return false +} + +func isEmpty(v reflect.Value) bool { + switch v.Kind() { + case reflect.Array, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == 0 + case reflect.Bool: + return !v.Bool() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return v.Int() == 0 + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return v.Uint() == 0 + case reflect.Float32, reflect.Float64: + return v.Float() == 0 + case reflect.Complex64, reflect.Complex128: + return v.Complex() == 0 + case reflect.Interface, reflect.Pointer: + return v.IsNil() + } + return false +} + +func invokeMarshaler(m logr.Marshaler) (ret any) { + defer func() { + if r := recover(); r != nil { + ret = fmt.Sprintf("", r) + } + }() + return m.MarshalLog() +} + +func invokeStringer(s fmt.Stringer) (ret string) { + defer func() { + if r := recover(); r != nil { + ret = fmt.Sprintf("", r) + } + }() + return s.String() +} + +func invokeError(e error) (ret string) { + defer func() { + if r := recover(); r != nil { + ret = fmt.Sprintf("", r) + } + }() + return e.Error() +} + +// Caller represents the original call site for a log line, after considering +// logr.Logger.WithCallDepth and logr.Logger.WithCallStackHelper. The File and +// Line fields will always be provided, while the Func field is optional. +// Users can set the render hook fields in Options to examine logged key-value +// pairs, one of which will be {"caller", Caller} if the Options.LogCaller +// field is enabled for the given MessageClass. +type Caller struct { + // File is the basename of the file for this call site. + File string `json:"file"` + // Line is the line number in the file for this call site. + Line int `json:"line"` + // Func is the function name for this call site, or empty if + // Options.LogCallerFunc is not enabled. + Func string `json:"function,omitempty"` +} + +func (f Formatter) caller() Caller { + // +1 for this frame, +1 for Info/Error. + pc, file, line, ok := runtime.Caller(f.depth + 2) + if !ok { + return Caller{"", 0, ""} + } + fn := "" + if f.opts.LogCallerFunc { + if fp := runtime.FuncForPC(pc); fp != nil { + fn = fp.Name() + } + } + + return Caller{filepath.Base(file), line, fn} +} + +const noValue = "" + +func (f Formatter) nonStringKey(v any) string { + return fmt.Sprintf("", f.snippet(v)) +} + +// snippet produces a short snippet string of an arbitrary value. +func (f Formatter) snippet(v any) string { + const snipLen = 16 + + snip := f.pretty(v) + if len(snip) > snipLen { + snip = snip[:snipLen] + } + return snip +} + +// sanitize ensures that a list of key-value pairs has a value for every key +// (adding a value if needed) and that each key is a string (substituting a key +// if needed). +func (f Formatter) sanitize(kvList []any) []any { + if len(kvList)%2 != 0 { + kvList = append(kvList, noValue) + } + for i := 0; i < len(kvList); i += 2 { + _, ok := kvList[i].(string) + if !ok { + kvList[i] = f.nonStringKey(kvList[i]) + } + } + return kvList +} + +// startGroup opens a new group scope (basically a sub-struct), which locks all +// the current saved values and starts them anew. This is needed to satisfy +// slog. +func (f *Formatter) startGroup(name string) { + // Unnamed groups are just inlined. + if name == "" { + return + } + + n := len(f.groups) + f.groups = append(f.groups[:n:n], groupDef{f.groupName, f.valuesStr}) + + // Start collecting new values. + f.groupName = name + f.valuesStr = "" + f.values = nil +} + +// Init configures this Formatter from runtime info, such as the call depth +// imposed by logr itself. +// Note that this receiver is a pointer, so depth can be saved. +func (f *Formatter) Init(info logr.RuntimeInfo) { + f.depth += info.CallDepth +} + +// Enabled checks whether an info message at the given level should be logged. +func (f Formatter) Enabled(level int) bool { + return level <= f.opts.Verbosity +} + +// GetDepth returns the current depth of this Formatter. This is useful for +// implementations which do their own caller attribution. +func (f Formatter) GetDepth() int { + return f.depth +} + +// FormatInfo renders an Info log message into strings. The prefix will be +// empty when no names were set (via AddNames), or when the output is +// configured for JSON. +func (f Formatter) FormatInfo(level int, msg string, kvList []any) (prefix, argsStr string) { + args := make([]any, 0, 64) // using a constant here impacts perf + prefix = f.prefix + if f.outputFormat == outputJSON { + args = append(args, "logger", prefix) + prefix = "" + } + if f.opts.LogTimestamp { + args = append(args, "ts", time.Now().Format(f.opts.TimestampFormat)) + } + if policy := f.opts.LogCaller; policy == All || policy == Info { + args = append(args, "caller", f.caller()) + } + if key := *f.opts.LogInfoLevel; key != "" { + args = append(args, key, level) + } + args = append(args, "msg", msg) + return prefix, f.render(args, kvList) +} + +// FormatError renders an Error log message into strings. The prefix will be +// empty when no names were set (via AddNames), or when the output is +// configured for JSON. +func (f Formatter) FormatError(err error, msg string, kvList []any) (prefix, argsStr string) { + args := make([]any, 0, 64) // using a constant here impacts perf + prefix = f.prefix + if f.outputFormat == outputJSON { + args = append(args, "logger", prefix) + prefix = "" + } + if f.opts.LogTimestamp { + args = append(args, "ts", time.Now().Format(f.opts.TimestampFormat)) + } + if policy := f.opts.LogCaller; policy == All || policy == Error { + args = append(args, "caller", f.caller()) + } + args = append(args, "msg", msg) + var loggableErr any + if err != nil { + loggableErr = err.Error() + } + args = append(args, "error", loggableErr) + return prefix, f.render(args, kvList) +} + +// AddName appends the specified name. funcr uses '/' characters to separate +// name elements. Callers should not pass '/' in the provided name string, but +// this library does not actually enforce that. +func (f *Formatter) AddName(name string) { + if len(f.prefix) > 0 { + f.prefix += "/" + } + f.prefix += name +} + +// AddValues adds key-value pairs to the set of saved values to be logged with +// each log line. +func (f *Formatter) AddValues(kvList []any) { + // Three slice args forces a copy. + n := len(f.values) + f.values = append(f.values[:n:n], kvList...) + + vals := f.values + if hook := f.opts.RenderValuesHook; hook != nil { + vals = hook(f.sanitize(vals)) + } + + // Pre-render values, so we don't have to do it on each Info/Error call. + buf := bytes.NewBuffer(make([]byte, 0, 1024)) + f.flatten(buf, vals, true) // escape user-provided keys + f.valuesStr = buf.String() +} + +// AddCallDepth increases the number of stack-frames to skip when attributing +// the log line to a file and line. +func (f *Formatter) AddCallDepth(depth int) { + f.depth += depth +} diff --git a/vendor/github.com/go-logr/logr/funcr/slogsink.go b/vendor/github.com/go-logr/logr/funcr/slogsink.go new file mode 100644 index 0000000..8b519c9 --- /dev/null +++ b/vendor/github.com/go-logr/logr/funcr/slogsink.go @@ -0,0 +1,115 @@ +//go:build go1.21 + +/* +Copyright 2023 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package funcr + +import ( + "context" + "log/slog" + + "github.com/go-logr/logr" +) + +var _ logr.SlogSink = &fnlogger{} + +const extraSlogSinkDepth = 3 // 2 for slog, 1 for SlogSink + +func (l fnlogger) Handle(_ context.Context, record slog.Record) error { + kvList := make([]any, 0, 2*record.NumAttrs()) + record.Attrs(func(attr slog.Attr) bool { + kvList = attrToKVs(attr, kvList, l.opts.MaxLogDepth) + return true + }) + + if record.Level >= slog.LevelError { + l.WithCallDepth(extraSlogSinkDepth).Error(nil, record.Message, kvList...) + } else { + level := l.levelFromSlog(record.Level) + l.WithCallDepth(extraSlogSinkDepth).Info(level, record.Message, kvList...) + } + return nil +} + +func (l fnlogger) WithAttrs(attrs []slog.Attr) logr.SlogSink { + kvList := make([]any, 0, 2*len(attrs)) + for _, attr := range attrs { + kvList = attrToKVs(attr, kvList, l.opts.MaxLogDepth) + } + l.AddValues(kvList) + return &l +} + +func (l fnlogger) WithGroup(name string) logr.SlogSink { + l.startGroup(name) + return &l +} + +// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups +// and other details of slog. maxDepth bounds recursion into nested groups so a +// deeply-nested slog.Group cannot exhaust the stack; it is decremented per group +// level and starts at the Formatter's MaxLogDepth (past which the formatter would +// truncate the rendering anyway). +func attrToKVs(attr slog.Attr, kvList []any, maxDepth int) []any { + attrVal := attr.Value.Resolve() + if attrVal.Kind() == slog.KindGroup { + if maxDepth <= 0 { + // Nesting is too deep to build without risking a stack overflow. + // Stop here; the formatter truncates below MaxLogDepth regardless. + if attr.Key != "" { + kvList = append(kvList, attr.Key, "") + } + return kvList + } + groupVal := attrVal.Group() + grpKVs := make([]any, 0, 2*len(groupVal)) + for _, attr := range groupVal { + grpKVs = attrToKVs(attr, grpKVs, maxDepth-1) + } + if attr.Key == "" { + // slog says we have to inline these + kvList = append(kvList, grpKVs...) + } else { + kvList = append(kvList, attr.Key, PseudoStruct(grpKVs)) + } + } else if attr.Key != "" { + kvList = append(kvList, attr.Key, attrVal.Any()) + } + + return kvList +} + +// levelFromSlog adjusts the level by the logger's verbosity and negates it. +// It ensures that the result is >= 0. This is necessary because the result is +// passed to a LogSink and that API did not historically document whether +// levels could be negative or what that meant. +// +// Some example usage: +// +// logrV0 := getMyLogger() +// logrV2 := logrV0.V(2) +// slogV2 := slog.New(logr.ToSlogHandler(logrV2)) +// slogV2.Debug("msg") // =~ logrV2.V(4) =~ logrV0.V(6) +// slogV2.Info("msg") // =~ logrV2.V(0) =~ logrV0.V(2) +// slogv2.Warn("msg") // =~ logrV2.V(-4) =~ logrV0.V(0) +func (l fnlogger) levelFromSlog(level slog.Level) int { + result := -level + if result < 0 { + result = 0 // because LogSink doesn't expect negative V levels + } + return int(result) +} diff --git a/vendor/github.com/go-logr/logr/logr.go b/vendor/github.com/go-logr/logr/logr.go new file mode 100644 index 0000000..b4428e1 --- /dev/null +++ b/vendor/github.com/go-logr/logr/logr.go @@ -0,0 +1,520 @@ +/* +Copyright 2019 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// This design derives from Dave Cheney's blog: +// http://dave.cheney.net/2015/11/05/lets-talk-about-logging + +// Package logr defines a general-purpose logging API and abstract interfaces +// to back that API. Packages in the Go ecosystem can depend on this package, +// while callers can implement logging with whatever backend is appropriate. +// +// # Usage +// +// Logging is done using a Logger instance. Logger is a concrete type with +// methods, which defers the actual logging to a LogSink interface. The main +// methods of Logger are Info() and Error(). Arguments to Info() and Error() +// are key/value pairs rather than printf-style formatted strings, emphasizing +// "structured logging". +// +// With Go's standard log package, we might write: +// +// log.Printf("setting target value %s", targetValue) +// +// With logr's structured logging, we'd write: +// +// logger.Info("setting target", "value", targetValue) +// +// Errors are much the same. Instead of: +// +// log.Printf("failed to open the pod bay door for user %s: %v", user, err) +// +// We'd write: +// +// logger.Error(err, "failed to open the pod bay door", "user", user) +// +// Info() and Error() are very similar, but they are separate methods so that +// LogSink implementations can choose to do things like attach additional +// information (such as stack traces) on calls to Error(). Error() messages are +// always logged, regardless of the current verbosity. If there is no error +// instance available, passing nil is valid. +// +// # Verbosity +// +// Often we want to log information only when the application in "verbose +// mode". To write log lines that are more verbose, Logger has a V() method. +// The higher the V-level of a log line, the less critical it is considered. +// Log-lines with V-levels that are not enabled (as per the LogSink) will not +// be written. Level V(0) is the default, and logger.V(0).Info() has the same +// meaning as logger.Info(). Negative V-levels have the same meaning as V(0). +// Error messages do not have a verbosity level and are always logged. +// +// Where we might have written: +// +// if flVerbose >= 2 { +// log.Printf("an unusual thing happened") +// } +// +// We can write: +// +// logger.V(2).Info("an unusual thing happened") +// +// # Logger Names +// +// Logger instances can have name strings so that all messages logged through +// that instance have additional context. For example, you might want to add +// a subsystem name: +// +// logger.WithName("compactor").Info("started", "time", time.Now()) +// +// The WithName() method returns a new Logger, which can be passed to +// constructors or other functions for further use. Repeated use of WithName() +// will accumulate name "segments". These name segments will be joined in some +// way by the LogSink implementation. It is strongly recommended that name +// segments contain simple identifiers (letters, digits, and hyphen), and do +// not contain characters that could muddle the log output or confuse the +// joining operation (e.g. whitespace, commas, periods, slashes, brackets, +// quotes, etc). +// +// # Saved Values +// +// Logger instances can store any number of key/value pairs, which will be +// logged alongside all messages logged through that instance. For example, +// you might want to create a Logger instance per managed object: +// +// With the standard log package, we might write: +// +// log.Printf("decided to set field foo to value %q for object %s/%s", +// targetValue, object.Namespace, object.Name) +// +// With logr we'd write: +// +// // Elsewhere: set up the logger to log the object name. +// obj.logger = mainLogger.WithValues( +// "name", obj.name, "namespace", obj.namespace) +// +// // later on... +// obj.logger.Info("setting foo", "value", targetValue) +// +// # Best Practices +// +// Logger has very few hard rules, with the goal that LogSink implementations +// might have a lot of freedom to differentiate. There are, however, some +// things to consider. +// +// The log message consists of a constant message attached to the log line. +// This should generally be a simple description of what's occurring, and should +// never be a format string. Variable information can then be attached using +// named values. +// +// Keys are arbitrary strings, but should generally be constant values. Values +// may be any Go value, but how the value is formatted is determined by the +// LogSink implementation. +// +// Logger instances are meant to be passed around by value. Code that receives +// such a value can call its methods without having to check whether the +// instance is ready for use. +// +// The zero logger (= Logger{}) is identical to Discard() and discards all log +// entries. Code that receives a Logger by value can simply call it, the methods +// will never crash. For cases where passing a logger is optional, a pointer to Logger +// should be used. +// +// # Key Naming Conventions +// +// Keys are not strictly required to conform to any specification or regex, but +// it is recommended that they: +// - be human-readable and meaningful (not auto-generated or simple ordinals) +// - be constant (not dependent on input data) +// - contain only printable characters +// - not contain whitespace or punctuation +// - use lower case for simple keys and lowerCamelCase for more complex ones +// +// These guidelines help ensure that log data is processed properly regardless +// of the log implementation. For example, log implementations will try to +// output JSON data or will store data for later database (e.g. SQL) queries. +// +// While users are generally free to use key names of their choice, it's +// generally best to avoid using the following keys, as they're frequently used +// by implementations: +// - "caller": the calling information (file/line) of a particular log line +// - "error": the underlying error value in the `Error` method +// - "level": the log level +// - "logger": the name of the associated logger +// - "msg": the log message +// - "stacktrace": the stack trace associated with a particular log line or +// error (often from the `Error` message) +// - "ts": the timestamp for a log line +// +// Implementations are encouraged to make use of these keys to represent the +// above concepts, when necessary (for example, in a pure-JSON output form, it +// would be necessary to represent at least message and timestamp as ordinary +// named values). +// +// # Break Glass +// +// Implementations may choose to give callers access to the underlying +// logging implementation. The recommended pattern for this is: +// +// // Underlier exposes access to the underlying logging implementation. +// // Since callers only have a logr.Logger, they have to know which +// // implementation is in use, so this interface is less of an abstraction +// // and more of way to test type conversion. +// type Underlier interface { +// GetUnderlying() +// } +// +// Logger grants access to the sink to enable type assertions like this: +// +// func DoSomethingWithImpl(log logr.Logger) { +// if underlier, ok := log.GetSink().(impl.Underlier); ok { +// implLogger := underlier.GetUnderlying() +// ... +// } +// } +// +// Custom `With*` functions can be implemented by copying the complete +// Logger struct and replacing the sink in the copy: +// +// // WithFooBar changes the foobar parameter in the log sink and returns a +// // new logger with that modified sink. It does nothing for loggers where +// // the sink doesn't support that parameter. +// func WithFoobar(log logr.Logger, foobar int) logr.Logger { +// if foobarLogSink, ok := log.GetSink().(FoobarSink); ok { +// log = log.WithSink(foobarLogSink.WithFooBar(foobar)) +// } +// return log +// } +// +// Don't use New to construct a new Logger with a LogSink retrieved from an +// existing Logger. Source code attribution might not work correctly and +// unexported fields in Logger get lost. +// +// Beware that the same LogSink instance may be shared by different logger +// instances. Calling functions that modify the LogSink will affect all of +// those. +package logr + +// New returns a new Logger instance. This is primarily used by libraries +// implementing LogSink, rather than end users. Passing a nil sink will create +// a Logger which discards all log lines. +func New(sink LogSink) Logger { + logger := Logger{} + logger.setSink(sink) + if sink != nil { + sink.Init(runtimeInfo) + } + return logger +} + +// setSink stores the sink and updates any related fields. It mutates the +// logger and thus is only safe to use for loggers that are not currently being +// used concurrently. +func (l *Logger) setSink(sink LogSink) { + l.sink = sink +} + +// GetSink returns the stored sink. +func (l Logger) GetSink() LogSink { + return l.sink +} + +// WithSink returns a copy of the logger with the new sink. +func (l Logger) WithSink(sink LogSink) Logger { + l.setSink(sink) + return l +} + +// Logger is an interface to an abstract logging implementation. This is a +// concrete type for performance reasons, but all the real work is passed on to +// a LogSink. Implementations of LogSink should provide their own constructors +// that return Logger, not LogSink. +// +// The underlying sink can be accessed through GetSink and be modified through +// WithSink. This enables the implementation of custom extensions (see "Break +// Glass" in the package documentation). Normally the sink should be used only +// indirectly. +type Logger struct { + sink LogSink + level int +} + +// Enabled tests whether this Logger is enabled. For example, commandline +// flags might be used to set the logging verbosity and disable some info logs. +func (l Logger) Enabled() bool { + // Some implementations of LogSink look at the caller in Enabled (e.g. + // different verbosity levels per package or file), but we only pass one + // CallDepth in (via Init). This means that all calls from Logger to the + // LogSink's Enabled, Info, and Error methods must have the same number of + // frames. In other words, Logger methods can't call other Logger methods + // which call these LogSink methods unless we do it the same in all paths. + return l.sink != nil && l.sink.Enabled(l.level) +} + +// Info logs a non-error message with the given key/value pairs as context. +// +// The msg argument should be used to add some constant description to the log +// line. The key/value pairs can then be used to add additional variable +// information. The key/value pairs must alternate string keys and arbitrary +// values. +func (l Logger) Info(msg string, keysAndValues ...any) { + if l.sink == nil { + return + } + if l.sink.Enabled(l.level) { // see comment in Enabled + if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { + withHelper.GetCallStackHelper()() + } + l.sink.Info(l.level, msg, keysAndValues...) + } +} + +// Error logs an error, with the given message and key/value pairs as context. +// It functions similarly to Info, but may have unique behavior, and should be +// preferred for logging errors (see the package documentations for more +// information). The log message will always be emitted, regardless of +// verbosity level. +// +// The msg argument should be used to add context to any underlying error, +// while the err argument should be used to attach the actual error that +// triggered this log line, if present. The err parameter is optional +// and nil may be passed instead of an error instance. +func (l Logger) Error(err error, msg string, keysAndValues ...any) { + if l.sink == nil { + return + } + if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { + withHelper.GetCallStackHelper()() + } + l.sink.Error(err, msg, keysAndValues...) +} + +// V returns a new Logger instance for a specific verbosity level, relative to +// this Logger. In other words, V-levels are additive. A higher verbosity +// level means a log message is less important. Negative V-levels are treated +// as 0. +func (l Logger) V(level int) Logger { + if l.sink == nil { + return l + } + if level < 0 { + level = 0 + } + l.level += level + return l +} + +// GetV returns the verbosity level of the logger. If the logger's LogSink is +// nil as in the Discard logger, this will always return 0. +func (l Logger) GetV() int { + // 0 if l.sink nil because of the if check in V above. + return l.level +} + +// WithValues returns a new Logger instance with additional key/value pairs. +// See Info for documentation on how key/value pairs work. +func (l Logger) WithValues(keysAndValues ...any) Logger { + if l.sink == nil { + return l + } + l.setSink(l.sink.WithValues(keysAndValues...)) + return l +} + +// WithName returns a new Logger instance with the specified name element added +// to the Logger's name. Successive calls with WithName append additional +// suffixes to the Logger's name. It's strongly recommended that name segments +// contain only letters, digits, and hyphens (see the package documentation for +// more information). +func (l Logger) WithName(name string) Logger { + if l.sink == nil { + return l + } + l.setSink(l.sink.WithName(name)) + return l +} + +// WithCallDepth returns a Logger instance that offsets the call stack by the +// specified number of frames when logging call site information, if possible. +// This is useful for users who have helper functions between the "real" call +// site and the actual calls to Logger methods. If depth is 0 the attribution +// should be to the direct caller of this function. If depth is 1 the +// attribution should skip 1 call frame, and so on. Successive calls to this +// are additive. +// +// If the underlying log implementation supports a WithCallDepth(int) method, +// it will be called and the result returned. If the implementation does not +// support CallDepthLogSink, the original Logger will be returned. +// +// To skip one level, WithCallStackHelper() should be used instead of +// WithCallDepth(1) because it works with implementions that support the +// CallDepthLogSink and/or CallStackHelperLogSink interfaces. +func (l Logger) WithCallDepth(depth int) Logger { + if l.sink == nil { + return l + } + if withCallDepth, ok := l.sink.(CallDepthLogSink); ok { + l.setSink(withCallDepth.WithCallDepth(depth)) + } + return l +} + +// WithCallStackHelper returns a new Logger instance that skips the direct +// caller when logging call site information, if possible. This is useful for +// users who have helper functions between the "real" call site and the actual +// calls to Logger methods and want to support loggers which depend on marking +// each individual helper function, like loggers based on testing.T. +// +// In addition to using that new logger instance, callers also must call the +// returned function. +// +// If the underlying log implementation supports a WithCallDepth(int) method, +// WithCallDepth(1) will be called to produce a new logger. If it supports a +// WithCallStackHelper() method, that will be also called. If the +// implementation does not support either of these, the original Logger will be +// returned. +func (l Logger) WithCallStackHelper() (func(), Logger) { + if l.sink == nil { + return func() {}, l + } + var helper func() + if withCallDepth, ok := l.sink.(CallDepthLogSink); ok { + l.setSink(withCallDepth.WithCallDepth(1)) + } + if withHelper, ok := l.sink.(CallStackHelperLogSink); ok { + helper = withHelper.GetCallStackHelper() + } else { + helper = func() {} + } + return helper, l +} + +// IsZero returns true if this logger is an uninitialized zero value +func (l Logger) IsZero() bool { + return l.sink == nil +} + +// RuntimeInfo holds information that the logr "core" library knows which +// LogSinks might want to know. +type RuntimeInfo struct { + // CallDepth is the number of call frames the logr library adds between the + // end-user and the LogSink. LogSink implementations which choose to print + // the original logging site (e.g. file & line) should climb this many + // additional frames to find it. + CallDepth int +} + +// runtimeInfo is a static global. It must not be changed at run time. +var runtimeInfo = RuntimeInfo{ + CallDepth: 1, +} + +// LogSink represents a logging implementation. End-users will generally not +// interact with this type. +type LogSink interface { + // Init receives optional information about the logr library for LogSink + // implementations that need it. + Init(info RuntimeInfo) + + // Enabled tests whether this LogSink is enabled at the specified V-level. + // For example, commandline flags might be used to set the logging + // verbosity and disable some info logs. + Enabled(level int) bool + + // Info logs a non-error message with the given key/value pairs as context. + // The level argument is provided for optional logging. This method will + // only be called when Enabled(level) is true. See Logger.Info for more + // details. + Info(level int, msg string, keysAndValues ...any) + + // Error logs an error, with the given message and key/value pairs as + // context. See Logger.Error for more details. + Error(err error, msg string, keysAndValues ...any) + + // WithValues returns a new LogSink with additional key/value pairs. See + // Logger.WithValues for more details. + WithValues(keysAndValues ...any) LogSink + + // WithName returns a new LogSink with the specified name appended. See + // Logger.WithName for more details. + WithName(name string) LogSink +} + +// CallDepthLogSink represents a LogSink that knows how to climb the call stack +// to identify the original call site and can offset the depth by a specified +// number of frames. This is useful for users who have helper functions +// between the "real" call site and the actual calls to Logger methods. +// Implementations that log information about the call site (such as file, +// function, or line) would otherwise log information about the intermediate +// helper functions. +// +// This is an optional interface and implementations are not required to +// support it. +type CallDepthLogSink interface { + // WithCallDepth returns a LogSink that will offset the call + // stack by the specified number of frames when logging call + // site information. + // + // If depth is 0, the LogSink should skip exactly the number + // of call frames defined in RuntimeInfo.CallDepth when Info + // or Error are called, i.e. the attribution should be to the + // direct caller of Logger.Info or Logger.Error. + // + // If depth is 1 the attribution should skip 1 call frame, and so on. + // Successive calls to this are additive. + WithCallDepth(depth int) LogSink +} + +// CallStackHelperLogSink represents a LogSink that knows how to climb +// the call stack to identify the original call site and can skip +// intermediate helper functions if they mark themselves as +// helper. Go's testing package uses that approach. +// +// This is useful for users who have helper functions between the +// "real" call site and the actual calls to Logger methods. +// Implementations that log information about the call site (such as +// file, function, or line) would otherwise log information about the +// intermediate helper functions. +// +// This is an optional interface and implementations are not required +// to support it. Implementations that choose to support this must not +// simply implement it as WithCallDepth(1), because +// Logger.WithCallStackHelper will call both methods if they are +// present. This should only be implemented for LogSinks that actually +// need it, as with testing.T. +type CallStackHelperLogSink interface { + // GetCallStackHelper returns a function that must be called + // to mark the direct caller as helper function when logging + // call site information. + GetCallStackHelper() func() +} + +// Marshaler is an optional interface that logged values may choose to +// implement. Loggers with structured output, such as JSON, should +// log the object return by the MarshalLog method instead of the +// original value. +type Marshaler interface { + // MarshalLog can be used to: + // - ensure that structs are not logged as strings when the original + // value has a String method: return a different type without a + // String method + // - select which fields of a complex type should get logged: + // return a simpler struct with fewer fields + // - log unexported fields: return a different struct + // with exported fields + // + // It may return any value of any type. + MarshalLog() any +} diff --git a/vendor/github.com/go-logr/logr/sloghandler.go b/vendor/github.com/go-logr/logr/sloghandler.go new file mode 100644 index 0000000..befaf55 --- /dev/null +++ b/vendor/github.com/go-logr/logr/sloghandler.go @@ -0,0 +1,191 @@ +//go:build go1.21 + +/* +Copyright 2023 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +import ( + "context" + "log/slog" +) + +type slogHandler struct { + // May be nil, in which case all logs get discarded. + sink LogSink + // Non-nil if sink is non-nil and implements SlogSink. + slogSink SlogSink + + // groupPrefix collects values from WithGroup calls. It gets added as + // prefix to value keys when handling a log record. + groupPrefix string + + // levelBias can be set when constructing the handler to influence the + // slog.Level of log records. A positive levelBias reduces the + // slog.Level value. slog has no API to influence this value after the + // handler got created, so it can only be set indirectly through + // Logger.V. + levelBias slog.Level +} + +var _ slog.Handler = &slogHandler{} + +// groupSeparator is used to concatenate WithGroup names and attribute keys. +const groupSeparator = "." + +// GetLevel is used for black box unit testing. +func (l *slogHandler) GetLevel() slog.Level { + return l.levelBias +} + +func (l *slogHandler) Enabled(_ context.Context, level slog.Level) bool { + return l.sink != nil && (level >= slog.LevelError || l.sink.Enabled(l.levelFromSlog(level))) +} + +func (l *slogHandler) Handle(ctx context.Context, record slog.Record) error { + if l.slogSink != nil { + // Only adjust verbosity level of log entries < slog.LevelError. + if record.Level < slog.LevelError { + record.Level -= l.levelBias + } + return l.slogSink.Handle(ctx, record) + } + + // No need to check for nil sink here because Handle will only be called + // when Enabled returned true. + + kvList := make([]any, 0, 2*record.NumAttrs()) + record.Attrs(func(attr slog.Attr) bool { + kvList = attrToKVs(attr, l.groupPrefix, kvList) + return true + }) + if record.Level >= slog.LevelError { + l.sinkWithCallDepth().Error(nil, record.Message, kvList...) + } else { + level := l.levelFromSlog(record.Level) + l.sinkWithCallDepth().Info(level, record.Message, kvList...) + } + return nil +} + +// sinkWithCallDepth adjusts the stack unwinding so that when Error or Info +// are called by Handle, code in slog gets skipped. +// +// This offset currently (Go 1.21.0) works for calls through +// slog.New(ToSlogHandler(...)). There's no guarantee that the call +// chain won't change. Wrapping the handler will also break unwinding. It's +// still better than not adjusting at all.... +// +// This cannot be done when constructing the handler because FromSlogHandler needs +// access to the original sink without this adjustment. A second copy would +// work, but then WithAttrs would have to be called for both of them. +func (l *slogHandler) sinkWithCallDepth() LogSink { + if sink, ok := l.sink.(CallDepthLogSink); ok { + return sink.WithCallDepth(2) + } + return l.sink +} + +func (l *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + if l.sink == nil || len(attrs) == 0 { + return l + } + + clone := *l + if l.slogSink != nil { + clone.slogSink = l.slogSink.WithAttrs(attrs) + clone.sink = clone.slogSink + } else { + kvList := make([]any, 0, 2*len(attrs)) + for _, attr := range attrs { + kvList = attrToKVs(attr, l.groupPrefix, kvList) + } + clone.sink = l.sink.WithValues(kvList...) + } + return &clone +} + +func (l *slogHandler) WithGroup(name string) slog.Handler { + if l.sink == nil { + return l + } + if name == "" { + // slog says to inline empty groups + return l + } + clone := *l + if l.slogSink != nil { + clone.slogSink = l.slogSink.WithGroup(name) + clone.sink = clone.slogSink + } else { + clone.groupPrefix = addPrefix(clone.groupPrefix, name) + } + return &clone +} + +// attrToKVs appends a slog.Attr to a logr-style kvList. It handle slog Groups +// and other details of slog. +func attrToKVs(attr slog.Attr, groupPrefix string, kvList []any) []any { + attrVal := attr.Value.Resolve() + if attrVal.Kind() == slog.KindGroup { + groupVal := attrVal.Group() + grpKVs := make([]any, 0, 2*len(groupVal)) + prefix := groupPrefix + if attr.Key != "" { + prefix = addPrefix(groupPrefix, attr.Key) + } + for _, attr := range groupVal { + grpKVs = attrToKVs(attr, prefix, grpKVs) + } + kvList = append(kvList, grpKVs...) + } else if attr.Key != "" { + kvList = append(kvList, addPrefix(groupPrefix, attr.Key), attrVal.Any()) + } + + return kvList +} + +func addPrefix(prefix, name string) string { + if prefix == "" { + return name + } + if name == "" { + return prefix + } + return prefix + groupSeparator + name +} + +// levelFromSlog adjusts the level by the logger's verbosity and negates it. +// It ensures that the result is >= 0. This is necessary because the result is +// passed to a LogSink and that API did not historically document whether +// levels could be negative or what that meant. +// +// Some example usage: +// +// logrV0 := getMyLogger() +// logrV2 := logrV0.V(2) +// slogV2 := slog.New(logr.ToSlogHandler(logrV2)) +// slogV2.Debug("msg") // =~ logrV2.V(4) =~ logrV0.V(6) +// slogV2.Info("msg") // =~ logrV2.V(0) =~ logrV0.V(2) +// slogv2.Warn("msg") // =~ logrV2.V(-4) =~ logrV0.V(0) +func (l *slogHandler) levelFromSlog(level slog.Level) int { + result := -level + result += l.levelBias // in case the original Logger had a V level + if result < 0 { + result = 0 // because LogSink doesn't expect negative V levels + } + return int(result) +} diff --git a/vendor/github.com/go-logr/logr/slogr.go b/vendor/github.com/go-logr/logr/slogr.go new file mode 100644 index 0000000..bfe80eb --- /dev/null +++ b/vendor/github.com/go-logr/logr/slogr.go @@ -0,0 +1,99 @@ +//go:build go1.21 + +/* +Copyright 2023 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +import ( + "context" + "log/slog" +) + +// FromSlogHandler returns a Logger which writes to the slog.Handler. +// +// The logr verbosity level is mapped to slog levels such that V(0) becomes +// slog.LevelInfo and V(4) becomes slog.LevelDebug. +func FromSlogHandler(handler slog.Handler) Logger { + if handler, ok := handler.(*slogHandler); ok { + if handler.sink == nil { + return Discard() + } + return New(handler.sink).V(int(handler.levelBias)) + } + return New(&slogSink{handler: handler}) +} + +// ToSlogHandler returns a slog.Handler which writes to the same sink as the Logger. +// +// The returned logger writes all records with level >= slog.LevelError as +// error log entries with LogSink.Error, regardless of the verbosity level of +// the Logger: +// +// logger := +// slog.New(ToSlogHandler(logger.V(10))).Error(...) -> logSink.Error(...) +// +// The level of all other records gets reduced by the verbosity +// level of the Logger and the result is negated. If it happens +// to be negative, then it gets replaced by zero because a LogSink +// is not expected to handled negative levels: +// +// slog.New(ToSlogHandler(logger)).Debug(...) -> logger.GetSink().Info(level=4, ...) +// slog.New(ToSlogHandler(logger)).Warning(...) -> logger.GetSink().Info(level=0, ...) +// slog.New(ToSlogHandler(logger)).Info(...) -> logger.GetSink().Info(level=0, ...) +// slog.New(ToSlogHandler(logger.V(4))).Info(...) -> logger.GetSink().Info(level=4, ...) +func ToSlogHandler(logger Logger) slog.Handler { + if sink, ok := logger.GetSink().(*slogSink); ok && logger.GetV() == 0 { + return sink.handler + } + + handler := &slogHandler{sink: logger.GetSink(), levelBias: slog.Level(logger.GetV())} + if slogSink, ok := handler.sink.(SlogSink); ok { + handler.slogSink = slogSink + } + return handler +} + +// SlogSink is an optional interface that a LogSink can implement to support +// logging through the slog.Logger or slog.Handler APIs better. It then should +// also support special slog values like slog.Group. When used as a +// slog.Handler, the advantages are: +// +// - stack unwinding gets avoided in favor of logging the pre-recorded PC, +// as intended by slog +// - proper grouping of key/value pairs via WithGroup +// - verbosity levels > slog.LevelInfo can be recorded +// - less overhead +// +// Both APIs (Logger and slog.Logger/Handler) then are supported equally +// well. Developers can pick whatever API suits them better and/or mix +// packages which use either API in the same binary with a common logging +// implementation. +// +// This interface is necessary because the type implementing the LogSink +// interface cannot also implement the slog.Handler interface due to the +// different prototype of the common Enabled method. +// +// An implementation could support both interfaces in two different types, but then +// additional interfaces would be needed to convert between those types in FromSlogHandler +// and ToSlogHandler. +type SlogSink interface { + LogSink + + Handle(ctx context.Context, record slog.Record) error + WithAttrs(attrs []slog.Attr) SlogSink + WithGroup(name string) SlogSink +} diff --git a/vendor/github.com/go-logr/logr/slogsink.go b/vendor/github.com/go-logr/logr/slogsink.go new file mode 100644 index 0000000..ab76ea9 --- /dev/null +++ b/vendor/github.com/go-logr/logr/slogsink.go @@ -0,0 +1,119 @@ +//go:build go1.21 + +/* +Copyright 2023 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package logr + +import ( + "context" + "log/slog" + "runtime" + "time" +) + +var ( + _ LogSink = &slogSink{} + _ CallDepthLogSink = &slogSink{} + _ Underlier = &slogSink{} +) + +// Underlier is implemented by the LogSink returned by NewFromLogHandler. +type Underlier interface { + // GetUnderlying returns the Handler used by the LogSink. + GetUnderlying() slog.Handler +} + +const ( + // nameKey is used to log the `WithName` values as an additional attribute. + nameKey = "logger" + + // errKey is used to log the error parameter of Error as an additional attribute. + errKey = "err" +) + +type slogSink struct { + callDepth int + name string + handler slog.Handler +} + +func (l *slogSink) Init(info RuntimeInfo) { + l.callDepth = info.CallDepth +} + +func (l *slogSink) GetUnderlying() slog.Handler { + return l.handler +} + +func (l *slogSink) WithCallDepth(depth int) LogSink { + newLogger := *l + newLogger.callDepth += depth + return &newLogger +} + +func (l *slogSink) Enabled(level int) bool { + return l.handler.Enabled(context.Background(), slog.Level(-level)) +} + +func (l *slogSink) Info(level int, msg string, kvList ...interface{}) { + l.log(nil, msg, slog.Level(-level), kvList...) +} + +func (l *slogSink) Error(err error, msg string, kvList ...interface{}) { + l.log(err, msg, slog.LevelError, kvList...) +} + +func (l *slogSink) log(err error, msg string, level slog.Level, kvList ...interface{}) { + var pcs [1]uintptr + // skip runtime.Callers, this function, Info/Error, and all helper functions above that. + runtime.Callers(3+l.callDepth, pcs[:]) + + record := slog.NewRecord(time.Now(), level, msg, pcs[0]) + if l.name != "" { + record.AddAttrs(slog.String(nameKey, l.name)) + } + if err != nil { + record.AddAttrs(slog.Any(errKey, err)) + } + record.Add(kvList...) + _ = l.handler.Handle(context.Background(), record) +} + +func (l slogSink) WithName(name string) LogSink { + if l.name != "" { + l.name += "/" + } + l.name += name + return &l +} + +func (l slogSink) WithValues(kvList ...interface{}) LogSink { + l.handler = l.handler.WithAttrs(kvListToAttrs(kvList...)) + return &l +} + +func kvListToAttrs(kvList ...interface{}) []slog.Attr { + // We don't need the record itself, only its Add method. + record := slog.NewRecord(time.Time{}, 0, "", 0) + record.Add(kvList...) + attrs := make([]slog.Attr, 0, record.NumAttrs()) + record.Attrs(func(attr slog.Attr) bool { + attrs = append(attrs, attr) + return true + }) + return attrs +} diff --git a/vendor/github.com/go-logr/stdr/LICENSE b/vendor/github.com/go-logr/stdr/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/vendor/github.com/go-logr/stdr/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/go-logr/stdr/README.md b/vendor/github.com/go-logr/stdr/README.md new file mode 100644 index 0000000..5158667 --- /dev/null +++ b/vendor/github.com/go-logr/stdr/README.md @@ -0,0 +1,6 @@ +# Minimal Go logging using logr and Go's standard library + +[![Go Reference](https://pkg.go.dev/badge/github.com/go-logr/stdr.svg)](https://pkg.go.dev/github.com/go-logr/stdr) + +This package implements the [logr interface](https://github.com/go-logr/logr) +in terms of Go's standard log package(https://pkg.go.dev/log). diff --git a/vendor/github.com/go-logr/stdr/stdr.go b/vendor/github.com/go-logr/stdr/stdr.go new file mode 100644 index 0000000..93a8aab --- /dev/null +++ b/vendor/github.com/go-logr/stdr/stdr.go @@ -0,0 +1,170 @@ +/* +Copyright 2019 The logr Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package stdr implements github.com/go-logr/logr.Logger in terms of +// Go's standard log package. +package stdr + +import ( + "log" + "os" + + "github.com/go-logr/logr" + "github.com/go-logr/logr/funcr" +) + +// The global verbosity level. See SetVerbosity(). +var globalVerbosity int + +// SetVerbosity sets the global level against which all info logs will be +// compared. If this is greater than or equal to the "V" of the logger, the +// message will be logged. A higher value here means more logs will be written. +// The previous verbosity value is returned. This is not concurrent-safe - +// callers must be sure to call it from only one goroutine. +func SetVerbosity(v int) int { + old := globalVerbosity + globalVerbosity = v + return old +} + +// New returns a logr.Logger which is implemented by Go's standard log package, +// or something like it. If std is nil, this will use a default logger +// instead. +// +// Example: stdr.New(log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile))) +func New(std StdLogger) logr.Logger { + return NewWithOptions(std, Options{}) +} + +// NewWithOptions returns a logr.Logger which is implemented by Go's standard +// log package, or something like it. See New for details. +func NewWithOptions(std StdLogger, opts Options) logr.Logger { + if std == nil { + // Go's log.Default() is only available in 1.16 and higher. + std = log.New(os.Stderr, "", log.LstdFlags) + } + + if opts.Depth < 0 { + opts.Depth = 0 + } + + fopts := funcr.Options{ + LogCaller: funcr.MessageClass(opts.LogCaller), + } + + sl := &logger{ + Formatter: funcr.NewFormatter(fopts), + std: std, + } + + // For skipping our own logger.Info/Error. + sl.Formatter.AddCallDepth(1 + opts.Depth) + + return logr.New(sl) +} + +// Options carries parameters which influence the way logs are generated. +type Options struct { + // Depth biases the assumed number of call frames to the "true" caller. + // This is useful when the calling code calls a function which then calls + // stdr (e.g. a logging shim to another API). Values less than zero will + // be treated as zero. + Depth int + + // LogCaller tells stdr to add a "caller" key to some or all log lines. + // Go's log package has options to log this natively, too. + LogCaller MessageClass + + // TODO: add an option to log the date/time +} + +// MessageClass indicates which category or categories of messages to consider. +type MessageClass int + +const ( + // None ignores all message classes. + None MessageClass = iota + // All considers all message classes. + All + // Info only considers info messages. + Info + // Error only considers error messages. + Error +) + +// StdLogger is the subset of the Go stdlib log.Logger API that is needed for +// this adapter. +type StdLogger interface { + // Output is the same as log.Output and log.Logger.Output. + Output(calldepth int, logline string) error +} + +type logger struct { + funcr.Formatter + std StdLogger +} + +var _ logr.LogSink = &logger{} +var _ logr.CallDepthLogSink = &logger{} + +func (l logger) Enabled(level int) bool { + return globalVerbosity >= level +} + +func (l logger) Info(level int, msg string, kvList ...interface{}) { + prefix, args := l.FormatInfo(level, msg, kvList) + if prefix != "" { + args = prefix + ": " + args + } + _ = l.std.Output(l.Formatter.GetDepth()+1, args) +} + +func (l logger) Error(err error, msg string, kvList ...interface{}) { + prefix, args := l.FormatError(err, msg, kvList) + if prefix != "" { + args = prefix + ": " + args + } + _ = l.std.Output(l.Formatter.GetDepth()+1, args) +} + +func (l logger) WithName(name string) logr.LogSink { + l.Formatter.AddName(name) + return &l +} + +func (l logger) WithValues(kvList ...interface{}) logr.LogSink { + l.Formatter.AddValues(kvList) + return &l +} + +func (l logger) WithCallDepth(depth int) logr.LogSink { + l.Formatter.AddCallDepth(depth) + return &l +} + +// Underlier exposes access to the underlying logging implementation. Since +// callers only have a logr.Logger, they have to know which implementation is +// in use, so this interface is less of an abstraction and more of way to test +// type conversion. +type Underlier interface { + GetUnderlying() StdLogger +} + +// GetUnderlying returns the StdLogger underneath this logger. Since StdLogger +// is itself an interface, the result may or may not be a Go log.Logger. +func (l logger) GetUnderlying() StdLogger { + return l.std +} diff --git a/vendor/github.com/go-playground/locales/.gitignore b/vendor/github.com/go-playground/locales/.gitignore new file mode 100644 index 0000000..daf913b --- /dev/null +++ b/vendor/github.com/go-playground/locales/.gitignore @@ -0,0 +1,24 @@ +# 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 diff --git a/vendor/github.com/go-playground/locales/.travis.yml b/vendor/github.com/go-playground/locales/.travis.yml new file mode 100644 index 0000000..d50237a --- /dev/null +++ b/vendor/github.com/go-playground/locales/.travis.yml @@ -0,0 +1,26 @@ +language: go +go: + - 1.13.1 + - tip +matrix: + allow_failures: + - go: tip + +notifications: + email: + recipients: dean.karn@gmail.com + on_success: change + on_failure: always + +before_install: + - go install github.com/mattn/goveralls + +# Only clone the most recent commit. +git: + depth: 1 + +script: + - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... + +after_success: | + goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/vendor/github.com/go-playground/locales/LICENSE b/vendor/github.com/go-playground/locales/LICENSE new file mode 100644 index 0000000..75854ac --- /dev/null +++ b/vendor/github.com/go-playground/locales/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Go Playground + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/vendor/github.com/go-playground/locales/README.md b/vendor/github.com/go-playground/locales/README.md new file mode 100644 index 0000000..7b6be2c --- /dev/null +++ b/vendor/github.com/go-playground/locales/README.md @@ -0,0 +1,170 @@ +## locales +![Project status](https://img.shields.io/badge/version-0.14.1-green.svg) +[![Build Status](https://travis-ci.org/go-playground/locales.svg?branch=master)](https://travis-ci.org/go-playground/locales) +[![GoDoc](https://godoc.org/github.com/go-playground/locales?status.svg)](https://godoc.org/github.com/go-playground/locales) +![License](https://img.shields.io/dub/l/vibe-d.svg) + +Locales is a set of locales generated from the [Unicode CLDR Project](http://cldr.unicode.org/) which can be used independently or within +an i18n package; these were built for use with, but not exclusive to, [Universal Translator](https://github.com/go-playground/universal-translator). + +Features +-------- +- [x] Rules generated from the latest [CLDR](http://cldr.unicode.org/index/downloads) data, v36.0.1 +- [x] Contains Cardinal, Ordinal and Range Plural Rules +- [x] Contains Month, Weekday and Timezone translations built in +- [x] Contains Date & Time formatting functions +- [x] Contains Number, Currency, Accounting and Percent formatting functions +- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) + +Full Tests +-------------------- +I could sure use your help adding tests for every locale, it is a huge undertaking and I just don't have the free time to do it all at the moment; +any help would be **greatly appreciated!!!!** please see [issue](https://github.com/go-playground/locales/issues/1) for details. + +Installation +----------- + +Use go get + +```shell +go get github.com/go-playground/locales +``` + +NOTES +-------- +You'll notice most return types are []byte, this is because most of the time the results will be concatenated with a larger body +of text and can avoid some allocations if already appending to a byte array, otherwise just cast as string. + +Usage +------- +```go +package main + +import ( + "fmt" + "time" + + "github.com/go-playground/locales/currency" + "github.com/go-playground/locales/en_CA" +) + +func main() { + + loc, _ := time.LoadLocation("America/Toronto") + datetime := time.Date(2016, 02, 03, 9, 0, 1, 0, loc) + + l := en_CA.New() + + // Dates + fmt.Println(l.FmtDateFull(datetime)) + fmt.Println(l.FmtDateLong(datetime)) + fmt.Println(l.FmtDateMedium(datetime)) + fmt.Println(l.FmtDateShort(datetime)) + + // Times + fmt.Println(l.FmtTimeFull(datetime)) + fmt.Println(l.FmtTimeLong(datetime)) + fmt.Println(l.FmtTimeMedium(datetime)) + fmt.Println(l.FmtTimeShort(datetime)) + + // Months Wide + fmt.Println(l.MonthWide(time.January)) + fmt.Println(l.MonthWide(time.February)) + fmt.Println(l.MonthWide(time.March)) + // ... + + // Months Abbreviated + fmt.Println(l.MonthAbbreviated(time.January)) + fmt.Println(l.MonthAbbreviated(time.February)) + fmt.Println(l.MonthAbbreviated(time.March)) + // ... + + // Months Narrow + fmt.Println(l.MonthNarrow(time.January)) + fmt.Println(l.MonthNarrow(time.February)) + fmt.Println(l.MonthNarrow(time.March)) + // ... + + // Weekdays Wide + fmt.Println(l.WeekdayWide(time.Sunday)) + fmt.Println(l.WeekdayWide(time.Monday)) + fmt.Println(l.WeekdayWide(time.Tuesday)) + // ... + + // Weekdays Abbreviated + fmt.Println(l.WeekdayAbbreviated(time.Sunday)) + fmt.Println(l.WeekdayAbbreviated(time.Monday)) + fmt.Println(l.WeekdayAbbreviated(time.Tuesday)) + // ... + + // Weekdays Short + fmt.Println(l.WeekdayShort(time.Sunday)) + fmt.Println(l.WeekdayShort(time.Monday)) + fmt.Println(l.WeekdayShort(time.Tuesday)) + // ... + + // Weekdays Narrow + fmt.Println(l.WeekdayNarrow(time.Sunday)) + fmt.Println(l.WeekdayNarrow(time.Monday)) + fmt.Println(l.WeekdayNarrow(time.Tuesday)) + // ... + + var f64 float64 + + f64 = -10356.4523 + + // Number + fmt.Println(l.FmtNumber(f64, 2)) + + // Currency + fmt.Println(l.FmtCurrency(f64, 2, currency.CAD)) + fmt.Println(l.FmtCurrency(f64, 2, currency.USD)) + + // Accounting + fmt.Println(l.FmtAccounting(f64, 2, currency.CAD)) + fmt.Println(l.FmtAccounting(f64, 2, currency.USD)) + + f64 = 78.12 + + // Percent + fmt.Println(l.FmtPercent(f64, 0)) + + // Plural Rules for locale, so you know what rules you must cover + fmt.Println(l.PluralsCardinal()) + fmt.Println(l.PluralsOrdinal()) + + // Cardinal Plural Rules + fmt.Println(l.CardinalPluralRule(1, 0)) + fmt.Println(l.CardinalPluralRule(1.0, 0)) + fmt.Println(l.CardinalPluralRule(1.0, 1)) + fmt.Println(l.CardinalPluralRule(3, 0)) + + // Ordinal Plural Rules + fmt.Println(l.OrdinalPluralRule(21, 0)) // 21st + fmt.Println(l.OrdinalPluralRule(22, 0)) // 22nd + fmt.Println(l.OrdinalPluralRule(33, 0)) // 33rd + fmt.Println(l.OrdinalPluralRule(34, 0)) // 34th + + // Range Plural Rules + fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1 + fmt.Println(l.RangePluralRule(1, 0, 2, 0)) // 1-2 + fmt.Println(l.RangePluralRule(5, 0, 8, 0)) // 5-8 +} +``` + +NOTES: +------- +These rules were generated from the [Unicode CLDR Project](http://cldr.unicode.org/), if you encounter any issues +I strongly encourage contributing to the CLDR project to get the locale information corrected and the next time +these locales are regenerated the fix will come with. + +I do however realize that time constraints are often important and so there are two options: + +1. Create your own locale, copy, paste and modify, and ensure it complies with the `Translator` interface. +2. Add an exception in the locale generation code directly and once regenerated, fix will be in place. + +Please to not make fixes inside the locale files, they WILL get overwritten when the locales are regenerated. + +License +------ +Distributed under MIT License, please see license file in code for more details. diff --git a/vendor/github.com/go-playground/locales/currency/currency.go b/vendor/github.com/go-playground/locales/currency/currency.go new file mode 100644 index 0000000..b5a95fb --- /dev/null +++ b/vendor/github.com/go-playground/locales/currency/currency.go @@ -0,0 +1,311 @@ +package currency + +// Type is the currency type associated with the locales currency enum +type Type int + +// locale currencies +const ( + ADP Type = iota + AED + AFA + AFN + ALK + ALL + AMD + ANG + AOA + AOK + AON + AOR + ARA + ARL + ARM + ARP + ARS + ATS + AUD + AWG + AZM + AZN + BAD + BAM + BAN + BBD + BDT + BEC + BEF + BEL + BGL + BGM + BGN + BGO + BHD + BIF + BMD + BND + BOB + BOL + BOP + BOV + BRB + BRC + BRE + BRL + BRN + BRR + BRZ + BSD + BTN + BUK + BWP + BYB + BYN + BYR + BZD + CAD + CDF + CHE + CHF + CHW + CLE + CLF + CLP + CNH + CNX + CNY + COP + COU + CRC + CSD + CSK + CUC + CUP + CVE + CYP + CZK + DDM + DEM + DJF + DKK + DOP + DZD + ECS + ECV + EEK + EGP + ERN + ESA + ESB + ESP + ETB + EUR + FIM + FJD + FKP + FRF + GBP + GEK + GEL + GHC + GHS + GIP + GMD + GNF + GNS + GQE + GRD + GTQ + GWE + GWP + GYD + HKD + HNL + HRD + HRK + HTG + HUF + IDR + IEP + ILP + ILR + ILS + INR + IQD + IRR + ISJ + ISK + ITL + JMD + JOD + JPY + KES + KGS + KHR + KMF + KPW + KRH + KRO + KRW + KWD + KYD + KZT + LAK + LBP + LKR + LRD + LSL + LTL + LTT + LUC + LUF + LUL + LVL + LVR + LYD + MAD + MAF + MCF + MDC + MDL + MGA + MGF + MKD + MKN + MLF + MMK + MNT + MOP + MRO + MRU + MTL + MTP + MUR + MVP + MVR + MWK + MXN + MXP + MXV + MYR + MZE + MZM + MZN + NAD + NGN + NIC + NIO + NLG + NOK + NPR + NZD + OMR + PAB + PEI + PEN + PES + PGK + PHP + PKR + PLN + PLZ + PTE + PYG + QAR + RHD + ROL + RON + RSD + RUB + RUR + RWF + SAR + SBD + SCR + SDD + SDG + SDP + SEK + SGD + SHP + SIT + SKK + SLL + SOS + SRD + SRG + SSP + STD + STN + SUR + SVC + SYP + SZL + THB + TJR + TJS + TMM + TMT + TND + TOP + TPE + TRL + TRY + TTD + TWD + TZS + UAH + UAK + UGS + UGX + USD + USN + USS + UYI + UYP + UYU + UYW + UZS + VEB + VEF + VES + VND + VNN + VUV + WST + XAF + XAG + XAU + XBA + XBB + XBC + XBD + XCD + XDR + XEU + XFO + XFU + XOF + XPD + XPF + XPT + XRE + XSU + XTS + XUA + XXX + YDD + YER + YUD + YUM + YUN + YUR + ZAL + ZAR + ZMK + ZMW + ZRN + ZRZ + ZWD + ZWL + ZWR +) diff --git a/vendor/github.com/go-playground/locales/en/en.go b/vendor/github.com/go-playground/locales/en/en.go new file mode 100644 index 0000000..baf343d --- /dev/null +++ b/vendor/github.com/go-playground/locales/en/en.go @@ -0,0 +1,650 @@ +package en + +import ( + "math" + "strconv" + "time" + + "github.com/go-playground/locales" + "github.com/go-playground/locales/currency" +) + +type en struct { + locale string + pluralsCardinal []locales.PluralRule + pluralsOrdinal []locales.PluralRule + pluralsRange []locales.PluralRule + decimal string + group string + minus string + percent string + perMille string + timeSeparator string + inifinity string + currencies []string // idx = enum of currency code + currencyNegativePrefix string + currencyNegativeSuffix string + monthsAbbreviated []string + monthsNarrow []string + monthsWide []string + daysAbbreviated []string + daysNarrow []string + daysShort []string + daysWide []string + periodsAbbreviated []string + periodsNarrow []string + periodsShort []string + periodsWide []string + erasAbbreviated []string + erasNarrow []string + erasWide []string + timezones map[string]string +} + +// New returns a new instance of translator for the 'en' locale +func New() locales.Translator { + return &en{ + locale: "en", + pluralsCardinal: []locales.PluralRule{2, 6}, + pluralsOrdinal: []locales.PluralRule{2, 3, 4, 6}, + pluralsRange: []locales.PluralRule{6}, + decimal: ".", + group: ",", + minus: "-", + percent: "%", + perMille: "‰", + timeSeparator: ":", + inifinity: "∞", + currencies: []string{"ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", "ANG", "AOA", "AOK", "AON", "AOR", "ARA", "ARL", "ARM", "ARP", "ARS", "ATS", "AUD", "AWG", "AZM", "AZN", "BAD", "BAM", "BAN", "BBD", "BDT", "BEC", "BEF", "BEL", "BGL", "BGM", "BGN", "BGO", "BHD", "BIF", "BMD", "BND", "BOB", "BOL", "BOP", "BOV", "BRB", "BRC", "BRE", "BRL", "BRN", "BRR", "BRZ", "BSD", "BTN", "BUK", "BWP", "BYB", "BYN", "BYR", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLE", "CLF", "CLP", "CNH", "CNX", "CNY", "COP", "COU", "CRC", "CSD", "CSK", "CUC", "CUP", "CVE", "CYP", "CZK", "DDM", "DEM", "DJF", "DKK", "DOP", "DZD", "ECS", "ECV", "EEK", "EGP", "ERN", "ESA", "ESB", "ESP", "ETB", "EUR", "FIM", "FJD", "FKP", "FRF", "GBP", "GEK", "GEL", "GHC", "GHS", "GIP", "GMD", "GNF", "GNS", "GQE", "GRD", "GTQ", "GWE", "GWP", "GYD", "HKD", "HNL", "HRD", "HRK", "HTG", "HUF", "IDR", "IEP", "ILP", "ILR", "ILS", "INR", "IQD", "IRR", "ISJ", "ISK", "ITL", "JMD", "JOD", "¥", "KES", "KGS", "KHR", "KMF", "KPW", "KRH", "KRO", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LTL", "LTT", "LUC", "LUF", "LUL", "LVL", "LVR", "LYD", "MAD", "MAF", "MCF", "MDC", "MDL", "MGA", "MGF", "MKD", "MKN", "MLF", "MMK", "MNT", "MOP", "MRO", "MRU", "MTL", "MTP", "MUR", "MVP", "MVR", "MWK", "MXN", "MXP", "MXV", "MYR", "MZE", "MZM", "MZN", "NAD", "NGN", "NIC", "NIO", "NLG", "NOK", "NPR", "NZD", "OMR", "PAB", "PEI", "PEN", "PES", "PGK", "PHP", "PKR", "PLN", "PLZ", "PTE", "PYG", "QAR", "RHD", "ROL", "RON", "RSD", "RUB", "RUR", "RWF", "SAR", "SBD", "SCR", "SDD", "SDG", "SDP", "SEK", "SGD", "SHP", "SIT", "SKK", "SLL", "SOS", "SRD", "SRG", "SSP", "STD", "STN", "SUR", "SVC", "SYP", "SZL", "THB", "TJR", "TJS", "TMM", "TMT", "TND", "TOP", "TPE", "TRL", "TRY", "TTD", "TWD", "TZS", "UAH", "UAK", "UGS", "UGX", "$", "USN", "USS", "UYI", "UYP", "UYU", "UYW", "UZS", "VEB", "VEF", "VES", "VND", "VNN", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XEU", "XFO", "XFU", "XOF", "XPD", "XPF", "XPT", "XRE", "XSU", "XTS", "XUA", "XXX", "YDD", "YER", "YUD", "YUM", "YUN", "YUR", "ZAL", "ZAR", "ZMK", "ZMW", "ZRN", "ZRZ", "ZWD", "ZWL", "ZWR"}, + currencyNegativePrefix: "(", + currencyNegativeSuffix: ")", + monthsAbbreviated: []string{"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}, + monthsNarrow: []string{"", "J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"}, + monthsWide: []string{"", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}, + daysAbbreviated: []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}, + daysNarrow: []string{"S", "M", "T", "W", "T", "F", "S"}, + daysShort: []string{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}, + daysWide: []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, + periodsAbbreviated: []string{"am", "pm"}, + periodsNarrow: []string{"a", "p"}, + periodsWide: []string{"am", "pm"}, + erasAbbreviated: []string{"BC", "AD"}, + erasNarrow: []string{"B", "A"}, + erasWide: []string{"Before Christ", "Anno Domini"}, + timezones: map[string]string{"ACDT": "Australian Central Daylight Time", "ACST": "Australian Central Standard Time", "ACWDT": "Australian Central Western Daylight Time", "ACWST": "Australian Central Western Standard Time", "ADT": "Atlantic Daylight Time", "AEDT": "Australian Eastern Daylight Time", "AEST": "Australian Eastern Standard Time", "AKDT": "Alaska Daylight Time", "AKST": "Alaska Standard Time", "ARST": "Argentina Summer Time", "ART": "Argentina Standard Time", "AST": "Atlantic Standard Time", "AWDT": "Australian Western Daylight Time", "AWST": "Australian Western Standard Time", "BOT": "Bolivia Time", "BT": "Bhutan Time", "CAT": "Central Africa Time", "CDT": "Central Daylight Time", "CHADT": "Chatham Daylight Time", "CHAST": "Chatham Standard Time", "CLST": "Chile Summer Time", "CLT": "Chile Standard Time", "COST": "Colombia Summer Time", "COT": "Colombia Standard Time", "CST": "Central Standard Time", "ChST": "Chamorro Standard Time", "EAT": "East Africa Time", "ECT": "Ecuador Time", "EDT": "Eastern Daylight Time", "EST": "Eastern Standard Time", "GFT": "French Guiana Time", "GMT": "Greenwich Mean Time", "GST": "Gulf Standard Time", "GYT": "Guyana Time", "HADT": "Hawaii-Aleutian Daylight Time", "HAST": "Hawaii-Aleutian Standard Time", "HAT": "Newfoundland Daylight Time", "HECU": "Cuba Daylight Time", "HEEG": "East Greenland Summer Time", "HENOMX": "Northwest Mexico Daylight Time", "HEOG": "West Greenland Summer Time", "HEPM": "St. Pierre & Miquelon Daylight Time", "HEPMX": "Mexican Pacific Daylight Time", "HKST": "Hong Kong Summer Time", "HKT": "Hong Kong Standard Time", "HNCU": "Cuba Standard Time", "HNEG": "East Greenland Standard Time", "HNNOMX": "Northwest Mexico Standard Time", "HNOG": "West Greenland Standard Time", "HNPM": "St. Pierre & Miquelon Standard Time", "HNPMX": "Mexican Pacific Standard Time", "HNT": "Newfoundland Standard Time", "IST": "India Standard Time", "JDT": "Japan Daylight Time", "JST": "Japan Standard Time", "LHDT": "Lord Howe Daylight Time", "LHST": "Lord Howe Standard Time", "MDT": "Mountain Daylight Time", "MESZ": "Central European Summer Time", "MEZ": "Central European Standard Time", "MST": "Mountain Standard Time", "MYT": "Malaysia Time", "NZDT": "New Zealand Daylight Time", "NZST": "New Zealand Standard Time", "OESZ": "Eastern European Summer Time", "OEZ": "Eastern European Standard Time", "PDT": "Pacific Daylight Time", "PST": "Pacific Standard Time", "SAST": "South Africa Standard Time", "SGT": "Singapore Standard Time", "SRT": "Suriname Time", "TMST": "Turkmenistan Summer Time", "TMT": "Turkmenistan Standard Time", "UYST": "Uruguay Summer Time", "UYT": "Uruguay Standard Time", "VET": "Venezuela Time", "WARST": "Western Argentina Summer Time", "WART": "Western Argentina Standard Time", "WAST": "West Africa Summer Time", "WAT": "West Africa Standard Time", "WESZ": "Western European Summer Time", "WEZ": "Western European Standard Time", "WIB": "Western Indonesia Time", "WIT": "Eastern Indonesia Time", "WITA": "Central Indonesia Time", "∅∅∅": "Brasilia Summer Time"}, + } +} + +// Locale returns the current translators string locale +func (en *en) Locale() string { + return en.locale +} + +// PluralsCardinal returns the list of cardinal plural rules associated with 'en' +func (en *en) PluralsCardinal() []locales.PluralRule { + return en.pluralsCardinal +} + +// PluralsOrdinal returns the list of ordinal plural rules associated with 'en' +func (en *en) PluralsOrdinal() []locales.PluralRule { + return en.pluralsOrdinal +} + +// PluralsRange returns the list of range plural rules associated with 'en' +func (en *en) PluralsRange() []locales.PluralRule { + return en.pluralsRange +} + +// CardinalPluralRule returns the cardinal PluralRule given 'num' and digits/precision of 'v' for 'en' +func (en *en) CardinalPluralRule(num float64, v uint64) locales.PluralRule { + + n := math.Abs(num) + i := int64(n) + + if i == 1 && v == 0 { + return locales.PluralRuleOne + } + + return locales.PluralRuleOther +} + +// OrdinalPluralRule returns the ordinal PluralRule given 'num' and digits/precision of 'v' for 'en' +func (en *en) OrdinalPluralRule(num float64, v uint64) locales.PluralRule { + + n := math.Abs(num) + nMod100 := math.Mod(n, 100) + nMod10 := math.Mod(n, 10) + + if nMod10 == 1 && nMod100 != 11 { + return locales.PluralRuleOne + } else if nMod10 == 2 && nMod100 != 12 { + return locales.PluralRuleTwo + } else if nMod10 == 3 && nMod100 != 13 { + return locales.PluralRuleFew + } + + return locales.PluralRuleOther +} + +// RangePluralRule returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for 'en' +func (en *en) RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) locales.PluralRule { + return locales.PluralRuleOther +} + +// MonthAbbreviated returns the locales abbreviated month given the 'month' provided +func (en *en) MonthAbbreviated(month time.Month) string { + return en.monthsAbbreviated[month] +} + +// MonthsAbbreviated returns the locales abbreviated months +func (en *en) MonthsAbbreviated() []string { + return en.monthsAbbreviated[1:] +} + +// MonthNarrow returns the locales narrow month given the 'month' provided +func (en *en) MonthNarrow(month time.Month) string { + return en.monthsNarrow[month] +} + +// MonthsNarrow returns the locales narrow months +func (en *en) MonthsNarrow() []string { + return en.monthsNarrow[1:] +} + +// MonthWide returns the locales wide month given the 'month' provided +func (en *en) MonthWide(month time.Month) string { + return en.monthsWide[month] +} + +// MonthsWide returns the locales wide months +func (en *en) MonthsWide() []string { + return en.monthsWide[1:] +} + +// WeekdayAbbreviated returns the locales abbreviated weekday given the 'weekday' provided +func (en *en) WeekdayAbbreviated(weekday time.Weekday) string { + return en.daysAbbreviated[weekday] +} + +// WeekdaysAbbreviated returns the locales abbreviated weekdays +func (en *en) WeekdaysAbbreviated() []string { + return en.daysAbbreviated +} + +// WeekdayNarrow returns the locales narrow weekday given the 'weekday' provided +func (en *en) WeekdayNarrow(weekday time.Weekday) string { + return en.daysNarrow[weekday] +} + +// WeekdaysNarrow returns the locales narrow weekdays +func (en *en) WeekdaysNarrow() []string { + return en.daysNarrow +} + +// WeekdayShort returns the locales short weekday given the 'weekday' provided +func (en *en) WeekdayShort(weekday time.Weekday) string { + return en.daysShort[weekday] +} + +// WeekdaysShort returns the locales short weekdays +func (en *en) WeekdaysShort() []string { + return en.daysShort +} + +// WeekdayWide returns the locales wide weekday given the 'weekday' provided +func (en *en) WeekdayWide(weekday time.Weekday) string { + return en.daysWide[weekday] +} + +// WeekdaysWide returns the locales wide weekdays +func (en *en) WeekdaysWide() []string { + return en.daysWide +} + +// Decimal returns the decimal point of number +func (en *en) Decimal() string { + return en.decimal +} + +// Group returns the group of number +func (en *en) Group() string { + return en.group +} + +// Group returns the minus sign of number +func (en *en) Minus() string { + return en.minus +} + +// FmtNumber returns 'num' with digits/precision of 'v' for 'en' and handles both Whole and Real numbers based on 'v' +func (en *en) FmtNumber(num float64, v uint64) string { + + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + l := len(s) + 2 + 1*len(s[:len(s)-int(v)-1])/3 + count := 0 + inWhole := v == 0 + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, en.decimal[0]) + inWhole = true + continue + } + + if inWhole { + if count == 3 { + b = append(b, en.group[0]) + count = 1 + } else { + count++ + } + } + + b = append(b, s[i]) + } + + if num < 0 { + b = append(b, en.minus[0]) + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + return string(b) +} + +// FmtPercent returns 'num' with digits/precision of 'v' for 'en' and handles both Whole and Real numbers based on 'v' +// NOTE: 'num' passed into FmtPercent is assumed to be in percent already +func (en *en) FmtPercent(num float64, v uint64) string { + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + l := len(s) + 3 + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, en.decimal[0]) + continue + } + + b = append(b, s[i]) + } + + if num < 0 { + b = append(b, en.minus[0]) + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + b = append(b, en.percent...) + + return string(b) +} + +// FmtCurrency returns the currency representation of 'num' with digits/precision of 'v' for 'en' +func (en *en) FmtCurrency(num float64, v uint64, currency currency.Type) string { + + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + symbol := en.currencies[currency] + l := len(s) + len(symbol) + 2 + 1*len(s[:len(s)-int(v)-1])/3 + count := 0 + inWhole := v == 0 + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, en.decimal[0]) + inWhole = true + continue + } + + if inWhole { + if count == 3 { + b = append(b, en.group[0]) + count = 1 + } else { + count++ + } + } + + b = append(b, s[i]) + } + + for j := len(symbol) - 1; j >= 0; j-- { + b = append(b, symbol[j]) + } + + if num < 0 { + b = append(b, en.minus[0]) + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + if int(v) < 2 { + + if v == 0 { + b = append(b, en.decimal...) + } + + for i := 0; i < 2-int(v); i++ { + b = append(b, '0') + } + } + + return string(b) +} + +// FmtAccounting returns the currency representation of 'num' with digits/precision of 'v' for 'en' +// in accounting notation. +func (en *en) FmtAccounting(num float64, v uint64, currency currency.Type) string { + + s := strconv.FormatFloat(math.Abs(num), 'f', int(v), 64) + symbol := en.currencies[currency] + l := len(s) + len(symbol) + 4 + 1*len(s[:len(s)-int(v)-1])/3 + count := 0 + inWhole := v == 0 + b := make([]byte, 0, l) + + for i := len(s) - 1; i >= 0; i-- { + + if s[i] == '.' { + b = append(b, en.decimal[0]) + inWhole = true + continue + } + + if inWhole { + if count == 3 { + b = append(b, en.group[0]) + count = 1 + } else { + count++ + } + } + + b = append(b, s[i]) + } + + if num < 0 { + + for j := len(symbol) - 1; j >= 0; j-- { + b = append(b, symbol[j]) + } + + b = append(b, en.currencyNegativePrefix[0]) + + } else { + + for j := len(symbol) - 1; j >= 0; j-- { + b = append(b, symbol[j]) + } + + } + + // reverse + for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { + b[i], b[j] = b[j], b[i] + } + + if int(v) < 2 { + + if v == 0 { + b = append(b, en.decimal...) + } + + for i := 0; i < 2-int(v); i++ { + b = append(b, '0') + } + } + + if num < 0 { + b = append(b, en.currencyNegativeSuffix...) + } + + return string(b) +} + +// FmtDateShort returns the short date representation of 't' for 'en' +func (en *en) FmtDateShort(t time.Time) string { + + b := make([]byte, 0, 32) + + b = strconv.AppendInt(b, int64(t.Month()), 10) + b = append(b, []byte{0x2f}...) + b = strconv.AppendInt(b, int64(t.Day()), 10) + b = append(b, []byte{0x2f}...) + + if t.Year() > 9 { + b = append(b, strconv.Itoa(t.Year())[2:]...) + } else { + b = append(b, strconv.Itoa(t.Year())[1:]...) + } + + return string(b) +} + +// FmtDateMedium returns the medium date representation of 't' for 'en' +func (en *en) FmtDateMedium(t time.Time) string { + + b := make([]byte, 0, 32) + + b = append(b, en.monthsAbbreviated[t.Month()]...) + b = append(b, []byte{0x20}...) + b = strconv.AppendInt(b, int64(t.Day()), 10) + b = append(b, []byte{0x2c, 0x20}...) + + if t.Year() > 0 { + b = strconv.AppendInt(b, int64(t.Year()), 10) + } else { + b = strconv.AppendInt(b, int64(-t.Year()), 10) + } + + return string(b) +} + +// FmtDateLong returns the long date representation of 't' for 'en' +func (en *en) FmtDateLong(t time.Time) string { + + b := make([]byte, 0, 32) + + b = append(b, en.monthsWide[t.Month()]...) + b = append(b, []byte{0x20}...) + b = strconv.AppendInt(b, int64(t.Day()), 10) + b = append(b, []byte{0x2c, 0x20}...) + + if t.Year() > 0 { + b = strconv.AppendInt(b, int64(t.Year()), 10) + } else { + b = strconv.AppendInt(b, int64(-t.Year()), 10) + } + + return string(b) +} + +// FmtDateFull returns the full date representation of 't' for 'en' +func (en *en) FmtDateFull(t time.Time) string { + + b := make([]byte, 0, 32) + + b = append(b, en.daysWide[t.Weekday()]...) + b = append(b, []byte{0x2c, 0x20}...) + b = append(b, en.monthsWide[t.Month()]...) + b = append(b, []byte{0x20}...) + b = strconv.AppendInt(b, int64(t.Day()), 10) + b = append(b, []byte{0x2c, 0x20}...) + + if t.Year() > 0 { + b = strconv.AppendInt(b, int64(t.Year()), 10) + } else { + b = strconv.AppendInt(b, int64(-t.Year()), 10) + } + + return string(b) +} + +// FmtTimeShort returns the short time representation of 't' for 'en' +func (en *en) FmtTimeShort(t time.Time) string { + + b := make([]byte, 0, 32) + + h := t.Hour() + + if h > 12 { + h -= 12 + } + + b = strconv.AppendInt(b, int64(h), 10) + b = append(b, en.timeSeparator...) + + if t.Minute() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Minute()), 10) + b = append(b, []byte{0x20}...) + + if t.Hour() < 12 { + b = append(b, en.periodsAbbreviated[0]...) + } else { + b = append(b, en.periodsAbbreviated[1]...) + } + + return string(b) +} + +// FmtTimeMedium returns the medium time representation of 't' for 'en' +func (en *en) FmtTimeMedium(t time.Time) string { + + b := make([]byte, 0, 32) + + h := t.Hour() + + if h > 12 { + h -= 12 + } + + b = strconv.AppendInt(b, int64(h), 10) + b = append(b, en.timeSeparator...) + + if t.Minute() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Minute()), 10) + b = append(b, en.timeSeparator...) + + if t.Second() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Second()), 10) + b = append(b, []byte{0x20}...) + + if t.Hour() < 12 { + b = append(b, en.periodsAbbreviated[0]...) + } else { + b = append(b, en.periodsAbbreviated[1]...) + } + + return string(b) +} + +// FmtTimeLong returns the long time representation of 't' for 'en' +func (en *en) FmtTimeLong(t time.Time) string { + + b := make([]byte, 0, 32) + + h := t.Hour() + + if h > 12 { + h -= 12 + } + + b = strconv.AppendInt(b, int64(h), 10) + b = append(b, en.timeSeparator...) + + if t.Minute() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Minute()), 10) + b = append(b, en.timeSeparator...) + + if t.Second() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Second()), 10) + b = append(b, []byte{0x20}...) + + if t.Hour() < 12 { + b = append(b, en.periodsAbbreviated[0]...) + } else { + b = append(b, en.periodsAbbreviated[1]...) + } + + b = append(b, []byte{0x20}...) + + tz, _ := t.Zone() + b = append(b, tz...) + + return string(b) +} + +// FmtTimeFull returns the full time representation of 't' for 'en' +func (en *en) FmtTimeFull(t time.Time) string { + + b := make([]byte, 0, 32) + + h := t.Hour() + + if h > 12 { + h -= 12 + } + + b = strconv.AppendInt(b, int64(h), 10) + b = append(b, en.timeSeparator...) + + if t.Minute() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Minute()), 10) + b = append(b, en.timeSeparator...) + + if t.Second() < 10 { + b = append(b, '0') + } + + b = strconv.AppendInt(b, int64(t.Second()), 10) + b = append(b, []byte{0x20}...) + + if t.Hour() < 12 { + b = append(b, en.periodsAbbreviated[0]...) + } else { + b = append(b, en.periodsAbbreviated[1]...) + } + + b = append(b, []byte{0x20}...) + + tz, _ := t.Zone() + + if btz, ok := en.timezones[tz]; ok { + b = append(b, btz...) + } else { + b = append(b, tz...) + } + + return string(b) +} diff --git a/vendor/github.com/go-playground/locales/logo.png b/vendor/github.com/go-playground/locales/logo.png new file mode 100644 index 0000000..3038276 Binary files /dev/null and b/vendor/github.com/go-playground/locales/logo.png differ diff --git a/vendor/github.com/go-playground/locales/rules.go b/vendor/github.com/go-playground/locales/rules.go new file mode 100644 index 0000000..9202900 --- /dev/null +++ b/vendor/github.com/go-playground/locales/rules.go @@ -0,0 +1,293 @@ +package locales + +import ( + "strconv" + "time" + + "github.com/go-playground/locales/currency" +) + +// // ErrBadNumberValue is returned when the number passed for +// // plural rule determination cannot be parsed +// type ErrBadNumberValue struct { +// NumberValue string +// InnerError error +// } + +// // Error returns ErrBadNumberValue error string +// func (e *ErrBadNumberValue) Error() string { +// return fmt.Sprintf("Invalid Number Value '%s' %s", e.NumberValue, e.InnerError) +// } + +// var _ error = new(ErrBadNumberValue) + +// PluralRule denotes the type of plural rules +type PluralRule int + +// PluralRule's +const ( + PluralRuleUnknown PluralRule = iota + PluralRuleZero // zero + PluralRuleOne // one - singular + PluralRuleTwo // two - dual + PluralRuleFew // few - paucal + PluralRuleMany // many - also used for fractions if they have a separate class + PluralRuleOther // other - required—general plural form—also used if the language only has a single form +) + +const ( + pluralsString = "UnknownZeroOneTwoFewManyOther" +) + +// Translator encapsulates an instance of a locale +// NOTE: some values are returned as a []byte just in case the caller +// wishes to add more and can help avoid allocations; otherwise just cast as string +type Translator interface { + + // The following Functions are for overriding, debugging or developing + // with a Translator Locale + + // Locale returns the string value of the translator + Locale() string + + // returns an array of cardinal plural rules associated + // with this translator + PluralsCardinal() []PluralRule + + // returns an array of ordinal plural rules associated + // with this translator + PluralsOrdinal() []PluralRule + + // returns an array of range plural rules associated + // with this translator + PluralsRange() []PluralRule + + // returns the cardinal PluralRule given 'num' and digits/precision of 'v' for locale + CardinalPluralRule(num float64, v uint64) PluralRule + + // returns the ordinal PluralRule given 'num' and digits/precision of 'v' for locale + OrdinalPluralRule(num float64, v uint64) PluralRule + + // returns the ordinal PluralRule given 'num1', 'num2' and digits/precision of 'v1' and 'v2' for locale + RangePluralRule(num1 float64, v1 uint64, num2 float64, v2 uint64) PluralRule + + // returns the locales abbreviated month given the 'month' provided + MonthAbbreviated(month time.Month) string + + // returns the locales abbreviated months + MonthsAbbreviated() []string + + // returns the locales narrow month given the 'month' provided + MonthNarrow(month time.Month) string + + // returns the locales narrow months + MonthsNarrow() []string + + // returns the locales wide month given the 'month' provided + MonthWide(month time.Month) string + + // returns the locales wide months + MonthsWide() []string + + // returns the locales abbreviated weekday given the 'weekday' provided + WeekdayAbbreviated(weekday time.Weekday) string + + // returns the locales abbreviated weekdays + WeekdaysAbbreviated() []string + + // returns the locales narrow weekday given the 'weekday' provided + WeekdayNarrow(weekday time.Weekday) string + + // WeekdaysNarrowreturns the locales narrow weekdays + WeekdaysNarrow() []string + + // returns the locales short weekday given the 'weekday' provided + WeekdayShort(weekday time.Weekday) string + + // returns the locales short weekdays + WeekdaysShort() []string + + // returns the locales wide weekday given the 'weekday' provided + WeekdayWide(weekday time.Weekday) string + + // returns the locales wide weekdays + WeekdaysWide() []string + + // The following Functions are common Formatting functionsfor the Translator's Locale + + // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' + FmtNumber(num float64, v uint64) string + + // returns 'num' with digits/precision of 'v' for locale and handles both Whole and Real numbers based on 'v' + // NOTE: 'num' passed into FmtPercent is assumed to be in percent already + FmtPercent(num float64, v uint64) string + + // returns the currency representation of 'num' with digits/precision of 'v' for locale + FmtCurrency(num float64, v uint64, currency currency.Type) string + + // returns the currency representation of 'num' with digits/precision of 'v' for locale + // in accounting notation. + FmtAccounting(num float64, v uint64, currency currency.Type) string + + // returns the short date representation of 't' for locale + FmtDateShort(t time.Time) string + + // returns the medium date representation of 't' for locale + FmtDateMedium(t time.Time) string + + // returns the long date representation of 't' for locale + FmtDateLong(t time.Time) string + + // returns the full date representation of 't' for locale + FmtDateFull(t time.Time) string + + // returns the short time representation of 't' for locale + FmtTimeShort(t time.Time) string + + // returns the medium time representation of 't' for locale + FmtTimeMedium(t time.Time) string + + // returns the long time representation of 't' for locale + FmtTimeLong(t time.Time) string + + // returns the full time representation of 't' for locale + FmtTimeFull(t time.Time) string +} + +// String returns the string value of PluralRule +func (p PluralRule) String() string { + + switch p { + case PluralRuleZero: + return pluralsString[7:11] + case PluralRuleOne: + return pluralsString[11:14] + case PluralRuleTwo: + return pluralsString[14:17] + case PluralRuleFew: + return pluralsString[17:20] + case PluralRuleMany: + return pluralsString[20:24] + case PluralRuleOther: + return pluralsString[24:] + default: + return pluralsString[:7] + } +} + +// +// Precision Notes: +// +// must specify a precision >= 0, and here is why https://play.golang.org/p/LyL90U0Vyh +// +// v := float64(3.141) +// i := float64(int64(v)) +// +// fmt.Println(v - i) +// +// or +// +// s := strconv.FormatFloat(v-i, 'f', -1, 64) +// fmt.Println(s) +// +// these will not print what you'd expect: 0.14100000000000001 +// and so this library requires a precision to be specified, or +// inaccurate plural rules could be applied. +// +// +// +// n - absolute value of the source number (integer and decimals). +// i - integer digits of n. +// v - number of visible fraction digits in n, with trailing zeros. +// w - number of visible fraction digits in n, without trailing zeros. +// f - visible fractional digits in n, with trailing zeros. +// t - visible fractional digits in n, without trailing zeros. +// +// +// Func(num float64, v uint64) // v = digits/precision and prevents -1 as a special case as this can lead to very unexpected behaviour, see precision note's above. +// +// n := math.Abs(num) +// i := int64(n) +// v := v +// +// +// w := strconv.FormatFloat(num-float64(i), 'f', int(v), 64) // then parse backwards on string until no more zero's.... +// f := strconv.FormatFloat(n, 'f', int(v), 64) // then turn everything after decimal into an int64 +// t := strconv.FormatFloat(n, 'f', int(v), 64) // then parse backwards on string until no more zero's.... +// +// +// +// General Inclusion Rules +// - v will always be available inherently +// - all require n +// - w requires i +// + +// W returns the number of visible fraction digits in N, without trailing zeros. +func W(n float64, v uint64) (w int64) { + + s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) + + // with either be '0' or '0.xxxx', so if 1 then w will be zero + // otherwise need to parse + if len(s) != 1 { + + s = s[2:] + end := len(s) + 1 + + for i := end; i >= 0; i-- { + if s[i] != '0' { + end = i + 1 + break + } + } + + w = int64(len(s[:end])) + } + + return +} + +// F returns the visible fractional digits in N, with trailing zeros. +func F(n float64, v uint64) (f int64) { + + s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) + + // with either be '0' or '0.xxxx', so if 1 then f will be zero + // otherwise need to parse + if len(s) != 1 { + + // ignoring error, because it can't fail as we generated + // the string internally from a real number + f, _ = strconv.ParseInt(s[2:], 10, 64) + } + + return +} + +// T returns the visible fractional digits in N, without trailing zeros. +func T(n float64, v uint64) (t int64) { + + s := strconv.FormatFloat(n-float64(int64(n)), 'f', int(v), 64) + + // with either be '0' or '0.xxxx', so if 1 then t will be zero + // otherwise need to parse + if len(s) != 1 { + + s = s[2:] + end := len(s) + 1 + + for i := end; i >= 0; i-- { + if s[i] != '0' { + end = i + 1 + break + } + } + + // ignoring error, because it can't fail as we generated + // the string internally from a real number + t, _ = strconv.ParseInt(s[:end], 10, 64) + } + + return +} diff --git a/vendor/github.com/go-playground/universal-translator/.gitignore b/vendor/github.com/go-playground/universal-translator/.gitignore new file mode 100644 index 0000000..bc4e07f --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/.gitignore @@ -0,0 +1,25 @@ +# 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 +*.coverprofile \ No newline at end of file diff --git a/vendor/github.com/go-playground/universal-translator/.travis.yml b/vendor/github.com/go-playground/universal-translator/.travis.yml new file mode 100644 index 0000000..39b8b92 --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/.travis.yml @@ -0,0 +1,27 @@ +language: go +go: + - 1.13.4 + - tip +matrix: + allow_failures: + - go: tip + +notifications: + email: + recipients: dean.karn@gmail.com + on_success: change + on_failure: always + +before_install: + - go install github.com/mattn/goveralls + +# Only clone the most recent commit. +git: + depth: 1 + +script: + - go test -v -race -covermode=atomic -coverprofile=coverage.coverprofile ./... + +after_success: | + [ $TRAVIS_GO_VERSION = 1.13.4 ] && + goveralls -coverprofile=coverage.coverprofile -service travis-ci -repotoken $COVERALLS_TOKEN \ No newline at end of file diff --git a/vendor/github.com/go-playground/universal-translator/LICENSE b/vendor/github.com/go-playground/universal-translator/LICENSE new file mode 100644 index 0000000..8d8aba1 --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Go Playground + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/go-playground/universal-translator/Makefile b/vendor/github.com/go-playground/universal-translator/Makefile new file mode 100644 index 0000000..ec3455b --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/Makefile @@ -0,0 +1,18 @@ +GOCMD=GO111MODULE=on go + +linters-install: + @golangci-lint --version >/dev/null 2>&1 || { \ + echo "installing linting tools..."; \ + curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh -s v1.41.1; \ + } + +lint: linters-install + golangci-lint run + +test: + $(GOCMD) test -cover -race ./... + +bench: + $(GOCMD) test -bench=. -benchmem ./... + +.PHONY: test lint linters-install \ No newline at end of file diff --git a/vendor/github.com/go-playground/universal-translator/README.md b/vendor/github.com/go-playground/universal-translator/README.md new file mode 100644 index 0000000..d9b6654 --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/README.md @@ -0,0 +1,87 @@ +## universal-translator +![Project status](https://img.shields.io/badge/version-0.18.1-green.svg) +[![Coverage Status](https://coveralls.io/repos/github/go-playground/universal-translator/badge.svg)](https://coveralls.io/github/go-playground/universal-translator) +[![Go Report Card](https://goreportcard.com/badge/github.com/go-playground/universal-translator)](https://goreportcard.com/report/github.com/go-playground/universal-translator) +[![GoDoc](https://godoc.org/github.com/go-playground/universal-translator?status.svg)](https://godoc.org/github.com/go-playground/universal-translator) +![License](https://img.shields.io/dub/l/vibe-d.svg) + +Universal Translator is an i18n Translator for Go/Golang using CLDR data + pluralization rules + +Why another i18n library? +-------------------------- +Because none of the plural rules seem to be correct out there, including the previous implementation of this package, +so I took it upon myself to create [locales](https://github.com/go-playground/locales) for everyone to use; this package +is a thin wrapper around [locales](https://github.com/go-playground/locales) in order to store and translate text for +use in your applications. + +Features +-------- +- [x] Rules generated from the [CLDR](http://cldr.unicode.org/index/downloads) data, v36.0.1 +- [x] Contains Cardinal, Ordinal and Range Plural Rules +- [x] Contains Month, Weekday and Timezone translations built in +- [x] Contains Date & Time formatting functions +- [x] Contains Number, Currency, Accounting and Percent formatting functions +- [x] Supports the "Gregorian" calendar only ( my time isn't unlimited, had to draw the line somewhere ) +- [x] Support loading translations from files +- [x] Exporting translations to file(s), mainly for getting them professionally translated +- [ ] Code Generation for translation files -> Go code.. i.e. after it has been professionally translated +- [ ] Tests for all languages, I need help with this, please see [here](https://github.com/go-playground/locales/issues/1) + +Installation +----------- + +Use go get + +```shell +go get github.com/go-playground/universal-translator +``` + +Usage & Documentation +------- + +Please see https://godoc.org/github.com/go-playground/universal-translator for usage docs + +##### Examples: + +- [Basic](https://github.com/go-playground/universal-translator/tree/master/_examples/basic) +- [Full - no files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-no-files) +- [Full - with files](https://github.com/go-playground/universal-translator/tree/master/_examples/full-with-files) + +File formatting +-------------- +All types, Plain substitution, Cardinal, Ordinal and Range translations can all be contained within the same file(s); +they are only separated for easy viewing. + +##### Examples: + +- [Formats](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) + +##### Basic Makeup +NOTE: not all fields are needed for all translation types, see [examples](https://github.com/go-playground/universal-translator/tree/master/_examples/file-formats) +```json +{ + "locale": "en", + "key": "days-left", + "trans": "You have {0} day left.", + "type": "Cardinal", + "rule": "One", + "override": false +} +``` +|Field|Description| +|---|---| +|locale|The locale for which the translation is for.| +|key|The translation key that will be used to store and lookup each translation; normally it is a string or integer.| +|trans|The actual translation text.| +|type|The type of translation Cardinal, Ordinal, Range or "" for a plain substitution(not required to be defined if plain used)| +|rule|The plural rule for which the translation is for eg. One, Two, Few, Many or Other.(not required to be defined if plain used)| +|override|If you wish to override an existing translation that has already been registered, set this to 'true'. 99% of the time there is no need to define it.| + +Help With Tests +--------------- +To anyone interesting in helping or contributing, I sure could use some help creating tests for each language. +Please see issue [here](https://github.com/go-playground/locales/issues/1) for details. + +License +------ +Distributed under MIT License, please see license file in code for more details. diff --git a/vendor/github.com/go-playground/universal-translator/errors.go b/vendor/github.com/go-playground/universal-translator/errors.go new file mode 100644 index 0000000..38b163b --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/errors.go @@ -0,0 +1,148 @@ +package ut + +import ( + "errors" + "fmt" + + "github.com/go-playground/locales" +) + +var ( + // ErrUnknowTranslation indicates the translation could not be found + ErrUnknowTranslation = errors.New("Unknown Translation") +) + +var _ error = new(ErrConflictingTranslation) +var _ error = new(ErrRangeTranslation) +var _ error = new(ErrOrdinalTranslation) +var _ error = new(ErrCardinalTranslation) +var _ error = new(ErrMissingPluralTranslation) +var _ error = new(ErrExistingTranslator) + +// ErrExistingTranslator is the error representing a conflicting translator +type ErrExistingTranslator struct { + locale string +} + +// Error returns ErrExistingTranslator's internal error text +func (e *ErrExistingTranslator) Error() string { + return fmt.Sprintf("error: conflicting translator for locale '%s'", e.locale) +} + +// ErrConflictingTranslation is the error representing a conflicting translation +type ErrConflictingTranslation struct { + locale string + key interface{} + rule locales.PluralRule + text string +} + +// Error returns ErrConflictingTranslation's internal error text +func (e *ErrConflictingTranslation) Error() string { + + if _, ok := e.key.(string); !ok { + return fmt.Sprintf("error: conflicting key '%#v' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) + } + + return fmt.Sprintf("error: conflicting key '%s' rule '%s' with text '%s' for locale '%s', value being ignored", e.key, e.rule, e.text, e.locale) +} + +// ErrRangeTranslation is the error representing a range translation error +type ErrRangeTranslation struct { + text string +} + +// Error returns ErrRangeTranslation's internal error text +func (e *ErrRangeTranslation) Error() string { + return e.text +} + +// ErrOrdinalTranslation is the error representing an ordinal translation error +type ErrOrdinalTranslation struct { + text string +} + +// Error returns ErrOrdinalTranslation's internal error text +func (e *ErrOrdinalTranslation) Error() string { + return e.text +} + +// ErrCardinalTranslation is the error representing a cardinal translation error +type ErrCardinalTranslation struct { + text string +} + +// Error returns ErrCardinalTranslation's internal error text +func (e *ErrCardinalTranslation) Error() string { + return e.text +} + +// ErrMissingPluralTranslation is the error signifying a missing translation given +// the locales plural rules. +type ErrMissingPluralTranslation struct { + locale string + key interface{} + rule locales.PluralRule + translationType string +} + +// Error returns ErrMissingPluralTranslation's internal error text +func (e *ErrMissingPluralTranslation) Error() string { + + if _, ok := e.key.(string); !ok { + return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%#v' and locale '%s'", e.translationType, e.rule, e.key, e.locale) + } + + return fmt.Sprintf("error: missing '%s' plural rule '%s' for translation with key '%s' and locale '%s'", e.translationType, e.rule, e.key, e.locale) +} + +// ErrMissingBracket is the error representing a missing bracket in a translation +// eg. This is a {0 <-- missing ending '}' +type ErrMissingBracket struct { + locale string + key interface{} + text string +} + +// Error returns ErrMissingBracket error message +func (e *ErrMissingBracket) Error() string { + return fmt.Sprintf("error: missing bracket '{}', in translation. locale: '%s' key: '%v' text: '%s'", e.locale, e.key, e.text) +} + +// ErrBadParamSyntax is the error representing a bad parameter definition in a translation +// eg. This is a {must-be-int} +type ErrBadParamSyntax struct { + locale string + param string + key interface{} + text string +} + +// Error returns ErrBadParamSyntax error message +func (e *ErrBadParamSyntax) Error() string { + return fmt.Sprintf("error: bad parameter syntax, missing parameter '%s' in translation. locale: '%s' key: '%v' text: '%s'", e.param, e.locale, e.key, e.text) +} + +// import/export errors + +// ErrMissingLocale is the error representing an expected locale that could +// not be found aka locale not registered with the UniversalTranslator Instance +type ErrMissingLocale struct { + locale string +} + +// Error returns ErrMissingLocale's internal error text +func (e *ErrMissingLocale) Error() string { + return fmt.Sprintf("error: locale '%s' not registered.", e.locale) +} + +// ErrBadPluralDefinition is the error representing an incorrect plural definition +// usually found within translations defined within files during the import process. +type ErrBadPluralDefinition struct { + tl translation +} + +// Error returns ErrBadPluralDefinition's internal error text +func (e *ErrBadPluralDefinition) Error() string { + return fmt.Sprintf("error: bad plural definition '%#v'", e.tl) +} diff --git a/vendor/github.com/go-playground/universal-translator/import_export.go b/vendor/github.com/go-playground/universal-translator/import_export.go new file mode 100644 index 0000000..87a1b46 --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/import_export.go @@ -0,0 +1,274 @@ +package ut + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + + "io" + + "github.com/go-playground/locales" +) + +type translation struct { + Locale string `json:"locale"` + Key interface{} `json:"key"` // either string or integer + Translation string `json:"trans"` + PluralType string `json:"type,omitempty"` + PluralRule string `json:"rule,omitempty"` + OverrideExisting bool `json:"override,omitempty"` +} + +const ( + cardinalType = "Cardinal" + ordinalType = "Ordinal" + rangeType = "Range" +) + +// ImportExportFormat is the format of the file import or export +type ImportExportFormat uint8 + +// supported Export Formats +const ( + FormatJSON ImportExportFormat = iota +) + +// Export writes the translations out to a file on disk. +// +// NOTE: this currently only works with string or int translations keys. +func (t *UniversalTranslator) Export(format ImportExportFormat, dirname string) error { + + _, err := os.Stat(dirname) + if err != nil { + + if !os.IsNotExist(err) { + return err + } + + if err = os.MkdirAll(dirname, 0744); err != nil { + return err + } + } + + // build up translations + var trans []translation + var b []byte + var ext string + + for _, locale := range t.translators { + + for k, v := range locale.(*translator).translations { + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k, + Translation: v.text, + }) + } + + for k, pluralTrans := range locale.(*translator).cardinalTanslations { + + for i, plural := range pluralTrans { + + // leave enough for all plural rules + // but not all are set for all languages. + if plural == nil { + continue + } + + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k.(string), + Translation: plural.text, + PluralType: cardinalType, + PluralRule: locales.PluralRule(i).String(), + }) + } + } + + for k, pluralTrans := range locale.(*translator).ordinalTanslations { + + for i, plural := range pluralTrans { + + // leave enough for all plural rules + // but not all are set for all languages. + if plural == nil { + continue + } + + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k.(string), + Translation: plural.text, + PluralType: ordinalType, + PluralRule: locales.PluralRule(i).String(), + }) + } + } + + for k, pluralTrans := range locale.(*translator).rangeTanslations { + + for i, plural := range pluralTrans { + + // leave enough for all plural rules + // but not all are set for all languages. + if plural == nil { + continue + } + + trans = append(trans, translation{ + Locale: locale.Locale(), + Key: k.(string), + Translation: plural.text, + PluralType: rangeType, + PluralRule: locales.PluralRule(i).String(), + }) + } + } + + switch format { + case FormatJSON: + b, err = json.MarshalIndent(trans, "", " ") + ext = ".json" + } + + if err != nil { + return err + } + + err = os.WriteFile(filepath.Join(dirname, fmt.Sprintf("%s%s", locale.Locale(), ext)), b, 0644) + if err != nil { + return err + } + + trans = trans[0:0] + } + + return nil +} + +// Import reads the translations out of a file or directory on disk. +// +// NOTE: this currently only works with string or int translations keys. +func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilename string) error { + + fi, err := os.Stat(dirnameOrFilename) + if err != nil { + return err + } + + processFn := func(filename string) error { + + f, err := os.Open(filename) + if err != nil { + return err + } + defer f.Close() + + return t.ImportByReader(format, f) + } + + if !fi.IsDir() { + return processFn(dirnameOrFilename) + } + + // recursively go through directory + walker := func(path string, info os.FileInfo, err error) error { + + if info.IsDir() { + return nil + } + + switch format { + case FormatJSON: + // skip non JSON files + if filepath.Ext(info.Name()) != ".json" { + return nil + } + } + + return processFn(path) + } + + return filepath.Walk(dirnameOrFilename, walker) +} + +// ImportByReader imports the the translations found within the contents read from the supplied reader. +// +// NOTE: generally used when assets have been embedded into the binary and are already in memory. +func (t *UniversalTranslator) ImportByReader(format ImportExportFormat, reader io.Reader) error { + + b, err := io.ReadAll(reader) + if err != nil { + return err + } + + var trans []translation + + switch format { + case FormatJSON: + err = json.Unmarshal(b, &trans) + } + + if err != nil { + return err + } + + for _, tl := range trans { + + locale, found := t.FindTranslator(tl.Locale) + if !found { + return &ErrMissingLocale{locale: tl.Locale} + } + + pr := stringToPR(tl.PluralRule) + + if pr == locales.PluralRuleUnknown { + + err = locale.Add(tl.Key, tl.Translation, tl.OverrideExisting) + if err != nil { + return err + } + + continue + } + + switch tl.PluralType { + case cardinalType: + err = locale.AddCardinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) + case ordinalType: + err = locale.AddOrdinal(tl.Key, tl.Translation, pr, tl.OverrideExisting) + case rangeType: + err = locale.AddRange(tl.Key, tl.Translation, pr, tl.OverrideExisting) + default: + return &ErrBadPluralDefinition{tl: tl} + } + + if err != nil { + return err + } + } + + return nil +} + +func stringToPR(s string) locales.PluralRule { + + switch s { + case "Zero": + return locales.PluralRuleZero + case "One": + return locales.PluralRuleOne + case "Two": + return locales.PluralRuleTwo + case "Few": + return locales.PluralRuleFew + case "Many": + return locales.PluralRuleMany + case "Other": + return locales.PluralRuleOther + default: + return locales.PluralRuleUnknown + } + +} diff --git a/vendor/github.com/go-playground/universal-translator/logo.png b/vendor/github.com/go-playground/universal-translator/logo.png new file mode 100644 index 0000000..a37aa8c Binary files /dev/null and b/vendor/github.com/go-playground/universal-translator/logo.png differ diff --git a/vendor/github.com/go-playground/universal-translator/translator.go b/vendor/github.com/go-playground/universal-translator/translator.go new file mode 100644 index 0000000..24b18db --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/translator.go @@ -0,0 +1,420 @@ +package ut + +import ( + "fmt" + "strconv" + "strings" + + "github.com/go-playground/locales" +) + +const ( + paramZero = "{0}" + paramOne = "{1}" + unknownTranslation = "" +) + +// Translator is universal translators +// translator instance which is a thin wrapper +// around locales.Translator instance providing +// some extra functionality +type Translator interface { + locales.Translator + + // adds a normal translation for a particular language/locale + // {#} is the only replacement type accepted and are ad infinitum + // eg. one: '{0} day left' other: '{0} days left' + Add(key interface{}, text string, override bool) error + + // adds a cardinal plural translation for a particular language/locale + // {0} is the only replacement type accepted and only one variable is accepted as + // multiple cannot be used for a plural rule determination, unless it is a range; + // see AddRange below. + // eg. in locale 'en' one: '{0} day left' other: '{0} days left' + AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error + + // adds an ordinal plural translation for a particular language/locale + // {0} is the only replacement type accepted and only one variable is accepted as + // multiple cannot be used for a plural rule determination, unless it is a range; + // see AddRange below. + // eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' + // - 1st, 2nd, 3rd... + AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error + + // adds a range plural translation for a particular language/locale + // {0} and {1} are the only replacement types accepted and only these are accepted. + // eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' + AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error + + // creates the translation for the locale given the 'key' and params passed in + T(key interface{}, params ...string) (string, error) + + // creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments + // and param passed in + C(key interface{}, num float64, digits uint64, param string) (string, error) + + // creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments + // and param passed in + O(key interface{}, num float64, digits uint64, param string) (string, error) + + // creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and + // 'digit2' arguments and 'param1' and 'param2' passed in + R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) + + // VerifyTranslations checks to ensures that no plural rules have been + // missed within the translations. + VerifyTranslations() error +} + +var _ Translator = new(translator) +var _ locales.Translator = new(translator) + +type translator struct { + locales.Translator + translations map[interface{}]*transText + cardinalTanslations map[interface{}][]*transText // array index is mapped to locales.PluralRule index + the locales.PluralRuleUnknown + ordinalTanslations map[interface{}][]*transText + rangeTanslations map[interface{}][]*transText +} + +type transText struct { + text string + indexes []int +} + +func newTranslator(trans locales.Translator) Translator { + return &translator{ + Translator: trans, + translations: make(map[interface{}]*transText), // translation text broken up by byte index + cardinalTanslations: make(map[interface{}][]*transText), + ordinalTanslations: make(map[interface{}][]*transText), + rangeTanslations: make(map[interface{}][]*transText), + } +} + +// Add adds a normal translation for a particular language/locale +// {#} is the only replacement type accepted and are ad infinitum +// eg. one: '{0} day left' other: '{0} days left' +func (t *translator) Add(key interface{}, text string, override bool) error { + + if _, ok := t.translations[key]; ok && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, text: text} + } + + lb := strings.Count(text, "{") + rb := strings.Count(text, "}") + + if lb != rb { + return &ErrMissingBracket{locale: t.Locale(), key: key, text: text} + } + + trans := &transText{ + text: text, + } + + var idx int + + for i := 0; i < lb; i++ { + s := "{" + strconv.Itoa(i) + "}" + idx = strings.Index(text, s) + if idx == -1 { + return &ErrBadParamSyntax{locale: t.Locale(), param: s, key: key, text: text} + } + + trans.indexes = append(trans.indexes, idx) + trans.indexes = append(trans.indexes, idx+len(s)) + } + + t.translations[key] = trans + + return nil +} + +// AddCardinal adds a cardinal plural translation for a particular language/locale +// {0} is the only replacement type accepted and only one variable is accepted as +// multiple cannot be used for a plural rule determination, unless it is a range; +// see AddRange below. +// eg. in locale 'en' one: '{0} day left' other: '{0} days left' +func (t *translator) AddCardinal(key interface{}, text string, rule locales.PluralRule, override bool) error { + + var verified bool + + // verify plural rule exists for locale + for _, pr := range t.PluralsCardinal() { + if pr == rule { + verified = true + break + } + } + + if !verified { + return &ErrCardinalTranslation{text: fmt.Sprintf("error: cardinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} + } + + tarr, ok := t.cardinalTanslations[key] + if ok { + // verify not adding a conflicting record + if len(tarr) > 0 && tarr[rule] != nil && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} + } + + } else { + tarr = make([]*transText, 7) + t.cardinalTanslations[key] = tarr + } + + trans := &transText{ + text: text, + indexes: make([]int, 2), + } + + tarr[rule] = trans + + idx := strings.Index(text, paramZero) + if idx == -1 { + tarr[rule] = nil + return &ErrCardinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddCardinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} + } + + trans.indexes[0] = idx + trans.indexes[1] = idx + len(paramZero) + + return nil +} + +// AddOrdinal adds an ordinal plural translation for a particular language/locale +// {0} is the only replacement type accepted and only one variable is accepted as +// multiple cannot be used for a plural rule determination, unless it is a range; +// see AddRange below. +// eg. in locale 'en' one: '{0}st day of spring' other: '{0}nd day of spring' - 1st, 2nd, 3rd... +func (t *translator) AddOrdinal(key interface{}, text string, rule locales.PluralRule, override bool) error { + + var verified bool + + // verify plural rule exists for locale + for _, pr := range t.PluralsOrdinal() { + if pr == rule { + verified = true + break + } + } + + if !verified { + return &ErrOrdinalTranslation{text: fmt.Sprintf("error: ordinal plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} + } + + tarr, ok := t.ordinalTanslations[key] + if ok { + // verify not adding a conflicting record + if len(tarr) > 0 && tarr[rule] != nil && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} + } + + } else { + tarr = make([]*transText, 7) + t.ordinalTanslations[key] = tarr + } + + trans := &transText{ + text: text, + indexes: make([]int, 2), + } + + tarr[rule] = trans + + idx := strings.Index(text, paramZero) + if idx == -1 { + tarr[rule] = nil + return &ErrOrdinalTranslation{text: fmt.Sprintf("error: parameter '%s' not found, may want to use 'Add' instead of 'AddOrdinal'. locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} + } + + trans.indexes[0] = idx + trans.indexes[1] = idx + len(paramZero) + + return nil +} + +// AddRange adds a range plural translation for a particular language/locale +// {0} and {1} are the only replacement types accepted and only these are accepted. +// eg. in locale 'nl' one: '{0}-{1} day left' other: '{0}-{1} days left' +func (t *translator) AddRange(key interface{}, text string, rule locales.PluralRule, override bool) error { + + var verified bool + + // verify plural rule exists for locale + for _, pr := range t.PluralsRange() { + if pr == rule { + verified = true + break + } + } + + if !verified { + return &ErrRangeTranslation{text: fmt.Sprintf("error: range plural rule '%s' does not exist for locale '%s' key: '%v' text: '%s'", rule, t.Locale(), key, text)} + } + + tarr, ok := t.rangeTanslations[key] + if ok { + // verify not adding a conflicting record + if len(tarr) > 0 && tarr[rule] != nil && !override { + return &ErrConflictingTranslation{locale: t.Locale(), key: key, rule: rule, text: text} + } + + } else { + tarr = make([]*transText, 7) + t.rangeTanslations[key] = tarr + } + + trans := &transText{ + text: text, + indexes: make([]int, 4), + } + + tarr[rule] = trans + + idx := strings.Index(text, paramZero) + if idx == -1 { + tarr[rule] = nil + return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, are you sure you're adding a Range Translation? locale: '%s' key: '%v' text: '%s'", paramZero, t.Locale(), key, text)} + } + + trans.indexes[0] = idx + trans.indexes[1] = idx + len(paramZero) + + idx = strings.Index(text, paramOne) + if idx == -1 { + tarr[rule] = nil + return &ErrRangeTranslation{text: fmt.Sprintf("error: parameter '%s' not found, a Range Translation requires two parameters. locale: '%s' key: '%v' text: '%s'", paramOne, t.Locale(), key, text)} + } + + trans.indexes[2] = idx + trans.indexes[3] = idx + len(paramOne) + + return nil +} + +// T creates the translation for the locale given the 'key' and params passed in +func (t *translator) T(key interface{}, params ...string) (string, error) { + + trans, ok := t.translations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + b := make([]byte, 0, 64) + + var start, end, count int + + for i := 0; i < len(trans.indexes); i++ { + end = trans.indexes[i] + b = append(b, trans.text[start:end]...) + b = append(b, params[count]...) + i++ + start = trans.indexes[i] + count++ + } + + b = append(b, trans.text[start:]...) + + return string(b), nil +} + +// C creates the cardinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in +func (t *translator) C(key interface{}, num float64, digits uint64, param string) (string, error) { + + tarr, ok := t.cardinalTanslations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + rule := t.CardinalPluralRule(num, digits) + + trans := tarr[rule] + + b := make([]byte, 0, 64) + b = append(b, trans.text[:trans.indexes[0]]...) + b = append(b, param...) + b = append(b, trans.text[trans.indexes[1]:]...) + + return string(b), nil +} + +// O creates the ordinal translation for the locale given the 'key', 'num' and 'digit' arguments and param passed in +func (t *translator) O(key interface{}, num float64, digits uint64, param string) (string, error) { + + tarr, ok := t.ordinalTanslations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + rule := t.OrdinalPluralRule(num, digits) + + trans := tarr[rule] + + b := make([]byte, 0, 64) + b = append(b, trans.text[:trans.indexes[0]]...) + b = append(b, param...) + b = append(b, trans.text[trans.indexes[1]:]...) + + return string(b), nil +} + +// R creates the range translation for the locale given the 'key', 'num1', 'digit1', 'num2' and 'digit2' arguments +// and 'param1' and 'param2' passed in +func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float64, digits2 uint64, param1, param2 string) (string, error) { + + tarr, ok := t.rangeTanslations[key] + if !ok { + return unknownTranslation, ErrUnknowTranslation + } + + rule := t.RangePluralRule(num1, digits1, num2, digits2) + + trans := tarr[rule] + + b := make([]byte, 0, 64) + b = append(b, trans.text[:trans.indexes[0]]...) + b = append(b, param1...) + b = append(b, trans.text[trans.indexes[1]:trans.indexes[2]]...) + b = append(b, param2...) + b = append(b, trans.text[trans.indexes[3]:]...) + + return string(b), nil +} + +// VerifyTranslations checks to ensures that no plural rules have been +// missed within the translations. +func (t *translator) VerifyTranslations() error { + + for k, v := range t.cardinalTanslations { + + for _, rule := range t.PluralsCardinal() { + + if v[rule] == nil { + return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "plural", rule: rule, key: k} + } + } + } + + for k, v := range t.ordinalTanslations { + + for _, rule := range t.PluralsOrdinal() { + + if v[rule] == nil { + return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "ordinal", rule: rule, key: k} + } + } + } + + for k, v := range t.rangeTanslations { + + for _, rule := range t.PluralsRange() { + + if v[rule] == nil { + return &ErrMissingPluralTranslation{locale: t.Locale(), translationType: "range", rule: rule, key: k} + } + } + } + + return nil +} diff --git a/vendor/github.com/go-playground/universal-translator/universal_translator.go b/vendor/github.com/go-playground/universal-translator/universal_translator.go new file mode 100644 index 0000000..dbf707f --- /dev/null +++ b/vendor/github.com/go-playground/universal-translator/universal_translator.go @@ -0,0 +1,113 @@ +package ut + +import ( + "strings" + + "github.com/go-playground/locales" +) + +// UniversalTranslator holds all locale & translation data +type UniversalTranslator struct { + translators map[string]Translator + fallback Translator +} + +// New returns a new UniversalTranslator instance set with +// the fallback locale and locales it should support +func New(fallback locales.Translator, supportedLocales ...locales.Translator) *UniversalTranslator { + + t := &UniversalTranslator{ + translators: make(map[string]Translator), + } + + for _, v := range supportedLocales { + + trans := newTranslator(v) + t.translators[strings.ToLower(trans.Locale())] = trans + + if fallback.Locale() == v.Locale() { + t.fallback = trans + } + } + + if t.fallback == nil && fallback != nil { + t.fallback = newTranslator(fallback) + } + + return t +} + +// FindTranslator trys to find a Translator based on an array of locales +// and returns the first one it can find, otherwise returns the +// fallback translator. +func (t *UniversalTranslator) FindTranslator(locales ...string) (trans Translator, found bool) { + + for _, locale := range locales { + + if trans, found = t.translators[strings.ToLower(locale)]; found { + return + } + } + + return t.fallback, false +} + +// GetTranslator returns the specified translator for the given locale, +// or fallback if not found +func (t *UniversalTranslator) GetTranslator(locale string) (trans Translator, found bool) { + + if trans, found = t.translators[strings.ToLower(locale)]; found { + return + } + + return t.fallback, false +} + +// GetFallback returns the fallback locale +func (t *UniversalTranslator) GetFallback() Translator { + return t.fallback +} + +// AddTranslator adds the supplied translator, if it already exists the override param +// will be checked and if false an error will be returned, otherwise the translator will be +// overridden; if the fallback matches the supplied translator it will be overridden as well +// NOTE: this is normally only used when translator is embedded within a library +func (t *UniversalTranslator) AddTranslator(translator locales.Translator, override bool) error { + + lc := strings.ToLower(translator.Locale()) + _, ok := t.translators[lc] + if ok && !override { + return &ErrExistingTranslator{locale: translator.Locale()} + } + + trans := newTranslator(translator) + + if t.fallback.Locale() == translator.Locale() { + + // because it's optional to have a fallback, I don't impose that limitation + // don't know why you wouldn't but... + if !override { + return &ErrExistingTranslator{locale: translator.Locale()} + } + + t.fallback = trans + } + + t.translators[lc] = trans + + return nil +} + +// VerifyTranslations runs through all locales and identifies any issues +// eg. missing plural rules for a locale +func (t *UniversalTranslator) VerifyTranslations() (err error) { + + for _, trans := range t.translators { + err = trans.VerifyTranslations() + if err != nil { + return + } + } + + return +} diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md new file mode 100644 index 0000000..7ec5ac7 --- /dev/null +++ b/vendor/github.com/google/uuid/CHANGELOG.md @@ -0,0 +1,41 @@ +# Changelog + +## [1.6.0](https://github.com/google/uuid/compare/v1.5.0...v1.6.0) (2024-01-16) + + +### Features + +* add Max UUID constant ([#149](https://github.com/google/uuid/issues/149)) ([c58770e](https://github.com/google/uuid/commit/c58770eb495f55fe2ced6284f93c5158a62e53e3)) + + +### Bug Fixes + +* fix typo in version 7 uuid documentation ([#153](https://github.com/google/uuid/issues/153)) ([016b199](https://github.com/google/uuid/commit/016b199544692f745ffc8867b914129ecb47ef06)) +* Monotonicity in UUIDv7 ([#150](https://github.com/google/uuid/issues/150)) ([a2b2b32](https://github.com/google/uuid/commit/a2b2b32373ff0b1a312b7fdf6d38a977099698a6)) + +## [1.5.0](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) (2023-12-12) + + +### Features + +* Validate UUID without creating new UUID ([#141](https://github.com/google/uuid/issues/141)) ([9ee7366](https://github.com/google/uuid/commit/9ee7366e66c9ad96bab89139418a713dc584ae29)) + +## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) + + +### Features + +* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) + +### Fixes + +* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) + +## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) + + +### Bug Fixes + +* Use .EqualFold() to parse urn prefixed UUIDs ([#118](https://github.com/google/uuid/issues/118)) ([574e687](https://github.com/google/uuid/commit/574e6874943741fb99d41764c705173ada5293f0)) + +## Changelog diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md new file mode 100644 index 0000000..a502fdc --- /dev/null +++ b/vendor/github.com/google/uuid/CONTRIBUTING.md @@ -0,0 +1,26 @@ +# How to contribute + +We definitely welcome patches and contribution to this project! + +### Tips + +Commits must be formatted according to the [Conventional Commits Specification](https://www.conventionalcommits.org). + +Always try to include a test case! If it is not possible or not necessary, +please explain why in the pull request description. + +### Releasing + +Commits that would precipitate a SemVer change, as described in the Conventional +Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) +to create a release candidate pull request. Once submitted, `release-please` +will create a release. + +For tips on how to work with `release-please`, see its documentation. + +### Legal requirements + +In order to protect both you and ourselves, you will need to sign the +[Contributor License Agreement](https://cla.developers.google.com/clas). + +You may have already signed it for other Google projects. diff --git a/vendor/github.com/google/uuid/CONTRIBUTORS b/vendor/github.com/google/uuid/CONTRIBUTORS new file mode 100644 index 0000000..b4bb97f --- /dev/null +++ b/vendor/github.com/google/uuid/CONTRIBUTORS @@ -0,0 +1,9 @@ +Paul Borman +bmatsuo +shawnps +theory +jboverfelt +dsymonds +cd1 +wallclockbuilder +dansouza diff --git a/vendor/github.com/google/uuid/LICENSE b/vendor/github.com/google/uuid/LICENSE new file mode 100644 index 0000000..5dc6826 --- /dev/null +++ b/vendor/github.com/google/uuid/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2009,2014 Google Inc. 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. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/google/uuid/README.md b/vendor/github.com/google/uuid/README.md new file mode 100644 index 0000000..3e9a618 --- /dev/null +++ b/vendor/github.com/google/uuid/README.md @@ -0,0 +1,21 @@ +# uuid +The uuid package generates and inspects UUIDs based on +[RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) +and DCE 1.1: Authentication and Security Services. + +This package is based on the github.com/pborman/uuid package (previously named +code.google.com/p/go-uuid). It differs from these earlier packages in that +a UUID is a 16 byte array rather than a byte slice. One loss due to this +change is the ability to represent an invalid UUID (vs a NIL UUID). + +###### Install +```sh +go get github.com/google/uuid +``` + +###### Documentation +[![Go Reference](https://pkg.go.dev/badge/github.com/google/uuid.svg)](https://pkg.go.dev/github.com/google/uuid) + +Full `go doc` style documentation for the package can be viewed online without +installing this package by using the GoDoc site here: +http://pkg.go.dev/github.com/google/uuid diff --git a/vendor/github.com/google/uuid/dce.go b/vendor/github.com/google/uuid/dce.go new file mode 100644 index 0000000..fa820b9 --- /dev/null +++ b/vendor/github.com/google/uuid/dce.go @@ -0,0 +1,80 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" + "fmt" + "os" +) + +// A Domain represents a Version 2 domain +type Domain byte + +// Domain constants for DCE Security (Version 2) UUIDs. +const ( + Person = Domain(0) + Group = Domain(1) + Org = Domain(2) +) + +// NewDCESecurity returns a DCE Security (Version 2) UUID. +// +// The domain should be one of Person, Group or Org. +// On a POSIX system the id should be the users UID for the Person +// domain and the users GID for the Group. The meaning of id for +// the domain Org or on non-POSIX systems is site defined. +// +// For a given domain/id pair the same token may be returned for up to +// 7 minutes and 10 seconds. +func NewDCESecurity(domain Domain, id uint32) (UUID, error) { + uuid, err := NewUUID() + if err == nil { + uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 + uuid[9] = byte(domain) + binary.BigEndian.PutUint32(uuid[0:], id) + } + return uuid, err +} + +// NewDCEPerson returns a DCE Security (Version 2) UUID in the person +// domain with the id returned by os.Getuid. +// +// NewDCESecurity(Person, uint32(os.Getuid())) +func NewDCEPerson() (UUID, error) { + return NewDCESecurity(Person, uint32(os.Getuid())) +} + +// NewDCEGroup returns a DCE Security (Version 2) UUID in the group +// domain with the id returned by os.Getgid. +// +// NewDCESecurity(Group, uint32(os.Getgid())) +func NewDCEGroup() (UUID, error) { + return NewDCESecurity(Group, uint32(os.Getgid())) +} + +// Domain returns the domain for a Version 2 UUID. Domains are only defined +// for Version 2 UUIDs. +func (uuid UUID) Domain() Domain { + return Domain(uuid[9]) +} + +// ID returns the id for a Version 2 UUID. IDs are only defined for Version 2 +// UUIDs. +func (uuid UUID) ID() uint32 { + return binary.BigEndian.Uint32(uuid[0:4]) +} + +func (d Domain) String() string { + switch d { + case Person: + return "Person" + case Group: + return "Group" + case Org: + return "Org" + } + return fmt.Sprintf("Domain%d", int(d)) +} diff --git a/vendor/github.com/google/uuid/doc.go b/vendor/github.com/google/uuid/doc.go new file mode 100644 index 0000000..5b8a4b9 --- /dev/null +++ b/vendor/github.com/google/uuid/doc.go @@ -0,0 +1,12 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package uuid generates and inspects UUIDs. +// +// UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security +// Services. +// +// A UUID is a 16 byte (128 bit) array. UUIDs may be used as keys to +// maps or compared directly. +package uuid diff --git a/vendor/github.com/google/uuid/hash.go b/vendor/github.com/google/uuid/hash.go new file mode 100644 index 0000000..dc60082 --- /dev/null +++ b/vendor/github.com/google/uuid/hash.go @@ -0,0 +1,59 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "crypto/md5" + "crypto/sha1" + "hash" +) + +// Well known namespace IDs and UUIDs +var ( + NameSpaceDNS = Must(Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")) + NameSpaceURL = Must(Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8")) + NameSpaceOID = Must(Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8")) + NameSpaceX500 = Must(Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8")) + Nil UUID // empty UUID, all zeros + + // The Max UUID is special form of UUID that is specified to have all 128 bits set to 1. + Max = UUID{ + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + } +) + +// NewHash returns a new UUID derived from the hash of space concatenated with +// data generated by h. The hash should be at least 16 byte in length. The +// first 16 bytes of the hash are used to form the UUID. The version of the +// UUID will be the lower 4 bits of version. NewHash is used to implement +// NewMD5 and NewSHA1. +func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { + h.Reset() + h.Write(space[:]) //nolint:errcheck + h.Write(data) //nolint:errcheck + s := h.Sum(nil) + var uuid UUID + copy(uuid[:], s) + uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) + uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant + return uuid +} + +// NewMD5 returns a new MD5 (Version 3) UUID based on the +// supplied name space and data. It is the same as calling: +// +// NewHash(md5.New(), space, data, 3) +func NewMD5(space UUID, data []byte) UUID { + return NewHash(md5.New(), space, data, 3) +} + +// NewSHA1 returns a new SHA1 (Version 5) UUID based on the +// supplied name space and data. It is the same as calling: +// +// NewHash(sha1.New(), space, data, 5) +func NewSHA1(space UUID, data []byte) UUID { + return NewHash(sha1.New(), space, data, 5) +} diff --git a/vendor/github.com/google/uuid/marshal.go b/vendor/github.com/google/uuid/marshal.go new file mode 100644 index 0000000..14bd340 --- /dev/null +++ b/vendor/github.com/google/uuid/marshal.go @@ -0,0 +1,38 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "fmt" + +// MarshalText implements encoding.TextMarshaler. +func (uuid UUID) MarshalText() ([]byte, error) { + var js [36]byte + encodeHex(js[:], uuid) + return js[:], nil +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (uuid *UUID) UnmarshalText(data []byte) error { + id, err := ParseBytes(data) + if err != nil { + return err + } + *uuid = id + return nil +} + +// MarshalBinary implements encoding.BinaryMarshaler. +func (uuid UUID) MarshalBinary() ([]byte, error) { + return uuid[:], nil +} + +// UnmarshalBinary implements encoding.BinaryUnmarshaler. +func (uuid *UUID) UnmarshalBinary(data []byte) error { + if len(data) != 16 { + return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) + } + copy(uuid[:], data) + return nil +} diff --git a/vendor/github.com/google/uuid/node.go b/vendor/github.com/google/uuid/node.go new file mode 100644 index 0000000..d651a2b --- /dev/null +++ b/vendor/github.com/google/uuid/node.go @@ -0,0 +1,90 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "sync" +) + +var ( + nodeMu sync.Mutex + ifname string // name of interface being used + nodeID [6]byte // hardware for version 1 UUIDs + zeroID [6]byte // nodeID with only 0's +) + +// NodeInterface returns the name of the interface from which the NodeID was +// derived. The interface "user" is returned if the NodeID was set by +// SetNodeID. +func NodeInterface() string { + defer nodeMu.Unlock() + nodeMu.Lock() + return ifname +} + +// SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. +// If name is "" then the first usable interface found will be used or a random +// Node ID will be generated. If a named interface cannot be found then false +// is returned. +// +// SetNodeInterface never fails when name is "". +func SetNodeInterface(name string) bool { + defer nodeMu.Unlock() + nodeMu.Lock() + return setNodeInterface(name) +} + +func setNodeInterface(name string) bool { + iname, addr := getHardwareInterface(name) // null implementation for js + if iname != "" && addr != nil { + ifname = iname + copy(nodeID[:], addr) + return true + } + + // We found no interfaces with a valid hardware address. If name + // does not specify a specific interface generate a random Node ID + // (section 4.1.6) + if name == "" { + ifname = "random" + randomBits(nodeID[:]) + return true + } + return false +} + +// NodeID returns a slice of a copy of the current Node ID, setting the Node ID +// if not already set. +func NodeID() []byte { + defer nodeMu.Unlock() + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + nid := nodeID + return nid[:] +} + +// SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes +// of id are used. If id is less than 6 bytes then false is returned and the +// Node ID is not set. +func SetNodeID(id []byte) bool { + if len(id) < 6 { + return false + } + defer nodeMu.Unlock() + nodeMu.Lock() + copy(nodeID[:], id) + ifname = "user" + return true +} + +// NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is +// not valid. The NodeID is only well defined for version 1 and 2 UUIDs. +func (uuid UUID) NodeID() []byte { + var node [6]byte + copy(node[:], uuid[10:]) + return node[:] +} diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go new file mode 100644 index 0000000..b2a0bc8 --- /dev/null +++ b/vendor/github.com/google/uuid/node_js.go @@ -0,0 +1,12 @@ +// Copyright 2017 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build js + +package uuid + +// getHardwareInterface returns nil values for the JS version of the code. +// This removes the "net" dependency, because it is not used in the browser. +// Using the "net" library inflates the size of the transpiled JS code by 673k bytes. +func getHardwareInterface(name string) (string, []byte) { return "", nil } diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go new file mode 100644 index 0000000..0cbbcdd --- /dev/null +++ b/vendor/github.com/google/uuid/node_net.go @@ -0,0 +1,33 @@ +// Copyright 2017 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !js + +package uuid + +import "net" + +var interfaces []net.Interface // cached list of interfaces + +// getHardwareInterface returns the name and hardware address of interface name. +// If name is "" then the name and hardware address of one of the system's +// interfaces is returned. If no interfaces are found (name does not exist or +// there are no interfaces) then "", nil is returned. +// +// Only addresses of at least 6 bytes are returned. +func getHardwareInterface(name string) (string, []byte) { + if interfaces == nil { + var err error + interfaces, err = net.Interfaces() + if err != nil { + return "", nil + } + } + for _, ifs := range interfaces { + if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { + return ifs.Name, ifs.HardwareAddr + } + } + return "", nil +} diff --git a/vendor/github.com/google/uuid/null.go b/vendor/github.com/google/uuid/null.go new file mode 100644 index 0000000..d7fcbf2 --- /dev/null +++ b/vendor/github.com/google/uuid/null.go @@ -0,0 +1,118 @@ +// Copyright 2021 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "bytes" + "database/sql/driver" + "encoding/json" + "fmt" +) + +var jsonNull = []byte("null") + +// NullUUID represents a UUID that may be null. +// NullUUID implements the SQL driver.Scanner interface so +// it can be used as a scan destination: +// +// var u uuid.NullUUID +// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&u) +// ... +// if u.Valid { +// // use u.UUID +// } else { +// // NULL value +// } +// +type NullUUID struct { + UUID UUID + Valid bool // Valid is true if UUID is not NULL +} + +// Scan implements the SQL driver.Scanner interface. +func (nu *NullUUID) Scan(value interface{}) error { + if value == nil { + nu.UUID, nu.Valid = Nil, false + return nil + } + + err := nu.UUID.Scan(value) + if err != nil { + nu.Valid = false + return err + } + + nu.Valid = true + return nil +} + +// Value implements the driver Valuer interface. +func (nu NullUUID) Value() (driver.Value, error) { + if !nu.Valid { + return nil, nil + } + // Delegate to UUID Value function + return nu.UUID.Value() +} + +// MarshalBinary implements encoding.BinaryMarshaler. +func (nu NullUUID) MarshalBinary() ([]byte, error) { + if nu.Valid { + return nu.UUID[:], nil + } + + return []byte(nil), nil +} + +// UnmarshalBinary implements encoding.BinaryUnmarshaler. +func (nu *NullUUID) UnmarshalBinary(data []byte) error { + if len(data) != 16 { + return fmt.Errorf("invalid UUID (got %d bytes)", len(data)) + } + copy(nu.UUID[:], data) + nu.Valid = true + return nil +} + +// MarshalText implements encoding.TextMarshaler. +func (nu NullUUID) MarshalText() ([]byte, error) { + if nu.Valid { + return nu.UUID.MarshalText() + } + + return jsonNull, nil +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (nu *NullUUID) UnmarshalText(data []byte) error { + id, err := ParseBytes(data) + if err != nil { + nu.Valid = false + return err + } + nu.UUID = id + nu.Valid = true + return nil +} + +// MarshalJSON implements json.Marshaler. +func (nu NullUUID) MarshalJSON() ([]byte, error) { + if nu.Valid { + return json.Marshal(nu.UUID) + } + + return jsonNull, nil +} + +// UnmarshalJSON implements json.Unmarshaler. +func (nu *NullUUID) UnmarshalJSON(data []byte) error { + if bytes.Equal(data, jsonNull) { + *nu = NullUUID{} + return nil // valid null UUID + } + err := json.Unmarshal(data, &nu.UUID) + nu.Valid = err == nil + return err +} diff --git a/vendor/github.com/google/uuid/sql.go b/vendor/github.com/google/uuid/sql.go new file mode 100644 index 0000000..2e02ec0 --- /dev/null +++ b/vendor/github.com/google/uuid/sql.go @@ -0,0 +1,59 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "database/sql/driver" + "fmt" +) + +// Scan implements sql.Scanner so UUIDs can be read from databases transparently. +// Currently, database types that map to string and []byte are supported. Please +// consult database-specific driver documentation for matching types. +func (uuid *UUID) Scan(src interface{}) error { + switch src := src.(type) { + case nil: + return nil + + case string: + // if an empty UUID comes from a table, we return a null UUID + if src == "" { + return nil + } + + // see Parse for required string format + u, err := Parse(src) + if err != nil { + return fmt.Errorf("Scan: %v", err) + } + + *uuid = u + + case []byte: + // if an empty UUID comes from a table, we return a null UUID + if len(src) == 0 { + return nil + } + + // assumes a simple slice of bytes if 16 bytes + // otherwise attempts to parse + if len(src) != 16 { + return uuid.Scan(string(src)) + } + copy((*uuid)[:], src) + + default: + return fmt.Errorf("Scan: unable to scan type %T into UUID", src) + } + + return nil +} + +// Value implements sql.Valuer so that UUIDs can be written to databases +// transparently. Currently, UUIDs map to strings. Please consult +// database-specific driver documentation for matching types. +func (uuid UUID) Value() (driver.Value, error) { + return uuid.String(), nil +} diff --git a/vendor/github.com/google/uuid/time.go b/vendor/github.com/google/uuid/time.go new file mode 100644 index 0000000..c351129 --- /dev/null +++ b/vendor/github.com/google/uuid/time.go @@ -0,0 +1,134 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" + "sync" + "time" +) + +// A Time represents a time as the number of 100's of nanoseconds since 15 Oct +// 1582. +type Time int64 + +const ( + lillian = 2299160 // Julian day of 15 Oct 1582 + unix = 2440587 // Julian day of 1 Jan 1970 + epoch = unix - lillian // Days between epochs + g1582 = epoch * 86400 // seconds between epochs + g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs +) + +var ( + timeMu sync.Mutex + lasttime uint64 // last time we returned + clockSeq uint16 // clock sequence for this run + + timeNow = time.Now // for testing +) + +// UnixTime converts t the number of seconds and nanoseconds using the Unix +// epoch of 1 Jan 1970. +func (t Time) UnixTime() (sec, nsec int64) { + sec = int64(t - g1582ns100) + nsec = (sec % 10000000) * 100 + sec /= 10000000 + return sec, nsec +} + +// GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and +// clock sequence as well as adjusting the clock sequence as needed. An error +// is returned if the current time cannot be determined. +func GetTime() (Time, uint16, error) { + defer timeMu.Unlock() + timeMu.Lock() + return getTime() +} + +func getTime() (Time, uint16, error) { + t := timeNow() + + // If we don't have a clock sequence already, set one. + if clockSeq == 0 { + setClockSequence(-1) + } + now := uint64(t.UnixNano()/100) + g1582ns100 + + // If time has gone backwards with this clock sequence then we + // increment the clock sequence + if now <= lasttime { + clockSeq = ((clockSeq + 1) & 0x3fff) | 0x8000 + } + lasttime = now + return Time(now), clockSeq, nil +} + +// ClockSequence returns the current clock sequence, generating one if not +// already set. The clock sequence is only used for Version 1 UUIDs. +// +// The uuid package does not use global static storage for the clock sequence or +// the last time a UUID was generated. Unless SetClockSequence is used, a new +// random clock sequence is generated the first time a clock sequence is +// requested by ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) +func ClockSequence() int { + defer timeMu.Unlock() + timeMu.Lock() + return clockSequence() +} + +func clockSequence() int { + if clockSeq == 0 { + setClockSequence(-1) + } + return int(clockSeq & 0x3fff) +} + +// SetClockSequence sets the clock sequence to the lower 14 bits of seq. Setting to +// -1 causes a new sequence to be generated. +func SetClockSequence(seq int) { + defer timeMu.Unlock() + timeMu.Lock() + setClockSequence(seq) +} + +func setClockSequence(seq int) { + if seq == -1 { + var b [2]byte + randomBits(b[:]) // clock sequence + seq = int(b[0])<<8 | int(b[1]) + } + oldSeq := clockSeq + clockSeq = uint16(seq&0x3fff) | 0x8000 // Set our variant + if oldSeq != clockSeq { + lasttime = 0 + } +} + +// Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in +// uuid. The time is only defined for version 1, 2, 6 and 7 UUIDs. +func (uuid UUID) Time() Time { + var t Time + switch uuid.Version() { + case 6: + time := binary.BigEndian.Uint64(uuid[:8]) // Ignore uuid[6] version b0110 + t = Time(time) + case 7: + time := binary.BigEndian.Uint64(uuid[:8]) + t = Time((time>>16)*10000 + g1582ns100) + default: // forward compatible + time := int64(binary.BigEndian.Uint32(uuid[0:4])) + time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 + time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 + t = Time(time) + } + return t +} + +// ClockSequence returns the clock sequence encoded in uuid. +// The clock sequence is only well defined for version 1 and 2 UUIDs. +func (uuid UUID) ClockSequence() int { + return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff +} diff --git a/vendor/github.com/google/uuid/util.go b/vendor/github.com/google/uuid/util.go new file mode 100644 index 0000000..5ea6c73 --- /dev/null +++ b/vendor/github.com/google/uuid/util.go @@ -0,0 +1,43 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "io" +) + +// randomBits completely fills slice b with random data. +func randomBits(b []byte) { + if _, err := io.ReadFull(rander, b); err != nil { + panic(err.Error()) // rand should never fail + } +} + +// xvalues returns the value of a byte as a hexadecimal digit or 255. +var xvalues = [256]byte{ + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, + 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, +} + +// xtob converts hex characters x1 and x2 into a byte. +func xtob(x1, x2 byte) (byte, bool) { + b1 := xvalues[x1] + b2 := xvalues[x2] + return (b1 << 4) | b2, b1 != 255 && b2 != 255 +} diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go new file mode 100644 index 0000000..5232b48 --- /dev/null +++ b/vendor/github.com/google/uuid/uuid.go @@ -0,0 +1,365 @@ +// Copyright 2018 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + "io" + "strings" + "sync" +) + +// A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC +// 4122. +type UUID [16]byte + +// A Version represents a UUID's version. +type Version byte + +// A Variant represents a UUID's variant. +type Variant byte + +// Constants returned by Variant. +const ( + Invalid = Variant(iota) // Invalid UUID + RFC4122 // The variant specified in RFC4122 + Reserved // Reserved, NCS backward compatibility. + Microsoft // Reserved, Microsoft Corporation backward compatibility. + Future // Reserved for future definition. +) + +const randPoolSize = 16 * 16 + +var ( + rander = rand.Reader // random function + poolEnabled = false + poolMu sync.Mutex + poolPos = randPoolSize // protected with poolMu + pool [randPoolSize]byte // protected with poolMu +) + +type invalidLengthError struct{ len int } + +func (err invalidLengthError) Error() string { + return fmt.Sprintf("invalid UUID length: %d", err.len) +} + +// IsInvalidLengthError is matcher function for custom error invalidLengthError +func IsInvalidLengthError(err error) bool { + _, ok := err.(invalidLengthError) + return ok +} + +// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both +// the standard UUID forms defined in RFC 4122 +// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, +// Parse accepts non-standard strings such as the raw hex encoding +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, +// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are +// examined in the latter case. Parse should not be used to validate strings as +// it parses non-standard encodings as indicated above. +func Parse(s string) (UUID, error) { + var uuid UUID + switch len(s) { + // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 36: + + // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 36 + 9: + if !strings.EqualFold(s[:9], "urn:uuid:") { + return uuid, fmt.Errorf("invalid urn prefix: %q", s[:9]) + } + s = s[9:] + + // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + case 36 + 2: + s = s[1:] + + // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + case 32: + var ok bool + for i := range uuid { + uuid[i], ok = xtob(s[i*2], s[i*2+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + } + return uuid, nil + default: + return uuid, invalidLengthError{len(s)} + } + // s is now at least 36 bytes long + // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return uuid, errors.New("invalid UUID format") + } + for i, x := range [16]int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34, + } { + v, ok := xtob(s[x], s[x+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + uuid[i] = v + } + return uuid, nil +} + +// ParseBytes is like Parse, except it parses a byte slice instead of a string. +func ParseBytes(b []byte) (UUID, error) { + var uuid UUID + switch len(b) { + case 36: // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + case 36 + 9: // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + if !bytes.EqualFold(b[:9], []byte("urn:uuid:")) { + return uuid, fmt.Errorf("invalid urn prefix: %q", b[:9]) + } + b = b[9:] + case 36 + 2: // {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} + b = b[1:] + case 32: // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + var ok bool + for i := 0; i < 32; i += 2 { + uuid[i/2], ok = xtob(b[i], b[i+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + } + return uuid, nil + default: + return uuid, invalidLengthError{len(b)} + } + // s is now at least 36 bytes long + // it must be of the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + if b[8] != '-' || b[13] != '-' || b[18] != '-' || b[23] != '-' { + return uuid, errors.New("invalid UUID format") + } + for i, x := range [16]int{ + 0, 2, 4, 6, + 9, 11, + 14, 16, + 19, 21, + 24, 26, 28, 30, 32, 34, + } { + v, ok := xtob(b[x], b[x+1]) + if !ok { + return uuid, errors.New("invalid UUID format") + } + uuid[i] = v + } + return uuid, nil +} + +// MustParse is like Parse but panics if the string cannot be parsed. +// It simplifies safe initialization of global variables holding compiled UUIDs. +func MustParse(s string) UUID { + uuid, err := Parse(s) + if err != nil { + panic(`uuid: Parse(` + s + `): ` + err.Error()) + } + return uuid +} + +// FromBytes creates a new UUID from a byte slice. Returns an error if the slice +// does not have a length of 16. The bytes are copied from the slice. +func FromBytes(b []byte) (uuid UUID, err error) { + err = uuid.UnmarshalBinary(b) + return uuid, err +} + +// Must returns uuid if err is nil and panics otherwise. +func Must(uuid UUID, err error) UUID { + if err != nil { + panic(err) + } + return uuid +} + +// Validate returns an error if s is not a properly formatted UUID in one of the following formats: +// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +// {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} +// It returns an error if the format is invalid, otherwise nil. +func Validate(s string) error { + switch len(s) { + // Standard UUID format + case 36: + + // UUID with "urn:uuid:" prefix + case 36 + 9: + if !strings.EqualFold(s[:9], "urn:uuid:") { + return fmt.Errorf("invalid urn prefix: %q", s[:9]) + } + s = s[9:] + + // UUID enclosed in braces + case 36 + 2: + if s[0] != '{' || s[len(s)-1] != '}' { + return fmt.Errorf("invalid bracketed UUID format") + } + s = s[1 : len(s)-1] + + // UUID without hyphens + case 32: + for i := 0; i < len(s); i += 2 { + _, ok := xtob(s[i], s[i+1]) + if !ok { + return errors.New("invalid UUID format") + } + } + + default: + return invalidLengthError{len(s)} + } + + // Check for standard UUID format + if len(s) == 36 { + if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { + return errors.New("invalid UUID format") + } + for _, x := range []int{0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34} { + if _, ok := xtob(s[x], s[x+1]); !ok { + return errors.New("invalid UUID format") + } + } + } + + return nil +} + +// String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx +// , or "" if uuid is invalid. +func (uuid UUID) String() string { + var buf [36]byte + encodeHex(buf[:], uuid) + return string(buf[:]) +} + +// URN returns the RFC 2141 URN form of uuid, +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. +func (uuid UUID) URN() string { + var buf [36 + 9]byte + copy(buf[:], "urn:uuid:") + encodeHex(buf[9:], uuid) + return string(buf[:]) +} + +func encodeHex(dst []byte, uuid UUID) { + hex.Encode(dst, uuid[:4]) + dst[8] = '-' + hex.Encode(dst[9:13], uuid[4:6]) + dst[13] = '-' + hex.Encode(dst[14:18], uuid[6:8]) + dst[18] = '-' + hex.Encode(dst[19:23], uuid[8:10]) + dst[23] = '-' + hex.Encode(dst[24:], uuid[10:]) +} + +// Variant returns the variant encoded in uuid. +func (uuid UUID) Variant() Variant { + switch { + case (uuid[8] & 0xc0) == 0x80: + return RFC4122 + case (uuid[8] & 0xe0) == 0xc0: + return Microsoft + case (uuid[8] & 0xe0) == 0xe0: + return Future + default: + return Reserved + } +} + +// Version returns the version of uuid. +func (uuid UUID) Version() Version { + return Version(uuid[6] >> 4) +} + +func (v Version) String() string { + if v > 15 { + return fmt.Sprintf("BAD_VERSION_%d", v) + } + return fmt.Sprintf("VERSION_%d", v) +} + +func (v Variant) String() string { + switch v { + case RFC4122: + return "RFC4122" + case Reserved: + return "Reserved" + case Microsoft: + return "Microsoft" + case Future: + return "Future" + case Invalid: + return "Invalid" + } + return fmt.Sprintf("BadVariant%d", int(v)) +} + +// SetRand sets the random number generator to r, which implements io.Reader. +// If r.Read returns an error when the package requests random data then +// a panic will be issued. +// +// Calling SetRand with nil sets the random number generator to the default +// generator. +func SetRand(r io.Reader) { + if r == nil { + rander = rand.Reader + return + } + rander = r +} + +// EnableRandPool enables internal randomness pool used for Random +// (Version 4) UUID generation. The pool contains random bytes read from +// the random number generator on demand in batches. Enabling the pool +// may improve the UUID generation throughput significantly. +// +// Since the pool is stored on the Go heap, this feature may be a bad fit +// for security sensitive applications. +// +// Both EnableRandPool and DisableRandPool are not thread-safe and should +// only be called when there is no possibility that New or any other +// UUID Version 4 generation function will be called concurrently. +func EnableRandPool() { + poolEnabled = true +} + +// DisableRandPool disables the randomness pool if it was previously +// enabled with EnableRandPool. +// +// Both EnableRandPool and DisableRandPool are not thread-safe and should +// only be called when there is no possibility that New or any other +// UUID Version 4 generation function will be called concurrently. +func DisableRandPool() { + poolEnabled = false + defer poolMu.Unlock() + poolMu.Lock() + poolPos = randPoolSize +} + +// UUIDs is a slice of UUID types. +type UUIDs []UUID + +// Strings returns a string slice containing the string form of each UUID in uuids. +func (uuids UUIDs) Strings() []string { + var uuidStrs = make([]string, len(uuids)) + for i, uuid := range uuids { + uuidStrs[i] = uuid.String() + } + return uuidStrs +} diff --git a/vendor/github.com/google/uuid/version1.go b/vendor/github.com/google/uuid/version1.go new file mode 100644 index 0000000..4631096 --- /dev/null +++ b/vendor/github.com/google/uuid/version1.go @@ -0,0 +1,44 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "encoding/binary" +) + +// NewUUID returns a Version 1 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewUUID returns nil. If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewUUID returns nil and an error. +// +// In most cases, New should be used. +func NewUUID() (UUID, error) { + var uuid UUID + now, seq, err := GetTime() + if err != nil { + return uuid, err + } + + timeLow := uint32(now & 0xffffffff) + timeMid := uint16((now >> 32) & 0xffff) + timeHi := uint16((now >> 48) & 0x0fff) + timeHi |= 0x1000 // Version 1 + + binary.BigEndian.PutUint32(uuid[0:], timeLow) + binary.BigEndian.PutUint16(uuid[4:], timeMid) + binary.BigEndian.PutUint16(uuid[6:], timeHi) + binary.BigEndian.PutUint16(uuid[8:], seq) + + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + copy(uuid[10:], nodeID[:]) + nodeMu.Unlock() + + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version4.go b/vendor/github.com/google/uuid/version4.go new file mode 100644 index 0000000..7697802 --- /dev/null +++ b/vendor/github.com/google/uuid/version4.go @@ -0,0 +1,76 @@ +// Copyright 2016 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "io" + +// New creates a new random UUID or panics. New is equivalent to +// the expression +// +// uuid.Must(uuid.NewRandom()) +func New() UUID { + return Must(NewRandom()) +} + +// NewString creates a new random UUID and returns it as a string or panics. +// NewString is equivalent to the expression +// +// uuid.New().String() +func NewString() string { + return Must(NewRandom()).String() +} + +// NewRandom returns a Random (Version 4) UUID. +// +// The strength of the UUIDs is based on the strength of the crypto/rand +// package. +// +// Uses the randomness pool if it was enabled with EnableRandPool. +// +// A note about uniqueness derived from the UUID Wikipedia entry: +// +// Randomly generated UUIDs have 122 random bits. One's annual risk of being +// hit by a meteorite is estimated to be one chance in 17 billion, that +// means the probability is about 0.00000000006 (6 × 10−11), +// equivalent to the odds of creating a few tens of trillions of UUIDs in a +// year and having one duplicate. +func NewRandom() (UUID, error) { + if !poolEnabled { + return NewRandomFromReader(rander) + } + return newRandomFromPool() +} + +// NewRandomFromReader returns a UUID based on bytes read from a given io.Reader. +func NewRandomFromReader(r io.Reader) (UUID, error) { + var uuid UUID + _, err := io.ReadFull(r, uuid[:]) + if err != nil { + return Nil, err + } + uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 + uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 + return uuid, nil +} + +func newRandomFromPool() (UUID, error) { + var uuid UUID + poolMu.Lock() + if poolPos == randPoolSize { + _, err := io.ReadFull(rander, pool[:]) + if err != nil { + poolMu.Unlock() + return Nil, err + } + poolPos = 0 + } + copy(uuid[:], pool[poolPos:(poolPos+16)]) + poolPos += 16 + poolMu.Unlock() + + uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 + uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version6.go b/vendor/github.com/google/uuid/version6.go new file mode 100644 index 0000000..339a959 --- /dev/null +++ b/vendor/github.com/google/uuid/version6.go @@ -0,0 +1,56 @@ +// Copyright 2023 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import "encoding/binary" + +// UUID version 6 is a field-compatible version of UUIDv1, reordered for improved DB locality. +// It is expected that UUIDv6 will primarily be used in contexts where there are existing v1 UUIDs. +// Systems that do not involve legacy UUIDv1 SHOULD consider using UUIDv7 instead. +// +// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#uuidv6 +// +// NewV6 returns a Version 6 UUID based on the current NodeID and clock +// sequence, and the current time. If the NodeID has not been set by SetNodeID +// or SetNodeInterface then it will be set automatically. If the NodeID cannot +// be set NewV6 set NodeID is random bits automatically . If clock sequence has not been set by +// SetClockSequence then it will be set automatically. If GetTime fails to +// return the current NewV6 returns Nil and an error. +func NewV6() (UUID, error) { + var uuid UUID + now, seq, err := GetTime() + if err != nil { + return uuid, err + } + + /* + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_high | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | time_mid | time_low_and_version | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |clk_seq_hi_res | clk_seq_low | node (0-1) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | node (2-5) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + + binary.BigEndian.PutUint64(uuid[0:], uint64(now)) + binary.BigEndian.PutUint16(uuid[8:], seq) + + uuid[6] = 0x60 | (uuid[6] & 0x0F) + uuid[8] = 0x80 | (uuid[8] & 0x3F) + + nodeMu.Lock() + if nodeID == zeroID { + setNodeInterface("") + } + copy(uuid[10:], nodeID[:]) + nodeMu.Unlock() + + return uuid, nil +} diff --git a/vendor/github.com/google/uuid/version7.go b/vendor/github.com/google/uuid/version7.go new file mode 100644 index 0000000..3167b64 --- /dev/null +++ b/vendor/github.com/google/uuid/version7.go @@ -0,0 +1,104 @@ +// Copyright 2023 Google Inc. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package uuid + +import ( + "io" +) + +// UUID version 7 features a time-ordered value field derived from the widely +// implemented and well known Unix Epoch timestamp source, +// the number of milliseconds seconds since midnight 1 Jan 1970 UTC, leap seconds excluded. +// As well as improved entropy characteristics over versions 1 or 6. +// +// see https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-03#name-uuid-version-7 +// +// Implementations SHOULD utilize UUID version 7 over UUID version 1 and 6 if possible. +// +// NewV7 returns a Version 7 UUID based on the current time(Unix Epoch). +// Uses the randomness pool if it was enabled with EnableRandPool. +// On error, NewV7 returns Nil and an error +func NewV7() (UUID, error) { + uuid, err := NewRandom() + if err != nil { + return uuid, err + } + makeV7(uuid[:]) + return uuid, nil +} + +// NewV7FromReader returns a Version 7 UUID based on the current time(Unix Epoch). +// it use NewRandomFromReader fill random bits. +// On error, NewV7FromReader returns Nil and an error. +func NewV7FromReader(r io.Reader) (UUID, error) { + uuid, err := NewRandomFromReader(r) + if err != nil { + return uuid, err + } + + makeV7(uuid[:]) + return uuid, nil +} + +// makeV7 fill 48 bits time (uuid[0] - uuid[5]), set version b0111 (uuid[6]) +// uuid[8] already has the right version number (Variant is 10) +// see function NewV7 and NewV7FromReader +func makeV7(uuid []byte) { + /* + 0 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | unix_ts_ms | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | unix_ts_ms | ver | rand_a (12 bit seq) | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + |var| rand_b | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + | rand_b | + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + _ = uuid[15] // bounds check + + t, s := getV7Time() + + uuid[0] = byte(t >> 40) + uuid[1] = byte(t >> 32) + uuid[2] = byte(t >> 24) + uuid[3] = byte(t >> 16) + uuid[4] = byte(t >> 8) + uuid[5] = byte(t) + + uuid[6] = 0x70 | (0x0F & byte(s>>8)) + uuid[7] = byte(s) +} + +// lastV7time is the last time we returned stored as: +// +// 52 bits of time in milliseconds since epoch +// 12 bits of (fractional nanoseconds) >> 8 +var lastV7time int64 + +const nanoPerMilli = 1000000 + +// getV7Time returns the time in milliseconds and nanoseconds / 256. +// The returned (milli << 12 + seq) is guarenteed to be greater than +// (milli << 12 + seq) returned by any previous call to getV7Time. +func getV7Time() (milli, seq int64) { + timeMu.Lock() + defer timeMu.Unlock() + + nano := timeNow().UnixNano() + milli = nano / nanoPerMilli + // Sequence number is between 0 and 3906 (nanoPerMilli>>8) + seq = (nano - milli*nanoPerMilli) >> 8 + now := milli<<12 + seq + if now <= lastV7time { + now = lastV7time + 1 + milli = now >> 12 + seq = now & 0xfff + } + lastV7time = now + return milli, seq +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/LICENSE b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/LICENSE new file mode 100644 index 0000000..3645162 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2015, Gengo, Inc. +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. + + * Neither the name of Gengo, Inc. nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel new file mode 100644 index 0000000..b8fbb2b --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/BUILD.bazel @@ -0,0 +1,35 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package(default_visibility = ["//visibility:public"]) + +go_library( + name = "httprule", + srcs = [ + "compile.go", + "parse.go", + "types.go", + ], + importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule", + deps = ["//utilities"], +) + +go_test( + name = "httprule_test", + size = "small", + srcs = [ + "compile_test.go", + "parse_test.go", + "types_test.go", + ], + embed = [":httprule"], + deps = [ + "//utilities", + "@org_golang_google_grpc//grpclog", + ], +) + +alias( + name = "go_default_library", + actual = ":httprule", + visibility = ["//:__subpackages__"], +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go new file mode 100644 index 0000000..3cd9372 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/compile.go @@ -0,0 +1,121 @@ +package httprule + +import ( + "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" +) + +const ( + opcodeVersion = 1 +) + +// Template is a compiled representation of path templates. +type Template struct { + // Version is the version number of the format. + Version int + // OpCodes is a sequence of operations. + OpCodes []int + // Pool is a constant pool + Pool []string + // Verb is a VERB part in the template. + Verb string + // Fields is a list of field paths bound in this template. + Fields []string + // Original template (example: /v1/a_bit_of_everything) + Template string +} + +// Compiler compiles utilities representation of path templates into marshallable operations. +// They can be unmarshalled by runtime.NewPattern. +type Compiler interface { + Compile() Template +} + +type op struct { + // code is the opcode of the operation + code utilities.OpCode + + // str is a string operand of the code. + // num is ignored if str is not empty. + str string + + // num is a numeric operand of the code. + num int +} + +func (w wildcard) compile() []op { + return []op{ + {code: utilities.OpPush}, + } +} + +func (w deepWildcard) compile() []op { + return []op{ + {code: utilities.OpPushM}, + } +} + +func (l literal) compile() []op { + return []op{ + { + code: utilities.OpLitPush, + str: string(l), + }, + } +} + +func (v variable) compile() []op { + var ops []op + for _, s := range v.segments { + ops = append(ops, s.compile()...) + } + ops = append(ops, op{ + code: utilities.OpConcatN, + num: len(v.segments), + }, op{ + code: utilities.OpCapture, + str: v.path, + }) + + return ops +} + +func (t template) Compile() Template { + var rawOps []op + for _, s := range t.segments { + rawOps = append(rawOps, s.compile()...) + } + + var ( + ops []int + pool []string + fields []string + ) + consts := make(map[string]int) + for _, op := range rawOps { + ops = append(ops, int(op.code)) + if op.str == "" { + ops = append(ops, op.num) + } else { + // eof segment literal represents the "/" path pattern + if op.str == eof { + op.str = "" + } + if _, ok := consts[op.str]; !ok { + consts[op.str] = len(pool) + pool = append(pool, op.str) + } + ops = append(ops, consts[op.str]) + } + if op.code == utilities.OpCapture { + fields = append(fields, op.str) + } + } + return Template{ + Version: opcodeVersion, + OpCodes: ops, + Pool: pool, + Verb: t.verb, + Fields: fields, + Template: t.template, + } +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go new file mode 100644 index 0000000..c056bd3 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/fuzz.go @@ -0,0 +1,11 @@ +//go:build gofuzz +// +build gofuzz + +package httprule + +func Fuzz(data []byte) int { + if _, err := Parse(string(data)); err != nil { + return 0 + } + return 0 +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go new file mode 100644 index 0000000..65ffcf5 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/parse.go @@ -0,0 +1,368 @@ +package httprule + +import ( + "errors" + "fmt" + "strings" +) + +// InvalidTemplateError indicates that the path template is not valid. +type InvalidTemplateError struct { + tmpl string + msg string +} + +func (e InvalidTemplateError) Error() string { + return fmt.Sprintf("%s: %s", e.msg, e.tmpl) +} + +// Parse parses the string representation of path template +func Parse(tmpl string) (Compiler, error) { + if !strings.HasPrefix(tmpl, "/") { + return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"} + } + tokens, verb := tokenize(tmpl[1:]) + + p := parser{tokens: tokens} + segs, err := p.topLevelSegments() + if err != nil { + return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()} + } + + return template{ + segments: segs, + verb: verb, + template: tmpl, + }, nil +} + +func tokenize(path string) (tokens []string, verb string) { + if path == "" { + return []string{eof}, "" + } + + const ( + init = iota + field + nested + ) + st := init + for path != "" { + var idx int + switch st { + case init: + idx = strings.IndexAny(path, "/{") + case field: + idx = strings.IndexAny(path, ".=}") + case nested: + idx = strings.IndexAny(path, "/}") + } + if idx < 0 { + tokens = append(tokens, path) + break + } + switch r := path[idx]; r { + case '/', '.': + case '{': + st = field + case '=': + st = nested + case '}': + st = init + } + if idx == 0 { + tokens = append(tokens, path[idx:idx+1]) + } else { + tokens = append(tokens, path[:idx], path[idx:idx+1]) + } + path = path[idx+1:] + } + + l := len(tokens) + // See + // https://github.com/grpc-ecosystem/grpc-gateway/pull/1947#issuecomment-774523693 ; + // although normal and backwards-compat logic here is to use the last index + // of a colon, if the final segment is a variable followed by a colon, the + // part following the colon must be a verb. Hence if the previous token is + // an end var marker, we switch the index we're looking for to Index instead + // of LastIndex, so that we correctly grab the remaining part of the path as + // the verb. + var penultimateTokenIsEndVar bool + switch l { + case 0, 1: + // Not enough to be variable so skip this logic and don't result in an + // invalid index + default: + penultimateTokenIsEndVar = tokens[l-2] == "}" + } + t := tokens[l-1] + var idx int + if penultimateTokenIsEndVar { + idx = strings.Index(t, ":") + } else { + idx = strings.LastIndex(t, ":") + } + if idx == 0 { + tokens, verb = tokens[:l-1], t[1:] + } else if idx > 0 { + tokens[l-1], verb = t[:idx], t[idx+1:] + } + tokens = append(tokens, eof) + return tokens, verb +} + +// parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto. +type parser struct { + tokens []string + accepted []string +} + +// topLevelSegments is the target of this parser. +func (p *parser) topLevelSegments() ([]segment, error) { + if _, err := p.accept(typeEOF); err == nil { + p.tokens = p.tokens[:0] + return []segment{literal(eof)}, nil + } + segs, err := p.segments() + if err != nil { + return nil, err + } + if _, err := p.accept(typeEOF); err != nil { + return nil, fmt.Errorf("unexpected token %q after segments %q", p.tokens[0], strings.Join(p.accepted, "")) + } + return segs, nil +} + +func (p *parser) segments() ([]segment, error) { + s, err := p.segment() + if err != nil { + return nil, err + } + + segs := []segment{s} + for { + if _, err := p.accept("/"); err != nil { + return segs, nil + } + s, err := p.segment() + if err != nil { + return segs, err + } + segs = append(segs, s) + } +} + +func (p *parser) segment() (segment, error) { + if _, err := p.accept("*"); err == nil { + return wildcard{}, nil + } + if _, err := p.accept("**"); err == nil { + return deepWildcard{}, nil + } + if l, err := p.literal(); err == nil { + return l, nil + } + + v, err := p.variable() + if err != nil { + return nil, fmt.Errorf("segment neither wildcards, literal or variable: %w", err) + } + return v, nil +} + +func (p *parser) literal() (segment, error) { + lit, err := p.accept(typeLiteral) + if err != nil { + return nil, err + } + return literal(lit), nil +} + +func (p *parser) variable() (segment, error) { + if _, err := p.accept("{"); err != nil { + return nil, err + } + + path, err := p.fieldPath() + if err != nil { + return nil, err + } + + var segs []segment + if _, err := p.accept("="); err == nil { + segs, err = p.segments() + if err != nil { + return nil, fmt.Errorf("invalid segment in variable %q: %w", path, err) + } + } else { + segs = []segment{wildcard{}} + } + + if _, err := p.accept("}"); err != nil { + return nil, fmt.Errorf("unterminated variable segment: %s", path) + } + return variable{ + path: path, + segments: segs, + }, nil +} + +func (p *parser) fieldPath() (string, error) { + c, err := p.accept(typeIdent) + if err != nil { + return "", err + } + components := []string{c} + for { + if _, err := p.accept("."); err != nil { + return strings.Join(components, "."), nil + } + c, err := p.accept(typeIdent) + if err != nil { + return "", fmt.Errorf("invalid field path component: %w", err) + } + components = append(components, c) + } +} + +// A termType is a type of terminal symbols. +type termType string + +// These constants define some of valid values of termType. +// They improve readability of parse functions. +// +// You can also use "/", "*", "**", "." or "=" as valid values. +const ( + typeIdent = termType("ident") + typeLiteral = termType("literal") + typeEOF = termType("$") +) + +// eof is the terminal symbol which always appears at the end of token sequence. +const eof = "\u0000" + +// accept tries to accept a token in "p". +// This function consumes a token and returns it if it matches to the specified "term". +// If it doesn't match, the function does not consume any tokens and return an error. +func (p *parser) accept(term termType) (string, error) { + t := p.tokens[0] + switch term { + case "/", "*", "**", ".", "=", "{", "}": + if t != string(term) && t != "/" { + return "", fmt.Errorf("expected %q but got %q", term, t) + } + case typeEOF: + if t != eof { + return "", fmt.Errorf("expected EOF but got %q", t) + } + case typeIdent: + if err := expectIdent(t); err != nil { + return "", err + } + case typeLiteral: + if err := expectPChars(t); err != nil { + return "", err + } + default: + return "", fmt.Errorf("unknown termType %q", term) + } + p.tokens = p.tokens[1:] + p.accepted = append(p.accepted, t) + return t, nil +} + +// expectPChars determines if "t" consists of only pchars defined in RFC3986. +// +// https://www.ietf.org/rfc/rfc3986.txt, P.49 +// +// pchar = unreserved / pct-encoded / sub-delims / ":" / "@" +// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" +// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" +// / "*" / "+" / "," / ";" / "=" +// pct-encoded = "%" HEXDIG HEXDIG +func expectPChars(t string) error { + const ( + init = iota + pct1 + pct2 + ) + st := init + for _, r := range t { + if st != init { + if !isHexDigit(r) { + return fmt.Errorf("invalid hexdigit: %c(%U)", r, r) + } + switch st { + case pct1: + st = pct2 + case pct2: + st = init + } + continue + } + + // unreserved + switch { + case 'A' <= r && r <= 'Z': + continue + case 'a' <= r && r <= 'z': + continue + case '0' <= r && r <= '9': + continue + } + switch r { + case '-', '.', '_', '~': + // unreserved + case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=': + // sub-delims + case ':', '@': + // rest of pchar + case '%': + // pct-encoded + st = pct1 + default: + return fmt.Errorf("invalid character in path segment: %q(%U)", r, r) + } + } + if st != init { + return fmt.Errorf("invalid percent-encoding in %q", t) + } + return nil +} + +// expectIdent determines if "ident" is a valid identifier in .proto schema ([[:alpha:]_][[:alphanum:]_]*). +func expectIdent(ident string) error { + if ident == "" { + return errors.New("empty identifier") + } + for pos, r := range ident { + switch { + case '0' <= r && r <= '9': + if pos == 0 { + return fmt.Errorf("identifier starting with digit: %s", ident) + } + continue + case 'A' <= r && r <= 'Z': + continue + case 'a' <= r && r <= 'z': + continue + case r == '_': + continue + default: + return fmt.Errorf("invalid character %q(%U) in identifier: %s", r, r, ident) + } + } + return nil +} + +func isHexDigit(r rune) bool { + switch { + case '0' <= r && r <= '9': + return true + case 'A' <= r && r <= 'F': + return true + case 'a' <= r && r <= 'f': + return true + } + return false +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go new file mode 100644 index 0000000..5a814a0 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule/types.go @@ -0,0 +1,60 @@ +package httprule + +import ( + "fmt" + "strings" +) + +type template struct { + segments []segment + verb string + template string +} + +type segment interface { + fmt.Stringer + compile() (ops []op) +} + +type wildcard struct{} + +type deepWildcard struct{} + +type literal string + +type variable struct { + path string + segments []segment +} + +func (wildcard) String() string { + return "*" +} + +func (deepWildcard) String() string { + return "**" +} + +func (l literal) String() string { + return string(l) +} + +func (v variable) String() string { + var segs []string + for _, s := range v.segments { + segs = append(segs, s.String()) + } + return fmt.Sprintf("{%s=%s}", v.path, strings.Join(segs, "/")) +} + +func (t template) String() string { + var segs []string + for _, s := range t.segments { + segs = append(segs, s.String()) + } + str := strings.Join(segs, "/") + if t.verb != "" { + str = fmt.Sprintf("%s:%s", str, t.verb) + } + return "/" + str +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel new file mode 100644 index 0000000..04b4beb --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/BUILD.bazel @@ -0,0 +1,98 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package(default_visibility = ["//visibility:public"]) + +go_library( + name = "runtime", + srcs = [ + "context.go", + "convert.go", + "doc.go", + "errors.go", + "fieldmask.go", + "handler.go", + "marshal_httpbodyproto.go", + "marshal_json.go", + "marshal_jsonpb.go", + "marshal_proto.go", + "marshaler.go", + "marshaler_registry.go", + "mux.go", + "pattern.go", + "proto2_convert.go", + "query.go", + ], + importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/runtime", + deps = [ + "//internal/httprule", + "//utilities", + "@org_golang_google_genproto_googleapis_api//httpbody", + "@org_golang_google_grpc//:grpc", + "@org_golang_google_grpc//codes", + "@org_golang_google_grpc//grpclog", + "@org_golang_google_grpc//health/grpc_health_v1", + "@org_golang_google_grpc//metadata", + "@org_golang_google_grpc//status", + "@org_golang_google_protobuf//encoding/protojson", + "@org_golang_google_protobuf//proto", + "@org_golang_google_protobuf//reflect/protoreflect", + "@org_golang_google_protobuf//reflect/protoregistry", + "@org_golang_google_protobuf//types/known/durationpb", + "@org_golang_google_protobuf//types/known/fieldmaskpb", + "@org_golang_google_protobuf//types/known/structpb", + "@org_golang_google_protobuf//types/known/timestamppb", + "@org_golang_google_protobuf//types/known/wrapperspb", + ], +) + +go_test( + name = "runtime_test", + size = "small", + srcs = [ + "context_test.go", + "convert_test.go", + "errors_test.go", + "fieldmask_test.go", + "handler_test.go", + "marshal_httpbodyproto_test.go", + "marshal_json_test.go", + "marshal_jsonpb_test.go", + "marshal_proto_test.go", + "marshaler_registry_test.go", + "mux_internal_test.go", + "mux_test.go", + "pattern_test.go", + "query_fuzz_test.go", + "query_test.go", + ], + embed = [":runtime"], + deps = [ + "//runtime/internal/examplepb", + "//utilities", + "@com_github_google_go_cmp//cmp", + "@com_github_google_go_cmp//cmp/cmpopts", + "@org_golang_google_genproto_googleapis_api//httpbody", + "@org_golang_google_genproto_googleapis_rpc//errdetails", + "@org_golang_google_genproto_googleapis_rpc//status", + "@org_golang_google_grpc//:grpc", + "@org_golang_google_grpc//codes", + "@org_golang_google_grpc//health/grpc_health_v1", + "@org_golang_google_grpc//metadata", + "@org_golang_google_grpc//status", + "@org_golang_google_protobuf//encoding/protojson", + "@org_golang_google_protobuf//proto", + "@org_golang_google_protobuf//testing/protocmp", + "@org_golang_google_protobuf//types/known/durationpb", + "@org_golang_google_protobuf//types/known/emptypb", + "@org_golang_google_protobuf//types/known/fieldmaskpb", + "@org_golang_google_protobuf//types/known/structpb", + "@org_golang_google_protobuf//types/known/timestamppb", + "@org_golang_google_protobuf//types/known/wrapperspb", + ], +) + +alias( + name = "go_default_library", + actual = ":runtime", + visibility = ["//visibility:public"], +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go new file mode 100644 index 0000000..00b2228 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/context.go @@ -0,0 +1,417 @@ +package runtime + +import ( + "context" + "encoding/base64" + "fmt" + "net" + "net/http" + "net/textproto" + "strconv" + "strings" + "sync" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// MetadataHeaderPrefix is the http prefix that represents custom metadata +// parameters to or from a gRPC call. +const MetadataHeaderPrefix = "Grpc-Metadata-" + +// MetadataPrefix is prepended to permanent HTTP header keys (as specified +// by the IANA) when added to the gRPC context. +const MetadataPrefix = "grpcgateway-" + +// MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to +// HTTP headers in a response handled by grpc-gateway +const MetadataTrailerPrefix = "Grpc-Trailer-" + +const metadataGrpcTimeout = "Grpc-Timeout" +const metadataHeaderBinarySuffix = "-Bin" + +const xForwardedFor = "X-Forwarded-For" +const xForwardedHost = "X-Forwarded-Host" + +// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound +// header isn't present. If the value is 0 the sent `context` will not have a timeout. +var DefaultContextTimeout = 0 * time.Second + +// malformedHTTPHeaders lists the headers that the gRPC server may reject outright as malformed. +// See https://github.com/grpc/grpc-go/pull/4803#issuecomment-986093310 for more context. +var malformedHTTPHeaders = map[string]struct{}{ + "connection": {}, +} + +type ( + rpcMethodKey struct{} + httpPathPatternKey struct{} + httpPatternKey struct{} + + AnnotateContextOption func(ctx context.Context) context.Context +) + +func WithHTTPPathPattern(pattern string) AnnotateContextOption { + return func(ctx context.Context) context.Context { + return withHTTPPathPattern(ctx, pattern) + } +} + +func decodeBinHeader(v string) ([]byte, error) { + if len(v)%4 == 0 { + // Input was padded, or padding was not necessary. + return base64.StdEncoding.DecodeString(v) + } + return base64.RawStdEncoding.DecodeString(v) +} + +/* +AnnotateContext adds context information such as metadata from the request. + +At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For", +except that the forwarded destination is not another HTTP service but rather +a gRPC service. +*/ +func AnnotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, error) { + ctx, md, err := annotateContext(ctx, mux, req, rpcMethodName, options...) + if err != nil { + return nil, err + } + if md == nil { + return ctx, nil + } + + return metadata.NewOutgoingContext(ctx, md), nil +} + +// AnnotateIncomingContext adds context information such as metadata from the request. +// Attach metadata as incoming context. +func AnnotateIncomingContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, error) { + ctx, md, err := annotateContext(ctx, mux, req, rpcMethodName, options...) + if err != nil { + return nil, err + } + if md == nil { + return ctx, nil + } + + return metadata.NewIncomingContext(ctx, md), nil +} + +func isValidGRPCMetadataKey(key string) bool { + // Must be a valid gRPC "Header-Name" as defined here: + // https://github.com/grpc/grpc/blob/4b05dc88b724214d0c725c8e7442cbc7a61b1374/doc/PROTOCOL-HTTP2.md + // This means 0-9 a-z _ - . + // Only lowercase letters are valid in the wire protocol, but the client library will normalize + // uppercase ASCII to lowercase, so uppercase ASCII is also acceptable. + bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode. + for _, ch := range bytes { + validLowercaseLetter := ch >= 'a' && ch <= 'z' + validUppercaseLetter := ch >= 'A' && ch <= 'Z' + validDigit := ch >= '0' && ch <= '9' + validOther := ch == '.' || ch == '-' || ch == '_' + if !validLowercaseLetter && !validUppercaseLetter && !validDigit && !validOther { + return false + } + } + return true +} + +func isValidGRPCMetadataTextValue(textValue string) bool { + // Must be a valid gRPC "ASCII-Value" as defined here: + // https://github.com/grpc/grpc/blob/4b05dc88b724214d0c725c8e7442cbc7a61b1374/doc/PROTOCOL-HTTP2.md + // This means printable ASCII (including/plus spaces); 0x20 to 0x7E inclusive. + bytes := []byte(textValue) // gRPC validates strings on the byte level, not Unicode. + for _, ch := range bytes { + if ch < 0x20 || ch > 0x7E { + return false + } + } + return true +} + +func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcMethodName string, options ...AnnotateContextOption) (context.Context, metadata.MD, error) { + ctx = withRPCMethod(ctx, rpcMethodName) + for _, o := range options { + ctx = o(ctx) + } + timeout := DefaultContextTimeout + if tm := req.Header.Get(metadataGrpcTimeout); tm != "" { + var err error + timeout, err = timeoutDecode(tm) + if err != nil { + return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm) + } + } + var pairs []string + for key, vals := range req.Header { + key = textproto.CanonicalMIMEHeaderKey(key) + switch key { + case xForwardedFor, xForwardedHost: + // Handled separately below + continue + } + + for _, val := range vals { + // For backwards-compatibility, pass through 'authorization' header with no prefix. + if key == "Authorization" { + pairs = append(pairs, "authorization", val) + } + if h, ok := mux.incomingHeaderMatcher(key); ok { + if !isValidGRPCMetadataKey(h) { + grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h) + continue + } + // Handles "-bin" metadata in grpc, since grpc will do another base64 + // encode before sending to server, we need to decode it first. + if strings.HasSuffix(key, metadataHeaderBinarySuffix) { + b, err := decodeBinHeader(val) + if err != nil { + return nil, nil, status.Errorf(codes.InvalidArgument, "invalid binary header %s: %s", key, err) + } + + val = string(b) + } else if !isValidGRPCMetadataTextValue(val) { + grpclog.Errorf("Value of HTTP header %q contains non-ASCII value (not valid as gRPC metadata): skipping", h) + continue + } + pairs = append(pairs, h, val) + } + } + } + if host := req.Header.Get(xForwardedHost); host != "" { + pairs = append(pairs, strings.ToLower(xForwardedHost), host) + } else if req.Host != "" { + pairs = append(pairs, strings.ToLower(xForwardedHost), req.Host) + } + + xff := req.Header.Values(xForwardedFor) + if addr := req.RemoteAddr; addr != "" { + if remoteIP, _, err := net.SplitHostPort(addr); err == nil { + xff = append(xff, remoteIP) + } + } + if len(xff) > 0 { + pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", ")) + } + + if timeout != 0 { + ctx, _ = context.WithTimeout(ctx, timeout) + } + md := metadata.Pairs(pairs...) + for _, mda := range mux.metadataAnnotators { + md = metadata.Join(md, mda(ctx, req)) + } + if len(md) == 0 { + return ctx, nil, nil + } + return ctx, md, nil +} + +// ServerMetadata consists of metadata sent from gRPC server. +type ServerMetadata struct { + HeaderMD metadata.MD + TrailerMD metadata.MD +} + +type serverMetadataKey struct{} + +// NewServerMetadataContext creates a new context with ServerMetadata +func NewServerMetadataContext(ctx context.Context, md ServerMetadata) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, serverMetadataKey{}, md) +} + +// ServerMetadataFromContext returns the ServerMetadata in ctx +func ServerMetadataFromContext(ctx context.Context) (md ServerMetadata, ok bool) { + if ctx == nil { + return md, false + } + md, ok = ctx.Value(serverMetadataKey{}).(ServerMetadata) + return +} + +// ServerTransportStream implements grpc.ServerTransportStream. +// It should only be used by the generated files to support grpc.SendHeader +// outside of gRPC server use. +type ServerTransportStream struct { + mu sync.Mutex + header metadata.MD + trailer metadata.MD +} + +// Method returns the method for the stream. +func (s *ServerTransportStream) Method() string { + return "" +} + +// Header returns the header metadata of the stream. +func (s *ServerTransportStream) Header() metadata.MD { + s.mu.Lock() + defer s.mu.Unlock() + return s.header.Copy() +} + +// SetHeader sets the header metadata. +func (s *ServerTransportStream) SetHeader(md metadata.MD) error { + if md.Len() == 0 { + return nil + } + + s.mu.Lock() + s.header = metadata.Join(s.header, md) + s.mu.Unlock() + return nil +} + +// SendHeader sets the header metadata. +func (s *ServerTransportStream) SendHeader(md metadata.MD) error { + return s.SetHeader(md) +} + +// Trailer returns the cached trailer metadata. +func (s *ServerTransportStream) Trailer() metadata.MD { + s.mu.Lock() + defer s.mu.Unlock() + return s.trailer.Copy() +} + +// SetTrailer sets the trailer metadata. +func (s *ServerTransportStream) SetTrailer(md metadata.MD) error { + if md.Len() == 0 { + return nil + } + + s.mu.Lock() + s.trailer = metadata.Join(s.trailer, md) + s.mu.Unlock() + return nil +} + +func timeoutDecode(s string) (time.Duration, error) { + size := len(s) + if size < 2 { + return 0, fmt.Errorf("timeout string is too short: %q", s) + } + d, ok := timeoutUnitToDuration(s[size-1]) + if !ok { + return 0, fmt.Errorf("timeout unit is not recognized: %q", s) + } + t, err := strconv.ParseInt(s[:size-1], 10, 64) + if err != nil { + return 0, err + } + return d * time.Duration(t), nil +} + +func timeoutUnitToDuration(u uint8) (d time.Duration, ok bool) { + switch u { + case 'H': + return time.Hour, true + case 'M': + return time.Minute, true + case 'S': + return time.Second, true + case 'm': + return time.Millisecond, true + case 'u': + return time.Microsecond, true + case 'n': + return time.Nanosecond, true + default: + return + } +} + +// isPermanentHTTPHeader checks whether hdr belongs to the list of +// permanent request headers maintained by IANA. +// http://www.iana.org/assignments/message-headers/message-headers.xml +func isPermanentHTTPHeader(hdr string) bool { + switch hdr { + case + "Accept", + "Accept-Charset", + "Accept-Language", + "Accept-Ranges", + "Authorization", + "Cache-Control", + "Content-Type", + "Cookie", + "Date", + "Expect", + "From", + "Host", + "If-Match", + "If-Modified-Since", + "If-None-Match", + "If-Schedule-Tag-Match", + "If-Unmodified-Since", + "Max-Forwards", + "Origin", + "Pragma", + "Referer", + "User-Agent", + "Via", + "Warning": + return true + } + return false +} + +// isMalformedHTTPHeader checks whether header belongs to the list of +// "malformed headers" and would be rejected by the gRPC server. +func isMalformedHTTPHeader(header string) bool { + _, isMalformed := malformedHTTPHeaders[strings.ToLower(header)] + return isMalformed +} + +// RPCMethod returns the method string for the server context. The returned +// string is in the format of "/package.service/method". +func RPCMethod(ctx context.Context) (string, bool) { + m := ctx.Value(rpcMethodKey{}) + if m == nil { + return "", false + } + ms, ok := m.(string) + if !ok { + return "", false + } + return ms, true +} + +func withRPCMethod(ctx context.Context, rpcMethodName string) context.Context { + return context.WithValue(ctx, rpcMethodKey{}, rpcMethodName) +} + +// HTTPPathPattern returns the HTTP path pattern string relating to the HTTP handler, if one exists. +// The format of the returned string is defined by the google.api.http path template type. +func HTTPPathPattern(ctx context.Context) (string, bool) { + m := ctx.Value(httpPathPatternKey{}) + if m == nil { + return "", false + } + ms, ok := m.(string) + if !ok { + return "", false + } + return ms, true +} + +func withHTTPPathPattern(ctx context.Context, httpPathPattern string) context.Context { + return context.WithValue(ctx, httpPathPatternKey{}, httpPathPattern) +} + +// HTTPPattern returns the HTTP path pattern struct relating to the HTTP handler, if one exists. +func HTTPPattern(ctx context.Context) (Pattern, bool) { + v, ok := ctx.Value(httpPatternKey{}).(Pattern) + return v, ok +} + +func withHTTPPattern(ctx context.Context, httpPattern Pattern) context.Context { + return context.WithValue(ctx, httpPatternKey{}, httpPattern) +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go new file mode 100644 index 0000000..2e50082 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/convert.go @@ -0,0 +1,318 @@ +package runtime + +import ( + "encoding/base64" + "fmt" + "strconv" + "strings" + + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/durationpb" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +// String just returns the given string. +// It is just for compatibility to other types. +func String(val string) (string, error) { + return val, nil +} + +// StringSlice converts 'val' where individual strings are separated by +// 'sep' into a string slice. +func StringSlice(val, sep string) ([]string, error) { + return strings.Split(val, sep), nil +} + +// Bool converts the given string representation of a boolean value into bool. +func Bool(val string) (bool, error) { + return strconv.ParseBool(val) +} + +// BoolSlice converts 'val' where individual booleans are separated by +// 'sep' into a bool slice. +func BoolSlice(val, sep string) ([]bool, error) { + s := strings.Split(val, sep) + values := make([]bool, len(s)) + for i, v := range s { + value, err := Bool(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Float64 converts the given string representation into representation of a floating point number into float64. +func Float64(val string) (float64, error) { + return strconv.ParseFloat(val, 64) +} + +// Float64Slice converts 'val' where individual floating point numbers are separated by +// 'sep' into a float64 slice. +func Float64Slice(val, sep string) ([]float64, error) { + s := strings.Split(val, sep) + values := make([]float64, len(s)) + for i, v := range s { + value, err := Float64(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Float32 converts the given string representation of a floating point number into float32. +func Float32(val string) (float32, error) { + f, err := strconv.ParseFloat(val, 32) + if err != nil { + return 0, err + } + return float32(f), nil +} + +// Float32Slice converts 'val' where individual floating point numbers are separated by +// 'sep' into a float32 slice. +func Float32Slice(val, sep string) ([]float32, error) { + s := strings.Split(val, sep) + values := make([]float32, len(s)) + for i, v := range s { + value, err := Float32(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Int64 converts the given string representation of an integer into int64. +func Int64(val string) (int64, error) { + return strconv.ParseInt(val, 0, 64) +} + +// Int64Slice converts 'val' where individual integers are separated by +// 'sep' into an int64 slice. +func Int64Slice(val, sep string) ([]int64, error) { + s := strings.Split(val, sep) + values := make([]int64, len(s)) + for i, v := range s { + value, err := Int64(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Int32 converts the given string representation of an integer into int32. +func Int32(val string) (int32, error) { + i, err := strconv.ParseInt(val, 0, 32) + if err != nil { + return 0, err + } + return int32(i), nil +} + +// Int32Slice converts 'val' where individual integers are separated by +// 'sep' into an int32 slice. +func Int32Slice(val, sep string) ([]int32, error) { + s := strings.Split(val, sep) + values := make([]int32, len(s)) + for i, v := range s { + value, err := Int32(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Uint64 converts the given string representation of an integer into uint64. +func Uint64(val string) (uint64, error) { + return strconv.ParseUint(val, 0, 64) +} + +// Uint64Slice converts 'val' where individual integers are separated by +// 'sep' into a uint64 slice. +func Uint64Slice(val, sep string) ([]uint64, error) { + s := strings.Split(val, sep) + values := make([]uint64, len(s)) + for i, v := range s { + value, err := Uint64(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Uint32 converts the given string representation of an integer into uint32. +func Uint32(val string) (uint32, error) { + i, err := strconv.ParseUint(val, 0, 32) + if err != nil { + return 0, err + } + return uint32(i), nil +} + +// Uint32Slice converts 'val' where individual integers are separated by +// 'sep' into a uint32 slice. +func Uint32Slice(val, sep string) ([]uint32, error) { + s := strings.Split(val, sep) + values := make([]uint32, len(s)) + for i, v := range s { + value, err := Uint32(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Bytes converts the given string representation of a byte sequence into a slice of bytes +// A bytes sequence is encoded in URL-safe base64 without padding +func Bytes(val string) ([]byte, error) { + b, err := base64.StdEncoding.DecodeString(val) + if err != nil { + b, err = base64.URLEncoding.DecodeString(val) + if err != nil { + return nil, err + } + } + return b, nil +} + +// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe +// base64 without padding, are separated by 'sep' into a slice of byte slices. +func BytesSlice(val, sep string) ([][]byte, error) { + s := strings.Split(val, sep) + values := make([][]byte, len(s)) + for i, v := range s { + value, err := Bytes(v) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Timestamp converts the given RFC3339 formatted string into a timestamp.Timestamp. +func Timestamp(val string) (*timestamppb.Timestamp, error) { + var r timestamppb.Timestamp + val = strconv.Quote(strings.Trim(val, `"`)) + unmarshaler := &protojson.UnmarshalOptions{} + if err := unmarshaler.Unmarshal([]byte(val), &r); err != nil { + return nil, err + } + return &r, nil +} + +// Duration converts the given string into a timestamp.Duration. +func Duration(val string) (*durationpb.Duration, error) { + var r durationpb.Duration + val = strconv.Quote(strings.Trim(val, `"`)) + unmarshaler := &protojson.UnmarshalOptions{} + if err := unmarshaler.Unmarshal([]byte(val), &r); err != nil { + return nil, err + } + return &r, nil +} + +// Enum converts the given string into an int32 that should be type casted into the +// correct enum proto type. +func Enum(val string, enumValMap map[string]int32) (int32, error) { + e, ok := enumValMap[val] + if ok { + return e, nil + } + + i, err := Int32(val) + if err != nil { + return 0, fmt.Errorf("%s is not valid", val) + } + for _, v := range enumValMap { + if v == i { + return i, nil + } + } + return 0, fmt.Errorf("%s is not valid", val) +} + +// EnumSlice converts 'val' where individual enums are separated by 'sep' +// into a int32 slice. Each individual int32 should be type casted into the +// correct enum proto type. +func EnumSlice(val, sep string, enumValMap map[string]int32) ([]int32, error) { + s := strings.Split(val, sep) + values := make([]int32, len(s)) + for i, v := range s { + value, err := Enum(v, enumValMap) + if err != nil { + return nil, err + } + values[i] = value + } + return values, nil +} + +// Support for google.protobuf.wrappers on top of primitive types + +// StringValue well-known type support as wrapper around string type +func StringValue(val string) (*wrapperspb.StringValue, error) { + return wrapperspb.String(val), nil +} + +// FloatValue well-known type support as wrapper around float32 type +func FloatValue(val string) (*wrapperspb.FloatValue, error) { + parsedVal, err := Float32(val) + return wrapperspb.Float(parsedVal), err +} + +// DoubleValue well-known type support as wrapper around float64 type +func DoubleValue(val string) (*wrapperspb.DoubleValue, error) { + parsedVal, err := Float64(val) + return wrapperspb.Double(parsedVal), err +} + +// BoolValue well-known type support as wrapper around bool type +func BoolValue(val string) (*wrapperspb.BoolValue, error) { + parsedVal, err := Bool(val) + return wrapperspb.Bool(parsedVal), err +} + +// Int32Value well-known type support as wrapper around int32 type +func Int32Value(val string) (*wrapperspb.Int32Value, error) { + parsedVal, err := Int32(val) + return wrapperspb.Int32(parsedVal), err +} + +// UInt32Value well-known type support as wrapper around uint32 type +func UInt32Value(val string) (*wrapperspb.UInt32Value, error) { + parsedVal, err := Uint32(val) + return wrapperspb.UInt32(parsedVal), err +} + +// Int64Value well-known type support as wrapper around int64 type +func Int64Value(val string) (*wrapperspb.Int64Value, error) { + parsedVal, err := Int64(val) + return wrapperspb.Int64(parsedVal), err +} + +// UInt64Value well-known type support as wrapper around uint64 type +func UInt64Value(val string) (*wrapperspb.UInt64Value, error) { + parsedVal, err := Uint64(val) + return wrapperspb.UInt64(parsedVal), err +} + +// BytesValue well-known type support as wrapper around bytes[] type +func BytesValue(val string) (*wrapperspb.BytesValue, error) { + parsedVal, err := Bytes(val) + return wrapperspb.Bytes(parsedVal), err +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/doc.go new file mode 100644 index 0000000..b6e5ddf --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/doc.go @@ -0,0 +1,5 @@ +/* +Package runtime contains runtime helper functions used by +servers which protoc-gen-grpc-gateway generates. +*/ +package runtime diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go new file mode 100644 index 0000000..bbe7dec --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/errors.go @@ -0,0 +1,204 @@ +package runtime + +import ( + "context" + "errors" + "io" + "net/http" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" +) + +// ErrorHandlerFunc is the signature used to configure error handling. +type ErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, error) + +// StreamErrorHandlerFunc is the signature used to configure stream error handling. +type StreamErrorHandlerFunc func(context.Context, error) *status.Status + +// RoutingErrorHandlerFunc is the signature used to configure error handling for routing errors. +type RoutingErrorHandlerFunc func(context.Context, *ServeMux, Marshaler, http.ResponseWriter, *http.Request, int) + +// HTTPStatusError is the error to use when needing to provide a different HTTP status code for an error +// passed to the DefaultRoutingErrorHandler. +type HTTPStatusError struct { + HTTPStatus int + Err error +} + +func (e *HTTPStatusError) Error() string { + return e.Err.Error() +} + +// HTTPStatusFromCode converts a gRPC error code into the corresponding HTTP response status. +// See: https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto +func HTTPStatusFromCode(code codes.Code) int { + switch code { + case codes.OK: + return http.StatusOK + case codes.Canceled: + return 499 + case codes.Unknown: + return http.StatusInternalServerError + case codes.InvalidArgument: + return http.StatusBadRequest + case codes.DeadlineExceeded: + return http.StatusGatewayTimeout + case codes.NotFound: + return http.StatusNotFound + case codes.AlreadyExists: + return http.StatusConflict + case codes.PermissionDenied: + return http.StatusForbidden + case codes.Unauthenticated: + return http.StatusUnauthorized + case codes.ResourceExhausted: + return http.StatusTooManyRequests + case codes.FailedPrecondition: + // Note, this deliberately doesn't translate to the similarly named '412 Precondition Failed' HTTP response status. + return http.StatusBadRequest + case codes.Aborted: + return http.StatusConflict + case codes.OutOfRange: + return http.StatusBadRequest + case codes.Unimplemented: + return http.StatusNotImplemented + case codes.Internal: + return http.StatusInternalServerError + case codes.Unavailable: + return http.StatusServiceUnavailable + case codes.DataLoss: + return http.StatusInternalServerError + default: + grpclog.Warningf("Unknown gRPC error code: %v", code) + return http.StatusInternalServerError + } +} + +// HTTPError uses the mux-configured error handler. +func HTTPError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { + mux.errorHandler(ctx, mux, marshaler, w, r, err) +} + +// HTTPStreamError uses the mux-configured stream error handler to notify error to the client without closing the connection. +func HTTPStreamError(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { + st := mux.streamErrorHandler(ctx, err) + msg := errorChunk(st) + buf, err := marshaler.Marshal(msg) + if err != nil { + grpclog.Errorf("Failed to marshal an error: %v", err) + return + } + if _, err := w.Write(buf); err != nil { + grpclog.Errorf("Failed to notify error to client: %v", err) + return + } +} + +// DefaultHTTPErrorHandler is the default error handler. +// If "err" is a gRPC Status, the function replies with the status code mapped by HTTPStatusFromCode. +// If "err" is a HTTPStatusError, the function replies with the status code provide by that struct. This is +// intended to allow passing through of specific statuses via the function set via WithRoutingErrorHandler +// for the ServeMux constructor to handle edge cases which the standard mappings in HTTPStatusFromCode +// are insufficient for. +// If otherwise, it replies with http.StatusInternalServerError. +// +// The response body written by this function is a Status message marshaled by the Marshaler. +func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, err error) { + // return Internal when Marshal failed + const fallback = `{"code": 13, "message": "failed to marshal error message"}` + const fallbackRewriter = `{"code": 13, "message": "failed to rewrite error message"}` + + var customStatus *HTTPStatusError + if errors.As(err, &customStatus) { + err = customStatus.Err + } + + s := status.Convert(err) + + w.Header().Del("Trailer") + w.Header().Del("Transfer-Encoding") + + respRw, err := mux.forwardResponseRewriter(ctx, s.Proto()) + if err != nil { + grpclog.Errorf("Failed to rewrite error message %q: %v", s, err) + w.WriteHeader(http.StatusInternalServerError) + if _, err := io.WriteString(w, fallbackRewriter); err != nil { + grpclog.Errorf("Failed to write response: %v", err) + } + return + } + + contentType := marshaler.ContentType(respRw) + w.Header().Set("Content-Type", contentType) + + if s.Code() == codes.Unauthenticated { + w.Header().Set("WWW-Authenticate", s.Message()) + } + + buf, merr := marshaler.Marshal(respRw) + if merr != nil { + grpclog.Errorf("Failed to marshal error message %q: %v", s, merr) + w.WriteHeader(http.StatusInternalServerError) + if _, err := io.WriteString(w, fallback); err != nil { + grpclog.Errorf("Failed to write response: %v", err) + } + return + } + + md, ok := ServerMetadataFromContext(ctx) + if ok { + handleForwardResponseServerMetadata(w, mux, md) + + // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2 + // Unless the request includes a TE header field indicating "trailers" + // is acceptable, as described in Section 4.3, a server SHOULD NOT + // generate trailer fields that it believes are necessary for the user + // agent to receive. + doForwardTrailers := requestAcceptsTrailers(r) + + if doForwardTrailers { + handleForwardResponseTrailerHeader(w, mux, md) + w.Header().Set("Transfer-Encoding", "chunked") + } + } + + st := HTTPStatusFromCode(s.Code()) + if customStatus != nil { + st = customStatus.HTTPStatus + } + + w.WriteHeader(st) + if _, err := w.Write(buf); err != nil { + grpclog.Errorf("Failed to write response: %v", err) + } + + if ok && requestAcceptsTrailers(r) { + handleForwardResponseTrailer(w, mux, md) + } +} + +func DefaultStreamErrorHandler(_ context.Context, err error) *status.Status { + return status.Convert(err) +} + +// DefaultRoutingErrorHandler is our default handler for routing errors. +// By default http error codes mapped on the following error codes: +// +// NotFound -> grpc.NotFound +// StatusBadRequest -> grpc.InvalidArgument +// MethodNotAllowed -> grpc.Unimplemented +// Other -> grpc.Internal, method is not expecting to be called for anything else +func DefaultRoutingErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, r *http.Request, httpStatus int) { + sterr := status.Error(codes.Internal, "Unexpected routing error") + switch httpStatus { + case http.StatusBadRequest: + sterr = status.Error(codes.InvalidArgument, http.StatusText(httpStatus)) + case http.StatusMethodNotAllowed: + sterr = status.Error(codes.Unimplemented, http.StatusText(httpStatus)) + case http.StatusNotFound: + sterr = status.Error(codes.NotFound, http.StatusText(httpStatus)) + } + mux.errorHandler(ctx, mux, marshaler, w, r, sterr) +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go new file mode 100644 index 0000000..2fcd7af --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/fieldmask.go @@ -0,0 +1,168 @@ +package runtime + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "sort" + + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + field_mask "google.golang.org/protobuf/types/known/fieldmaskpb" +) + +func getFieldByName(fields protoreflect.FieldDescriptors, name string) protoreflect.FieldDescriptor { + fd := fields.ByName(protoreflect.Name(name)) + if fd != nil { + return fd + } + + return fields.ByJSONName(name) +} + +// FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body. +func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.FieldMask, error) { + fm := &field_mask.FieldMask{} + var root interface{} + + if err := json.NewDecoder(r).Decode(&root); err != nil { + if errors.Is(err, io.EOF) { + return fm, nil + } + return nil, err + } + + queue := []fieldMaskPathItem{{node: root, msg: msg.ProtoReflect()}} + for len(queue) > 0 { + // dequeue an item + item := queue[0] + queue = queue[1:] + + m, ok := item.node.(map[string]interface{}) + switch { + case ok && len(m) > 0: + // if the item is an object, then enqueue all of its children + for k, v := range m { + if item.msg == nil { + return nil, errors.New("JSON structure did not match request type") + } + + fd := getFieldByName(item.msg.Descriptor().Fields(), k) + if fd == nil { + return nil, fmt.Errorf("could not find field %q in %q", k, item.msg.Descriptor().FullName()) + } + + if isDynamicProtoMessage(fd.Message()) { + for _, p := range buildPathsBlindly(string(fd.FullName().Name()), v) { + newPath := p + if item.path != "" { + newPath = item.path + "." + newPath + } + queue = append(queue, fieldMaskPathItem{path: newPath}) + } + continue + } + + if isProtobufAnyMessage(fd.Message()) && !fd.IsList() { + _, hasTypeField := v.(map[string]interface{})["@type"] + if hasTypeField { + queue = append(queue, fieldMaskPathItem{path: k}) + continue + } else { + return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName()) + } + + } + + child := fieldMaskPathItem{ + node: v, + } + if item.path == "" { + child.path = string(fd.FullName().Name()) + } else { + child.path = item.path + "." + string(fd.FullName().Name()) + } + + switch { + case fd.IsList(), fd.IsMap(): + // As per: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto#L85-L86 + // Do not recurse into repeated fields. The repeated field goes on the end of the path and we stop. + fm.Paths = append(fm.Paths, child.path) + case fd.Message() != nil: + child.msg = item.msg.Get(fd).Message() + fallthrough + default: + queue = append(queue, child) + } + } + case ok && len(m) == 0: + fallthrough + case len(item.path) > 0: + // otherwise, it's a leaf node so print its path + fm.Paths = append(fm.Paths, item.path) + } + } + + // Sort for deterministic output in the presence + // of repeated fields. + sort.Strings(fm.Paths) + + return fm, nil +} + +func isProtobufAnyMessage(md protoreflect.MessageDescriptor) bool { + return md != nil && (md.FullName() == "google.protobuf.Any") +} + +func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool { + return md != nil && (md.FullName() == "google.protobuf.Struct" || md.FullName() == "google.protobuf.Value") +} + +// buildPathsBlindly does not attempt to match proto field names to the +// json value keys. Instead it relies completely on the structure of +// the unmarshalled json contained within in. +// Returns a slice containing all subpaths with the root at the +// passed in name and json value. +func buildPathsBlindly(name string, in interface{}) []string { + m, ok := in.(map[string]interface{}) + if !ok { + return []string{name} + } + + var paths []string + queue := []fieldMaskPathItem{{path: name, node: m}} + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + + m, ok := cur.node.(map[string]interface{}) + if !ok { + // This should never happen since we should always check that we only add + // nodes of type map[string]interface{} to the queue. + continue + } + for k, v := range m { + if mi, ok := v.(map[string]interface{}); ok { + queue = append(queue, fieldMaskPathItem{path: cur.path + "." + k, node: mi}) + } else { + // This is not a struct, so there are no more levels to descend. + curPath := cur.path + "." + k + paths = append(paths, curPath) + } + } + } + return paths +} + +// fieldMaskPathItem stores an in-progress deconstruction of a path for a fieldmask +type fieldMaskPathItem struct { + // the list of prior fields leading up to node connected by dots + path string + + // a generic decoded json object the current item to inspect for further path extraction + node interface{} + + // parent message + msg protoreflect.Message +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go new file mode 100644 index 0000000..4c9083d --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/handler.go @@ -0,0 +1,253 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/textproto" + "strconv" + "strings" + + "google.golang.org/genproto/googleapis/api/httpbody" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// ForwardResponseStream forwards the stream from gRPC server to REST client. +func ForwardResponseStream(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, recv func() (proto.Message, error), opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { + rc := http.NewResponseController(w) + md, ok := ServerMetadataFromContext(ctx) + if !ok { + grpclog.Error("Failed to extract ServerMetadata from context") + http.Error(w, "unexpected error", http.StatusInternalServerError) + return + } + handleForwardResponseServerMetadata(w, mux, md) + + if !mux.disableChunkedEncoding { + w.Header().Set("Transfer-Encoding", "chunked") + } + if err := handleForwardResponseOptions(ctx, w, nil, opts); err != nil { + HTTPError(ctx, mux, marshaler, w, req, err) + return + } + + var delimiter []byte + if d, ok := marshaler.(Delimited); ok { + delimiter = d.Delimiter() + } else { + delimiter = []byte("\n") + } + + var wroteHeader bool + for { + resp, err := recv() + if errors.Is(err, io.EOF) { + return + } + if err != nil { + handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err, delimiter) + return + } + if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { + handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err, delimiter) + return + } + + respRw, err := mux.forwardResponseRewriter(ctx, resp) + if err != nil { + grpclog.Errorf("Rewrite error: %v", err) + handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err, delimiter) + return + } + + if !wroteHeader { + var contentType string + if sct, ok := marshaler.(StreamContentType); ok { + contentType = sct.StreamContentType(respRw) + } else { + contentType = marshaler.ContentType(respRw) + } + w.Header().Set("Content-Type", contentType) + } + + var buf []byte + httpBody, isHTTPBody := respRw.(*httpbody.HttpBody) + switch { + case respRw == nil: + buf, err = marshaler.Marshal(errorChunk(status.New(codes.Internal, "empty response"))) + case isHTTPBody: + buf = httpBody.GetData() + default: + result := map[string]interface{}{"result": respRw} + if rb, ok := respRw.(responseBody); ok { + result["result"] = rb.XXX_ResponseBody() + } + + buf, err = marshaler.Marshal(result) + } + + if err != nil { + grpclog.Errorf("Failed to marshal response chunk: %v", err) + handleForwardResponseStreamError(ctx, wroteHeader, marshaler, w, req, mux, err, delimiter) + return + } + if _, err := w.Write(buf); err != nil { + grpclog.Errorf("Failed to send response chunk: %v", err) + return + } + wroteHeader = true + if _, err := w.Write(delimiter); err != nil { + grpclog.Errorf("Failed to send delimiter chunk: %v", err) + return + } + err = rc.Flush() + if err != nil { + if errors.Is(err, http.ErrNotSupported) { + grpclog.Errorf("Flush not supported in %T", w) + http.Error(w, "unexpected type of web server", http.StatusInternalServerError) + return + } + grpclog.Errorf("Failed to flush response to client: %v", err) + return + } + } +} + +func handleForwardResponseServerMetadata(w http.ResponseWriter, mux *ServeMux, md ServerMetadata) { + for k, vs := range md.HeaderMD { + if h, ok := mux.outgoingHeaderMatcher(k); ok { + for _, v := range vs { + w.Header().Add(h, v) + } + } + } +} + +func handleForwardResponseTrailerHeader(w http.ResponseWriter, mux *ServeMux, md ServerMetadata) { + for k := range md.TrailerMD { + if h, ok := mux.outgoingTrailerMatcher(k); ok { + w.Header().Add("Trailer", textproto.CanonicalMIMEHeaderKey(h)) + } + } +} + +func handleForwardResponseTrailer(w http.ResponseWriter, mux *ServeMux, md ServerMetadata) { + for k, vs := range md.TrailerMD { + if h, ok := mux.outgoingTrailerMatcher(k); ok { + for _, v := range vs { + w.Header().Add(h, v) + } + } + } +} + +// responseBody interface contains method for getting field for marshaling to the response body +// this method is generated for response struct from the value of `response_body` in the `google.api.HttpRule` +type responseBody interface { + XXX_ResponseBody() interface{} +} + +// ForwardResponseMessage forwards the message "resp" from gRPC server to REST client. +func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marshaler, w http.ResponseWriter, req *http.Request, resp proto.Message, opts ...func(context.Context, http.ResponseWriter, proto.Message) error) { + md, ok := ServerMetadataFromContext(ctx) + if ok { + handleForwardResponseServerMetadata(w, mux, md) + } + + // RFC 7230 https://tools.ietf.org/html/rfc7230#section-4.1.2 + // Unless the request includes a TE header field indicating "trailers" + // is acceptable, as described in Section 4.3, a server SHOULD NOT + // generate trailer fields that it believes are necessary for the user + // agent to receive. + doForwardTrailers := requestAcceptsTrailers(req) + + if ok && doForwardTrailers { + handleForwardResponseTrailerHeader(w, mux, md) + w.Header().Set("Transfer-Encoding", "chunked") + } + + contentType := marshaler.ContentType(resp) + w.Header().Set("Content-Type", contentType) + + if err := handleForwardResponseOptions(ctx, w, resp, opts); err != nil { + HTTPError(ctx, mux, marshaler, w, req, err) + return + } + respRw, err := mux.forwardResponseRewriter(ctx, resp) + if err != nil { + grpclog.Errorf("Rewrite error: %v", err) + HTTPError(ctx, mux, marshaler, w, req, err) + return + } + var buf []byte + if rb, ok := respRw.(responseBody); ok { + buf, err = marshaler.Marshal(rb.XXX_ResponseBody()) + } else { + buf, err = marshaler.Marshal(respRw) + } + if err != nil { + grpclog.Errorf("Marshal error: %v", err) + HTTPError(ctx, mux, marshaler, w, req, err) + return + } + + if !doForwardTrailers && mux.writeContentLength { + w.Header().Set("Content-Length", strconv.Itoa(len(buf))) + } + + if _, err = w.Write(buf); err != nil && !errors.Is(err, http.ErrBodyNotAllowed) { + grpclog.Errorf("Failed to write response: %v", err) + } + + if ok && doForwardTrailers { + handleForwardResponseTrailer(w, mux, md) + } +} + +func requestAcceptsTrailers(req *http.Request) bool { + te := req.Header.Get("TE") + return strings.Contains(strings.ToLower(te), "trailers") +} + +func handleForwardResponseOptions(ctx context.Context, w http.ResponseWriter, resp proto.Message, opts []func(context.Context, http.ResponseWriter, proto.Message) error) error { + if len(opts) == 0 { + return nil + } + for _, opt := range opts { + if err := opt(ctx, w, resp); err != nil { + return fmt.Errorf("error handling ForwardResponseOptions: %w", err) + } + } + return nil +} + +func handleForwardResponseStreamError(ctx context.Context, wroteHeader bool, marshaler Marshaler, w http.ResponseWriter, req *http.Request, mux *ServeMux, err error, delimiter []byte) { + st := mux.streamErrorHandler(ctx, err) + msg := errorChunk(st) + if !wroteHeader { + w.Header().Set("Content-Type", marshaler.ContentType(msg)) + w.WriteHeader(HTTPStatusFromCode(st.Code())) + } + buf, err := marshaler.Marshal(msg) + if err != nil { + grpclog.Errorf("Failed to marshal an error: %v", err) + return + } + if _, err := w.Write(buf); err != nil { + grpclog.Errorf("Failed to notify error to client: %v", err) + return + } + if _, err := w.Write(delimiter); err != nil { + grpclog.Errorf("Failed to send delimiter chunk: %v", err) + return + } +} + +func errorChunk(st *status.Status) map[string]proto.Message { + return map[string]proto.Message{"error": st.Proto()} +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_httpbodyproto.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_httpbodyproto.go new file mode 100644 index 0000000..6de2e22 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_httpbodyproto.go @@ -0,0 +1,32 @@ +package runtime + +import ( + "google.golang.org/genproto/googleapis/api/httpbody" +) + +// HTTPBodyMarshaler is a Marshaler which supports marshaling of a +// google.api.HttpBody message as the full response body if it is +// the actual message used as the response. If not, then this will +// simply fallback to the Marshaler specified as its default Marshaler. +type HTTPBodyMarshaler struct { + Marshaler +} + +// ContentType returns its specified content type in case v is a +// google.api.HttpBody message, otherwise it will fall back to the default Marshalers +// content type. +func (h *HTTPBodyMarshaler) ContentType(v interface{}) string { + if httpBody, ok := v.(*httpbody.HttpBody); ok { + return httpBody.GetContentType() + } + return h.Marshaler.ContentType(v) +} + +// Marshal marshals "v" by returning the body bytes if v is a +// google.api.HttpBody message, otherwise it falls back to the default Marshaler. +func (h *HTTPBodyMarshaler) Marshal(v interface{}) ([]byte, error) { + if httpBody, ok := v.(*httpbody.HttpBody); ok { + return httpBody.GetData(), nil + } + return h.Marshaler.Marshal(v) +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_json.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_json.go new file mode 100644 index 0000000..fe52081 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_json.go @@ -0,0 +1,50 @@ +package runtime + +import ( + "encoding/json" + "io" +) + +// JSONBuiltin is a Marshaler which marshals/unmarshals into/from JSON +// with the standard "encoding/json" package of Golang. +// Although it is generally faster for simple proto messages than JSONPb, +// it does not support advanced features of protobuf, e.g. map, oneof, .... +// +// The NewEncoder and NewDecoder types return *json.Encoder and +// *json.Decoder respectively. +type JSONBuiltin struct{} + +// ContentType always Returns "application/json". +func (*JSONBuiltin) ContentType(_ interface{}) string { + return "application/json" +} + +// Marshal marshals "v" into JSON +func (j *JSONBuiltin) Marshal(v interface{}) ([]byte, error) { + return json.Marshal(v) +} + +// MarshalIndent is like Marshal but applies Indent to format the output +func (j *JSONBuiltin) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + return json.MarshalIndent(v, prefix, indent) +} + +// Unmarshal unmarshals JSON data into "v". +func (j *JSONBuiltin) Unmarshal(data []byte, v interface{}) error { + return json.Unmarshal(data, v) +} + +// NewDecoder returns a Decoder which reads JSON stream from "r". +func (j *JSONBuiltin) NewDecoder(r io.Reader) Decoder { + return json.NewDecoder(r) +} + +// NewEncoder returns an Encoder which writes JSON stream into "w". +func (j *JSONBuiltin) NewEncoder(w io.Writer) Encoder { + return json.NewEncoder(w) +} + +// Delimiter for newline encoded JSON streams. +func (j *JSONBuiltin) Delimiter() []byte { + return []byte("\n") +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go new file mode 100644 index 0000000..3d07063 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_jsonpb.go @@ -0,0 +1,349 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "reflect" + "strconv" + + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" +) + +// JSONPb is a Marshaler which marshals/unmarshals into/from JSON +// with the "google.golang.org/protobuf/encoding/protojson" marshaler. +// It supports the full functionality of protobuf unlike JSONBuiltin. +// +// The NewDecoder method returns a DecoderWrapper, so the underlying +// *json.Decoder methods can be used. +type JSONPb struct { + protojson.MarshalOptions + protojson.UnmarshalOptions +} + +// ContentType always returns "application/json". +func (*JSONPb) ContentType(_ interface{}) string { + return "application/json" +} + +// Marshal marshals "v" into JSON. +func (j *JSONPb) Marshal(v interface{}) ([]byte, error) { + var buf bytes.Buffer + if err := j.marshalTo(&buf, v); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func (j *JSONPb) marshalTo(w io.Writer, v interface{}) error { + p, ok := v.(proto.Message) + if !ok { + buf, err := j.marshalNonProtoField(v) + if err != nil { + return err + } + if j.Indent != "" { + b := &bytes.Buffer{} + if err := json.Indent(b, buf, "", j.Indent); err != nil { + return err + } + buf = b.Bytes() + } + _, err = w.Write(buf) + return err + } + + b, err := j.MarshalOptions.Marshal(p) + if err != nil { + return err + } + + _, err = w.Write(b) + return err +} + +var ( + // protoMessageType is stored to prevent constant lookup of the same type at runtime. + protoMessageType = reflect.TypeFor[proto.Message]() +) + +// marshalNonProto marshals a non-message field of a protobuf message. +// This function does not correctly marshal arbitrary data structures into JSON, +// it is only capable of marshaling non-message field values of protobuf, +// i.e. primitive types, enums; pointers to primitives or enums; maps from +// integer/string types to primitives/enums/pointers to messages. +func (j *JSONPb) marshalNonProtoField(v interface{}) ([]byte, error) { + if v == nil { + return []byte("null"), nil + } + rv := reflect.ValueOf(v) + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + return []byte("null"), nil + } + rv = rv.Elem() + } + + if rv.Kind() == reflect.Slice { + if rv.IsNil() { + if j.EmitUnpopulated { + return []byte("[]"), nil + } + return []byte("null"), nil + } + + if rv.Type().Elem().Implements(protoMessageType) { + var buf bytes.Buffer + if err := buf.WriteByte('['); err != nil { + return nil, err + } + for i := 0; i < rv.Len(); i++ { + if i != 0 { + if err := buf.WriteByte(','); err != nil { + return nil, err + } + } + if err := j.marshalTo(&buf, rv.Index(i).Interface().(proto.Message)); err != nil { + return nil, err + } + } + if err := buf.WriteByte(']'); err != nil { + return nil, err + } + + return buf.Bytes(), nil + } + + if rv.Type().Elem().Implements(typeProtoEnum) { + var buf bytes.Buffer + if err := buf.WriteByte('['); err != nil { + return nil, err + } + for i := 0; i < rv.Len(); i++ { + if i != 0 { + if err := buf.WriteByte(','); err != nil { + return nil, err + } + } + var err error + if j.UseEnumNumbers { + _, err = buf.WriteString(strconv.FormatInt(rv.Index(i).Int(), 10)) + } else { + _, err = buf.WriteString("\"" + rv.Index(i).Interface().(protoEnum).String() + "\"") + } + if err != nil { + return nil, err + } + } + if err := buf.WriteByte(']'); err != nil { + return nil, err + } + + return buf.Bytes(), nil + } + } + + if rv.Kind() == reflect.Map { + m := make(map[string]*json.RawMessage) + for _, k := range rv.MapKeys() { + buf, err := j.Marshal(rv.MapIndex(k).Interface()) + if err != nil { + return nil, err + } + m[fmt.Sprintf("%v", k.Interface())] = (*json.RawMessage)(&buf) + } + return json.Marshal(m) + } + if enum, ok := rv.Interface().(protoEnum); ok && !j.UseEnumNumbers { + return json.Marshal(enum.String()) + } + return json.Marshal(rv.Interface()) +} + +// Unmarshal unmarshals JSON "data" into "v" +func (j *JSONPb) Unmarshal(data []byte, v interface{}) error { + return unmarshalJSONPb(data, j.UnmarshalOptions, v) +} + +// NewDecoder returns a Decoder which reads JSON stream from "r". +func (j *JSONPb) NewDecoder(r io.Reader) Decoder { + d := json.NewDecoder(r) + return DecoderWrapper{ + Decoder: d, + UnmarshalOptions: j.UnmarshalOptions, + } +} + +// DecoderWrapper is a wrapper around a *json.Decoder that adds +// support for protos to the Decode method. +type DecoderWrapper struct { + *json.Decoder + protojson.UnmarshalOptions +} + +// Decode wraps the embedded decoder's Decode method to support +// protos using a jsonpb.Unmarshaler. +func (d DecoderWrapper) Decode(v interface{}) error { + return decodeJSONPb(d.Decoder, d.UnmarshalOptions, v) +} + +// NewEncoder returns an Encoder which writes JSON stream into "w". +func (j *JSONPb) NewEncoder(w io.Writer) Encoder { + return EncoderFunc(func(v interface{}) error { + if err := j.marshalTo(w, v); err != nil { + return err + } + // mimic json.Encoder by adding a newline (makes output + // easier to read when it contains multiple encoded items) + _, err := w.Write(j.Delimiter()) + return err + }) +} + +func unmarshalJSONPb(data []byte, unmarshaler protojson.UnmarshalOptions, v interface{}) error { + d := json.NewDecoder(bytes.NewReader(data)) + return decodeJSONPb(d, unmarshaler, v) +} + +func decodeJSONPb(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v interface{}) error { + p, ok := v.(proto.Message) + if !ok { + return decodeNonProtoField(d, unmarshaler, v) + } + + // Decode into bytes for marshalling + var b json.RawMessage + if err := d.Decode(&b); err != nil { + return err + } + + return unmarshaler.Unmarshal([]byte(b), p) +} + +func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions, v interface{}) error { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Ptr { + return fmt.Errorf("%T is not a pointer", v) + } + for rv.Kind() == reflect.Ptr { + if rv.IsNil() { + rv.Set(reflect.New(rv.Type().Elem())) + } + if rv.Type().ConvertibleTo(typeProtoMessage) { + // Decode into bytes for marshalling + var b json.RawMessage + if err := d.Decode(&b); err != nil { + return err + } + + return unmarshaler.Unmarshal([]byte(b), rv.Interface().(proto.Message)) + } + rv = rv.Elem() + } + if rv.Kind() == reflect.Map { + if rv.IsNil() { + rv.Set(reflect.MakeMap(rv.Type())) + } + conv, ok := convFromType[rv.Type().Key().Kind()] + if !ok { + return fmt.Errorf("unsupported type of map field key: %v", rv.Type().Key()) + } + + m := make(map[string]*json.RawMessage) + if err := d.Decode(&m); err != nil { + return err + } + for k, v := range m { + result := conv.Call([]reflect.Value{reflect.ValueOf(k)}) + if err := result[1].Interface(); err != nil { + return err.(error) + } + bk := result[0] + bv := reflect.New(rv.Type().Elem()) + if v == nil { + null := json.RawMessage("null") + v = &null + } + if err := unmarshalJSONPb([]byte(*v), unmarshaler, bv.Interface()); err != nil { + return err + } + rv.SetMapIndex(bk, bv.Elem()) + } + return nil + } + if rv.Kind() == reflect.Slice { + if rv.Type().Elem().Kind() == reflect.Uint8 { + var sl []byte + if err := d.Decode(&sl); err != nil { + return err + } + if sl != nil { + rv.SetBytes(sl) + } + return nil + } + + var sl []json.RawMessage + if err := d.Decode(&sl); err != nil { + return err + } + if sl != nil { + rv.Set(reflect.MakeSlice(rv.Type(), 0, 0)) + } + for _, item := range sl { + bv := reflect.New(rv.Type().Elem()) + if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil { + return err + } + rv.Set(reflect.Append(rv, bv.Elem())) + } + return nil + } + if _, ok := rv.Interface().(protoEnum); ok { + var repr interface{} + if err := d.Decode(&repr); err != nil { + return err + } + switch v := repr.(type) { + case string: + // TODO(yugui) Should use proto.StructProperties? + return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface()) + case float64: + rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type())) + return nil + default: + return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface()) + } + } + return d.Decode(v) +} + +type protoEnum interface { + fmt.Stringer + EnumDescriptor() ([]byte, []int) +} + +var typeProtoEnum = reflect.TypeFor[protoEnum]() + +var typeProtoMessage = reflect.TypeFor[proto.Message]() + +// Delimiter for newline encoded JSON streams. +func (j *JSONPb) Delimiter() []byte { + return []byte("\n") +} + +var ( + convFromType = map[reflect.Kind]reflect.Value{ + reflect.String: reflect.ValueOf(String), + reflect.Bool: reflect.ValueOf(Bool), + reflect.Float64: reflect.ValueOf(Float64), + reflect.Float32: reflect.ValueOf(Float32), + reflect.Int64: reflect.ValueOf(Int64), + reflect.Int32: reflect.ValueOf(Int32), + reflect.Uint64: reflect.ValueOf(Uint64), + reflect.Uint32: reflect.ValueOf(Uint32), + reflect.Slice: reflect.ValueOf(Bytes), + } +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go new file mode 100644 index 0000000..398c780 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshal_proto.go @@ -0,0 +1,60 @@ +package runtime + +import ( + "errors" + "io" + + "google.golang.org/protobuf/proto" +) + +// ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes +type ProtoMarshaller struct{} + +// ContentType always returns "application/octet-stream". +func (*ProtoMarshaller) ContentType(_ interface{}) string { + return "application/octet-stream" +} + +// Marshal marshals "value" into Proto +func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error) { + message, ok := value.(proto.Message) + if !ok { + return nil, errors.New("unable to marshal non proto field") + } + return proto.Marshal(message) +} + +// Unmarshal unmarshals proto "data" into "value" +func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error { + message, ok := value.(proto.Message) + if !ok { + return errors.New("unable to unmarshal non proto field") + } + return proto.Unmarshal(data, message) +} + +// NewDecoder returns a Decoder which reads proto stream from "reader". +func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder { + return DecoderFunc(func(value interface{}) error { + buffer, err := io.ReadAll(reader) + if err != nil { + return err + } + return marshaller.Unmarshal(buffer, value) + }) +} + +// NewEncoder returns an Encoder which writes proto stream into "writer". +func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder { + return EncoderFunc(func(value interface{}) error { + buffer, err := marshaller.Marshal(value) + if err != nil { + return err + } + if _, err := writer.Write(buffer); err != nil { + return err + } + + return nil + }) +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go new file mode 100644 index 0000000..b1dfc37 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler.go @@ -0,0 +1,58 @@ +package runtime + +import ( + "io" +) + +// Marshaler defines a conversion between byte sequence and gRPC payloads / fields. +type Marshaler interface { + // Marshal marshals "v" into byte sequence. + Marshal(v interface{}) ([]byte, error) + // Unmarshal unmarshals "data" into "v". + // "v" must be a pointer value. + Unmarshal(data []byte, v interface{}) error + // NewDecoder returns a Decoder which reads byte sequence from "r". + NewDecoder(r io.Reader) Decoder + // NewEncoder returns an Encoder which writes bytes sequence into "w". + NewEncoder(w io.Writer) Encoder + // ContentType returns the Content-Type which this marshaler is responsible for. + // The parameter describes the type which is being marshalled, which can sometimes + // affect the content type returned. + ContentType(v interface{}) string +} + +// Decoder decodes a byte sequence +type Decoder interface { + Decode(v interface{}) error +} + +// Encoder encodes gRPC payloads / fields into byte sequence. +type Encoder interface { + Encode(v interface{}) error +} + +// DecoderFunc adapts an decoder function into Decoder. +type DecoderFunc func(v interface{}) error + +// Decode delegates invocations to the underlying function itself. +func (f DecoderFunc) Decode(v interface{}) error { return f(v) } + +// EncoderFunc adapts an encoder function into Encoder +type EncoderFunc func(v interface{}) error + +// Encode delegates invocations to the underlying function itself. +func (f EncoderFunc) Encode(v interface{}) error { return f(v) } + +// Delimited defines the streaming delimiter. +type Delimited interface { + // Delimiter returns the record separator for the stream. + Delimiter() []byte +} + +// StreamContentType defines the streaming content type. +type StreamContentType interface { + // StreamContentType returns the content type for a stream. This shares the + // same behaviour as for `Marshaler.ContentType`, but is called, if present, + // in the case of a streamed response. + StreamContentType(v interface{}) string +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go new file mode 100644 index 0000000..07c2811 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/marshaler_registry.go @@ -0,0 +1,109 @@ +package runtime + +import ( + "errors" + "mime" + "net/http" + + "google.golang.org/grpc/grpclog" + "google.golang.org/protobuf/encoding/protojson" +) + +// MIMEWildcard is the fallback MIME type used for requests which do not match +// a registered MIME type. +const MIMEWildcard = "*" + +var ( + acceptHeader = http.CanonicalHeaderKey("Accept") + contentTypeHeader = http.CanonicalHeaderKey("Content-Type") + + defaultMarshaler = &HTTPBodyMarshaler{ + Marshaler: &JSONPb{ + MarshalOptions: protojson.MarshalOptions{ + EmitUnpopulated: true, + }, + UnmarshalOptions: protojson.UnmarshalOptions{ + DiscardUnknown: true, + }, + }, + } +) + +// MarshalerForRequest returns the inbound/outbound marshalers for this request. +// It checks the registry on the ServeMux for the MIME type set by the Content-Type header. +// If it isn't set (or the request Content-Type is empty), checks for "*". +// If there are multiple Content-Type headers set, choose the first one that it can +// exactly match in the registry. +// Otherwise, it follows the above logic for "*"/InboundMarshaler/OutboundMarshaler. +func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, outbound Marshaler) { + for _, acceptVal := range r.Header[acceptHeader] { + if m, ok := mux.marshalers.mimeMap[acceptVal]; ok { + outbound = m + break + } + } + + for _, contentTypeVal := range r.Header[contentTypeHeader] { + contentType, _, err := mime.ParseMediaType(contentTypeVal) + if err != nil { + grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err) + continue + } + if m, ok := mux.marshalers.mimeMap[contentType]; ok { + inbound = m + break + } + } + + if inbound == nil { + inbound = mux.marshalers.mimeMap[MIMEWildcard] + } + if outbound == nil { + outbound = inbound + } + + return inbound, outbound +} + +// marshalerRegistry is a mapping from MIME types to Marshalers. +type marshalerRegistry struct { + mimeMap map[string]Marshaler +} + +// add adds a marshaler for a case-sensitive MIME type string ("*" to match any +// MIME type). +func (m marshalerRegistry) add(mime string, marshaler Marshaler) error { + if len(mime) == 0 { + return errors.New("empty MIME type") + } + + m.mimeMap[mime] = marshaler + + return nil +} + +// makeMarshalerMIMERegistry returns a new registry of marshalers. +// It allows for a mapping of case-sensitive Content-Type MIME type string to runtime.Marshaler interfaces. +// +// For example, you could allow the client to specify the use of the runtime.JSONPb marshaler +// with an "application/jsonpb" Content-Type and the use of the runtime.JSONBuiltin marshaler +// with an "application/json" Content-Type. +// "*" can be used to match any Content-Type. +// This can be attached to a ServerMux with the marshaler option. +func makeMarshalerMIMERegistry() marshalerRegistry { + return marshalerRegistry{ + mimeMap: map[string]Marshaler{ + MIMEWildcard: defaultMarshaler, + }, + } +} + +// WithMarshalerOption returns a ServeMuxOption which associates inbound and outbound +// Marshalers to a MIME type in mux. +func WithMarshalerOption(mime string, marshaler Marshaler) ServeMuxOption { + return func(mux *ServeMux) { + if err := mux.marshalers.add(mime, marshaler); err != nil { + panic(err) + } + } +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go new file mode 100644 index 0000000..69edf5e --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/mux.go @@ -0,0 +1,580 @@ +package runtime + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/textproto" + "regexp" + "strings" + + "github.com/grpc-ecosystem/grpc-gateway/v2/internal/httprule" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/health/grpc_health_v1" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" +) + +// UnescapingMode defines the behavior of ServeMux when unescaping path parameters. +type UnescapingMode int + +const ( + // UnescapingModeLegacy is the default V2 behavior, which escapes the entire + // path string before doing any routing. + UnescapingModeLegacy UnescapingMode = iota + + // UnescapingModeAllExceptReserved unescapes all path parameters except RFC 6570 + // reserved characters. + UnescapingModeAllExceptReserved + + // UnescapingModeAllExceptSlash unescapes URL path parameters except path + // separators, which will be left as "%2F". + UnescapingModeAllExceptSlash + + // UnescapingModeAllCharacters unescapes all URL path parameters. + UnescapingModeAllCharacters + + // UnescapingModeDefault is the default escaping type. + // TODO(v3): default this to UnescapingModeAllExceptReserved per grpc-httpjson-transcoding's + // reference implementation + UnescapingModeDefault = UnescapingModeLegacy +) + +var encodedPathSplitter = regexp.MustCompile("(/|%2F)") + +// A HandlerFunc handles a specific pair of path pattern and HTTP method. +type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) + +// A Middleware handler wraps another HandlerFunc to do some pre- and/or post-processing of the request. This is used as an alternative to gRPC interceptors when using the direct-to-implementation +// registration methods. It is generally recommended to use gRPC client or server interceptors instead +// where possible. +type Middleware func(HandlerFunc) HandlerFunc + +// ServeMux is a request multiplexer for grpc-gateway. +// It matches http requests to patterns and invokes the corresponding handler. +type ServeMux struct { + // handlers maps HTTP method to a list of handlers. + handlers map[string][]handler + middlewares []Middleware + forwardResponseOptions []func(context.Context, http.ResponseWriter, proto.Message) error + forwardResponseRewriter ForwardResponseRewriter + marshalers marshalerRegistry + incomingHeaderMatcher HeaderMatcherFunc + outgoingHeaderMatcher HeaderMatcherFunc + outgoingTrailerMatcher HeaderMatcherFunc + metadataAnnotators []func(context.Context, *http.Request) metadata.MD + errorHandler ErrorHandlerFunc + streamErrorHandler StreamErrorHandlerFunc + routingErrorHandler RoutingErrorHandlerFunc + disablePathLengthFallback bool + disableHTTPMethodOverride bool + unescapingMode UnescapingMode + writeContentLength bool + disableChunkedEncoding bool +} + +// ServeMuxOption is an option that can be given to a ServeMux on construction. +type ServeMuxOption func(*ServeMux) + +// ForwardResponseRewriter is the signature of a function that is capable of rewriting messages +// before they are forwarded in a unary, stream, or error response. +type ForwardResponseRewriter func(ctx context.Context, response proto.Message) (any, error) + +// WithForwardResponseRewriter returns a ServeMuxOption that allows for implementers to insert logic +// that can rewrite the final response before it is forwarded. +// +// The response rewriter function is called during unary message forwarding, stream message +// forwarding and when errors are being forwarded. +// +// NOTE: Using this option will likely make what is generated by `protoc-gen-openapiv2` incorrect. +// Since this option involves making runtime changes to the response shape or type. +func WithForwardResponseRewriter(fwdResponseRewriter ForwardResponseRewriter) ServeMuxOption { + return func(sm *ServeMux) { + sm.forwardResponseRewriter = fwdResponseRewriter + } +} + +// WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption. +// +// forwardResponseOption is an option that will be called on the relevant context.Context, +// http.ResponseWriter, and proto.Message before every forwarded response. +// +// The message may be nil in the case where just a header is being sent. +func WithForwardResponseOption(forwardResponseOption func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.forwardResponseOptions = append(serveMux.forwardResponseOptions, forwardResponseOption) + } +} + +// WithUnescapingMode sets the escaping type. See the definitions of UnescapingMode +// for more information. +func WithUnescapingMode(mode UnescapingMode) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.unescapingMode = mode + } +} + +// WithMiddlewares sets server middleware for all handlers. This is useful as an alternative to gRPC +// interceptors when using the direct-to-implementation registration methods and cannot rely +// on gRPC interceptors. It's recommended to use gRPC interceptors instead if possible. +func WithMiddlewares(middlewares ...Middleware) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.middlewares = append(serveMux.middlewares, middlewares...) + } +} + +// WithDisableChunkedEncoding disables the Transfer-Encoding: chunked header +// for streaming responses. This is useful for streaming implementations that use +// Content-Length, which is mutually exclusive with Transfer-Encoding:chunked. +// Note that this option will not automatically add Content-Length headers, so it should be used with caution. +func WithDisableChunkedEncoding() ServeMuxOption { + return func(mux *ServeMux) { + mux.disableChunkedEncoding = true + } +} + +// SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters. +// Configuring this will mean the generated OpenAPI output is no longer correct, and it should be +// done with careful consideration. +func SetQueryParameterParser(queryParameterParser QueryParameterParser) ServeMuxOption { + return func(serveMux *ServeMux) { + currentQueryParser = queryParameterParser + } +} + +// HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context. +type HeaderMatcherFunc func(string) (string, bool) + +// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header +// keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function. +// HTTP headers that start with 'Grpc-Metadata-' are mapped to gRPC metadata after removing the prefix 'Grpc-Metadata-'. +// Other headers are not added to the gRPC metadata. +func DefaultHeaderMatcher(key string) (string, bool) { + switch key = textproto.CanonicalMIMEHeaderKey(key); { + case isPermanentHTTPHeader(key): + return MetadataPrefix + key, true + case strings.HasPrefix(key, MetadataHeaderPrefix): + return key[len(MetadataHeaderPrefix):], true + } + return "", false +} + +func defaultOutgoingHeaderMatcher(key string) (string, bool) { + return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true +} + +func defaultOutgoingTrailerMatcher(key string) (string, bool) { + return fmt.Sprintf("%s%s", MetadataTrailerPrefix, key), true +} + +// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway. +// +// This matcher will be called with each header in http.Request. If matcher returns true, that header will be +// passed to gRPC context. To transform the header before passing to gRPC context, matcher should return the modified header. +func WithIncomingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { + for _, header := range fn.matchedMalformedHeaders() { + grpclog.Warningf("The configured forwarding filter would allow %q to be sent to the gRPC server, which will likely cause errors. See https://github.com/grpc/grpc-go/pull/4803#issuecomment-986093310 for more information.", header) + } + + return func(mux *ServeMux) { + mux.incomingHeaderMatcher = fn + } +} + +// matchedMalformedHeaders returns the malformed headers that would be forwarded to gRPC server. +func (fn HeaderMatcherFunc) matchedMalformedHeaders() []string { + if fn == nil { + return nil + } + headers := make([]string, 0) + for header := range malformedHTTPHeaders { + out, accept := fn(header) + if accept && isMalformedHTTPHeader(out) { + headers = append(headers, out) + } + } + return headers +} + +// WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway. +// +// This matcher will be called with each header in response header metadata. If matcher returns true, that header will be +// passed to http response returned from gateway. To transform the header before passing to response, +// matcher should return the modified header. +func WithOutgoingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { + return func(mux *ServeMux) { + mux.outgoingHeaderMatcher = fn + } +} + +// WithOutgoingTrailerMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway. +// +// This matcher will be called with each header in response trailer metadata. If matcher returns true, that header will be +// passed to http response returned from gateway. To transform the header before passing to response, +// matcher should return the modified header. +func WithOutgoingTrailerMatcher(fn HeaderMatcherFunc) ServeMuxOption { + return func(mux *ServeMux) { + mux.outgoingTrailerMatcher = fn + } +} + +// WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context. +// +// This can be used by services that need to read from http.Request and modify gRPC context. A common use case +// is reading token from cookie and adding it in gRPC context. +func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.metadataAnnotators = append(serveMux.metadataAnnotators, annotator) + } +} + +// WithErrorHandler returns a ServeMuxOption for configuring a custom error handler. +// +// This can be used to configure a custom error response. +func WithErrorHandler(fn ErrorHandlerFunc) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.errorHandler = fn + } +} + +// WithStreamErrorHandler returns a ServeMuxOption that will use the given custom stream +// error handler, which allows for customizing the error trailer for server-streaming +// calls. +// +// For stream errors that occur before any response has been written, the mux's +// ErrorHandler will be invoked. However, once data has been written, the errors must +// be handled differently: they must be included in the response body. The response body's +// final message will include the error details returned by the stream error handler. +func WithStreamErrorHandler(fn StreamErrorHandlerFunc) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.streamErrorHandler = fn + } +} + +// WithRoutingErrorHandler returns a ServeMuxOption for configuring a custom error handler to handle http routing errors. +// +// Method called for errors which can happen before gRPC route selected or executed. +// The following error codes: StatusMethodNotAllowed StatusNotFound StatusBadRequest +func WithRoutingErrorHandler(fn RoutingErrorHandlerFunc) ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.routingErrorHandler = fn + } +} + +// WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback. +func WithDisablePathLengthFallback() ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.disablePathLengthFallback = true + } +} + +// WithDisableHTTPMethodOverride returns a ServeMuxOption that disables the +// X-HTTP-Method-Override header handling. +// +// When this option is used, the mux will no longer allow POST requests with +// the X-HTTP-Method-Override header to override the HTTP method. The path +// length fallback (POST with application/x-www-form-urlencoded falling back +// to a matching GET handler) is not affected by this option. +func WithDisableHTTPMethodOverride() ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.disableHTTPMethodOverride = true + } +} + +// WithWriteContentLength returns a ServeMuxOption to enable writing content length on non-streaming responses +func WithWriteContentLength() ServeMuxOption { + return func(serveMux *ServeMux) { + serveMux.writeContentLength = true + } +} + +// WithHealthEndpointAt returns a ServeMuxOption that will add an endpoint to the created ServeMux at the path specified by endpointPath. +// When called the handler will forward the request to the upstream grpc service health check (defined in the +// gRPC Health Checking Protocol). +// +// See here https://grpc-ecosystem.github.io/grpc-gateway/docs/operations/health_check/ for more information on how +// to setup the protocol in the grpc server. +// +// If you define a service as query parameter, this will also be forwarded as service in the HealthCheckRequest. +func WithHealthEndpointAt(healthCheckClient grpc_health_v1.HealthClient, endpointPath string) ServeMuxOption { + return func(s *ServeMux) { + // error can be ignored since pattern is definitely valid + _ = s.HandlePath( + http.MethodGet, endpointPath, func(w http.ResponseWriter, r *http.Request, _ map[string]string, + ) { + _, outboundMarshaler := MarshalerForRequest(s, r) + annotatedContext, err := AnnotateContext(r.Context(), s, r, grpc_health_v1.Health_Check_FullMethodName, WithHTTPPathPattern(endpointPath)) + if err != nil { + s.errorHandler(r.Context(), s, outboundMarshaler, w, r, err) + return + } + + var md ServerMetadata + resp, err := healthCheckClient.Check(annotatedContext, &grpc_health_v1.HealthCheckRequest{ + Service: r.URL.Query().Get("service"), + }, grpc.Header(&md.HeaderMD), grpc.Trailer(&md.TrailerMD)) + annotatedContext = NewServerMetadataContext(annotatedContext, md) + if err != nil { + s.errorHandler(annotatedContext, s, outboundMarshaler, w, r, err) + return + } + + w.Header().Set("Content-Type", "application/json") + + if resp.GetStatus() != grpc_health_v1.HealthCheckResponse_SERVING { + switch resp.GetStatus() { + case grpc_health_v1.HealthCheckResponse_NOT_SERVING, grpc_health_v1.HealthCheckResponse_UNKNOWN: + err = status.Error(codes.Unavailable, resp.String()) + case grpc_health_v1.HealthCheckResponse_SERVICE_UNKNOWN: + err = status.Error(codes.NotFound, resp.String()) + } + + s.errorHandler(annotatedContext, s, outboundMarshaler, w, r, err) + return + } + + _ = outboundMarshaler.NewEncoder(w).Encode(resp) + }) + } +} + +// WithHealthzEndpoint returns a ServeMuxOption that will add a /healthz endpoint to the created ServeMux. +// +// See WithHealthEndpointAt for the general implementation. +func WithHealthzEndpoint(healthCheckClient grpc_health_v1.HealthClient) ServeMuxOption { + return WithHealthEndpointAt(healthCheckClient, "/healthz") +} + +// NewServeMux returns a new ServeMux whose internal mapping is empty. +func NewServeMux(opts ...ServeMuxOption) *ServeMux { + serveMux := &ServeMux{ + handlers: make(map[string][]handler), + forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), + forwardResponseRewriter: func(ctx context.Context, response proto.Message) (any, error) { return response, nil }, + marshalers: makeMarshalerMIMERegistry(), + errorHandler: DefaultHTTPErrorHandler, + streamErrorHandler: DefaultStreamErrorHandler, + routingErrorHandler: DefaultRoutingErrorHandler, + unescapingMode: UnescapingModeDefault, + } + + for _, opt := range opts { + opt(serveMux) + } + + if serveMux.incomingHeaderMatcher == nil { + serveMux.incomingHeaderMatcher = DefaultHeaderMatcher + } + if serveMux.outgoingHeaderMatcher == nil { + serveMux.outgoingHeaderMatcher = defaultOutgoingHeaderMatcher + } + if serveMux.outgoingTrailerMatcher == nil { + serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher + } + + return serveMux +} + +// Handle associates "h" to the pair of HTTP method and path pattern. +func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { + if len(s.middlewares) > 0 { + h = chainMiddlewares(s.middlewares)(h) + } + s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...) +} + +// HandlePath allows users to configure custom path handlers. +// refer: https://grpc-ecosystem.github.io/grpc-gateway/docs/operations/inject_router/ +func (s *ServeMux) HandlePath(meth string, pathPattern string, h HandlerFunc) error { + compiler, err := httprule.Parse(pathPattern) + if err != nil { + return fmt.Errorf("parsing path pattern: %w", err) + } + tp := compiler.Compile() + pattern, err := NewPattern(tp.Version, tp.OpCodes, tp.Pool, tp.Verb) + if err != nil { + return fmt.Errorf("creating new pattern: %w", err) + } + s.Handle(meth, pattern, h) + return nil +} + +// ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.URL.Path. +func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + path := r.URL.Path + if !strings.HasPrefix(path, "/") { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusBadRequest) + return + } + + // TODO(v3): remove UnescapingModeLegacy + if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" { + path = r.URL.RawPath + } + + if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) { + if err := r.ParseForm(); err != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + sterr := status.Error(codes.InvalidArgument, err.Error()) + s.errorHandler(ctx, s, outboundMarshaler, w, r, sterr) + return + } + r.Method = strings.ToUpper(override) + } + + var pathComponents []string + // since in UnescapeModeLegacy, the URL will already have been fully unescaped, if we also split on "%2F" + // in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the + // path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default + // behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReserved + if s.unescapingMode == UnescapingModeAllCharacters { + pathComponents = encodedPathSplitter.Split(path[1:], -1) + } else { + pathComponents = strings.Split(path[1:], "/") + } + + lastPathComponent := pathComponents[len(pathComponents)-1] + + for _, h := range s.handlers[r.Method] { + // If the pattern has a verb, explicitly look for a suffix in the last + // component that matches a colon plus the verb. This allows us to + // handle some cases that otherwise can't be correctly handled by the + // former LastIndex case, such as when the verb literal itself contains + // a colon. This should work for all cases that have run through the + // parser because we know what verb we're looking for, however, there + // are still some cases that the parser itself cannot disambiguate. See + // the comment there if interested. + + var verb string + patVerb := h.pat.Verb() + + idx := -1 + if patVerb != "" && strings.HasSuffix(lastPathComponent, ":"+patVerb) { + idx = len(lastPathComponent) - len(patVerb) - 1 + } + if idx == 0 { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound) + return + } + + comps := make([]string, len(pathComponents)) + copy(comps, pathComponents) + + if idx > 0 { + comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:] + } + + pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode) + if err != nil { + var mse MalformedSequenceError + if ok := errors.As(err, &mse); ok { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.errorHandler(ctx, s, outboundMarshaler, w, r, &HTTPStatusError{ + HTTPStatus: http.StatusBadRequest, + Err: mse, + }) + return + } + continue + } + s.handleHandler(h, w, r, pathParams) + return + } + + // if no handler has found for the request, lookup for other methods + // to handle POST -> GET fallback if the request is subject to path + // length fallback. + // Note we are not eagerly checking the request here as we want to return the + // right HTTP status code, and we need to process the fallback candidates in + // order to do that. + for m, handlers := range s.handlers { + if m == r.Method { + continue + } + for _, h := range handlers { + var verb string + patVerb := h.pat.Verb() + + idx := -1 + if patVerb != "" && strings.HasSuffix(lastPathComponent, ":"+patVerb) { + idx = len(lastPathComponent) - len(patVerb) - 1 + } + + comps := make([]string, len(pathComponents)) + copy(comps, pathComponents) + + if idx > 0 { + comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:] + } + + pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode) + if err != nil { + var mse MalformedSequenceError + if ok := errors.As(err, &mse); ok { + _, outboundMarshaler := MarshalerForRequest(s, r) + s.errorHandler(ctx, s, outboundMarshaler, w, r, &HTTPStatusError{ + HTTPStatus: http.StatusBadRequest, + Err: mse, + }) + return + } + continue + } + + // X-HTTP-Method-Override is optional. Always allow fallback to POST. + // Also, only consider POST -> GET fallbacks, and avoid falling back to + // potentially dangerous operations like DELETE. + if s.isPathLengthFallback(r) && m == http.MethodGet { + if err := r.ParseForm(); err != nil { + _, outboundMarshaler := MarshalerForRequest(s, r) + sterr := status.Error(codes.InvalidArgument, err.Error()) + s.errorHandler(ctx, s, outboundMarshaler, w, r, sterr) + return + } + s.handleHandler(h, w, r, pathParams) + return + } + _, outboundMarshaler := MarshalerForRequest(s, r) + s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusMethodNotAllowed) + return + } + } + + _, outboundMarshaler := MarshalerForRequest(s, r) + s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound) +} + +// GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux. +func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.ResponseWriter, proto.Message) error { + return s.forwardResponseOptions +} + +func (s *ServeMux) isPathLengthFallback(r *http.Request) bool { + return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" +} + +type handler struct { + pat Pattern + h HandlerFunc +} + +func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) { + h.h(w, r.WithContext(withHTTPPattern(r.Context(), h.pat)), pathParams) +} + +func chainMiddlewares(mws []Middleware) Middleware { + return func(next HandlerFunc) HandlerFunc { + for i := len(mws); i > 0; i-- { + next = mws[i-1](next) + } + return next + } +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go new file mode 100644 index 0000000..e545071 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/pattern.go @@ -0,0 +1,381 @@ +package runtime + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "google.golang.org/grpc/grpclog" +) + +var ( + // ErrNotMatch indicates that the given HTTP request path does not match to the pattern. + ErrNotMatch = errors.New("not match to the path pattern") + // ErrInvalidPattern indicates that the given definition of Pattern is not valid. + ErrInvalidPattern = errors.New("invalid pattern") +) + +type MalformedSequenceError string + +func (e MalformedSequenceError) Error() string { + return "malformed path escape " + strconv.Quote(string(e)) +} + +type op struct { + code utilities.OpCode + operand int +} + +// Pattern is a template pattern of http request paths defined in +// https://github.com/googleapis/googleapis/blob/master/google/api/http.proto +type Pattern struct { + // ops is a list of operations + ops []op + // pool is a constant pool indexed by the operands or vars. + pool []string + // vars is a list of variables names to be bound by this pattern + vars []string + // stacksize is the max depth of the stack + stacksize int + // tailLen is the length of the fixed-size segments after a deep wildcard + tailLen int + // verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. + verb string +} + +// NewPattern returns a new Pattern from the given definition values. +// "ops" is a sequence of op codes. "pool" is a constant pool. +// "verb" is the verb part of the pattern. It is empty if the pattern does not have the part. +// "version" must be 1 for now. +// It returns an error if the given definition is invalid. +func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, error) { + if version != 1 { + grpclog.Errorf("unsupported version: %d", version) + return Pattern{}, ErrInvalidPattern + } + + l := len(ops) + if l%2 != 0 { + grpclog.Errorf("odd number of ops codes: %d", l) + return Pattern{}, ErrInvalidPattern + } + + var ( + typedOps []op + stack, maxstack int + tailLen int + pushMSeen bool + vars []string + ) + for i := 0; i < l; i += 2 { + op := op{code: utilities.OpCode(ops[i]), operand: ops[i+1]} + switch op.code { + case utilities.OpNop: + continue + case utilities.OpPush: + if pushMSeen { + tailLen++ + } + stack++ + case utilities.OpPushM: + if pushMSeen { + grpclog.Error("pushM appears twice") + return Pattern{}, ErrInvalidPattern + } + pushMSeen = true + stack++ + case utilities.OpLitPush: + if op.operand < 0 || len(pool) <= op.operand { + grpclog.Errorf("negative literal index: %d", op.operand) + return Pattern{}, ErrInvalidPattern + } + if pushMSeen { + tailLen++ + } + stack++ + case utilities.OpConcatN: + if op.operand <= 0 { + grpclog.Errorf("negative concat size: %d", op.operand) + return Pattern{}, ErrInvalidPattern + } + stack -= op.operand + if stack < 0 { + grpclog.Error("stack underflow") + return Pattern{}, ErrInvalidPattern + } + stack++ + case utilities.OpCapture: + if op.operand < 0 || len(pool) <= op.operand { + grpclog.Errorf("variable name index out of bound: %d", op.operand) + return Pattern{}, ErrInvalidPattern + } + v := pool[op.operand] + op.operand = len(vars) + vars = append(vars, v) + stack-- + if stack < 0 { + grpclog.Error("stack underflow") + return Pattern{}, ErrInvalidPattern + } + default: + grpclog.Errorf("invalid opcode: %d", op.code) + return Pattern{}, ErrInvalidPattern + } + + if maxstack < stack { + maxstack = stack + } + typedOps = append(typedOps, op) + } + return Pattern{ + ops: typedOps, + pool: pool, + vars: vars, + stacksize: maxstack, + tailLen: tailLen, + verb: verb, + }, nil +} + +// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization. +func MustPattern(p Pattern, err error) Pattern { + if err != nil { + grpclog.Fatalf("Pattern initialization failed: %v", err) + } + return p +} + +// MatchAndEscape examines components to determine if they match to a Pattern. +// MatchAndEscape will return an error if no Patterns matched or if a pattern +// matched but contained malformed escape sequences. If successful, the function +// returns a mapping from field paths to their captured values. +func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode UnescapingMode) (map[string]string, error) { + if p.verb != verb { + if p.verb != "" { + return nil, ErrNotMatch + } + if len(components) == 0 { + components = []string{":" + verb} + } else { + components = append([]string{}, components...) + components[len(components)-1] += ":" + verb + } + } + + var pos int + stack := make([]string, 0, p.stacksize) + captured := make([]string, len(p.vars)) + l := len(components) + for _, op := range p.ops { + var err error + + switch op.code { + case utilities.OpNop: + continue + case utilities.OpPush, utilities.OpLitPush: + if pos >= l { + return nil, ErrNotMatch + } + c := components[pos] + if op.code == utilities.OpLitPush { + if lit := p.pool[op.operand]; c != lit { + return nil, ErrNotMatch + } + } else if op.code == utilities.OpPush { + if c, err = unescape(c, unescapingMode, false); err != nil { + return nil, err + } + } + stack = append(stack, c) + pos++ + case utilities.OpPushM: + end := len(components) + if end < pos+p.tailLen { + return nil, ErrNotMatch + } + end -= p.tailLen + c := strings.Join(components[pos:end], "/") + if c, err = unescape(c, unescapingMode, true); err != nil { + return nil, err + } + stack = append(stack, c) + pos = end + case utilities.OpConcatN: + n := op.operand + l := len(stack) - n + stack = append(stack[:l], strings.Join(stack[l:], "/")) + case utilities.OpCapture: + n := len(stack) - 1 + captured[op.operand] = stack[n] + stack = stack[:n] + } + } + if pos < l { + return nil, ErrNotMatch + } + bindings := make(map[string]string) + for i, val := range captured { + bindings[p.vars[i]] = val + } + return bindings, nil +} + +// MatchAndEscape examines components to determine if they match to a Pattern. +// It will never perform per-component unescaping (see: UnescapingModeLegacy). +// MatchAndEscape will return an error if no Patterns matched. If successful, +// the function returns a mapping from field paths to their captured values. +// +// Deprecated: Use MatchAndEscape. +func (p Pattern) Match(components []string, verb string) (map[string]string, error) { + return p.MatchAndEscape(components, verb, UnescapingModeDefault) +} + +// Verb returns the verb part of the Pattern. +func (p Pattern) Verb() string { return p.verb } + +func (p Pattern) String() string { + var stack []string + for _, op := range p.ops { + switch op.code { + case utilities.OpNop: + continue + case utilities.OpPush: + stack = append(stack, "*") + case utilities.OpLitPush: + stack = append(stack, p.pool[op.operand]) + case utilities.OpPushM: + stack = append(stack, "**") + case utilities.OpConcatN: + n := op.operand + l := len(stack) - n + stack = append(stack[:l], strings.Join(stack[l:], "/")) + case utilities.OpCapture: + n := len(stack) - 1 + stack[n] = fmt.Sprintf("{%s=%s}", p.vars[op.operand], stack[n]) + } + } + segs := strings.Join(stack, "/") + if p.verb != "" { + return fmt.Sprintf("/%s:%s", segs, p.verb) + } + return "/" + segs +} + +/* + * The following code is adopted and modified from Go's standard library + * and carries the attached license. + * + * Copyright 2009 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ + +// ishex returns whether or not the given byte is a valid hex character +func ishex(c byte) bool { + switch { + case '0' <= c && c <= '9': + return true + case 'a' <= c && c <= 'f': + return true + case 'A' <= c && c <= 'F': + return true + } + return false +} + +func isRFC6570Reserved(c byte) bool { + switch c { + case '!', '#', '$', '&', '\'', '(', ')', '*', + '+', ',', '/', ':', ';', '=', '?', '@', '[', ']': + return true + default: + return false + } +} + +// unhex converts a hex point to the bit representation +func unhex(c byte) byte { + switch { + case '0' <= c && c <= '9': + return c - '0' + case 'a' <= c && c <= 'f': + return c - 'a' + 10 + case 'A' <= c && c <= 'F': + return c - 'A' + 10 + } + return 0 +} + +// shouldUnescapeWithMode returns true if the character is escapable with the +// given mode +func shouldUnescapeWithMode(c byte, mode UnescapingMode) bool { + switch mode { + case UnescapingModeAllExceptReserved: + if isRFC6570Reserved(c) { + return false + } + case UnescapingModeAllExceptSlash: + if c == '/' { + return false + } + case UnescapingModeAllCharacters: + return true + } + return true +} + +// unescape unescapes a path string using the provided mode +func unescape(s string, mode UnescapingMode, multisegment bool) (string, error) { + // TODO(v3): remove UnescapingModeLegacy + if mode == UnescapingModeLegacy { + return s, nil + } + + if !multisegment { + mode = UnescapingModeAllCharacters + } + + // Count %, check that they're well-formed. + n := 0 + for i := 0; i < len(s); { + if s[i] == '%' { + n++ + if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { + s = s[i:] + if len(s) > 3 { + s = s[:3] + } + + return "", MalformedSequenceError(s) + } + i += 3 + } else { + i++ + } + } + + if n == 0 { + return s, nil + } + + var t strings.Builder + t.Grow(len(s)) + for i := 0; i < len(s); i++ { + switch s[i] { + case '%': + c := unhex(s[i+1])<<4 | unhex(s[i+2]) + if shouldUnescapeWithMode(c, mode) { + t.WriteByte(c) + i += 2 + continue + } + fallthrough + default: + t.WriteByte(s[i]) + } + } + + return t.String(), nil +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go new file mode 100644 index 0000000..f710036 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/proto2_convert.go @@ -0,0 +1,80 @@ +package runtime + +import ( + "google.golang.org/protobuf/proto" +) + +// StringP returns a pointer to a string whose pointee is same as the given string value. +func StringP(val string) (*string, error) { + return proto.String(val), nil +} + +// BoolP parses the given string representation of a boolean value, +// and returns a pointer to a bool whose value is same as the parsed value. +func BoolP(val string) (*bool, error) { + b, err := Bool(val) + if err != nil { + return nil, err + } + return proto.Bool(b), nil +} + +// Float64P parses the given string representation of a floating point number, +// and returns a pointer to a float64 whose value is same as the parsed number. +func Float64P(val string) (*float64, error) { + f, err := Float64(val) + if err != nil { + return nil, err + } + return proto.Float64(f), nil +} + +// Float32P parses the given string representation of a floating point number, +// and returns a pointer to a float32 whose value is same as the parsed number. +func Float32P(val string) (*float32, error) { + f, err := Float32(val) + if err != nil { + return nil, err + } + return proto.Float32(f), nil +} + +// Int64P parses the given string representation of an integer +// and returns a pointer to an int64 whose value is same as the parsed integer. +func Int64P(val string) (*int64, error) { + i, err := Int64(val) + if err != nil { + return nil, err + } + return proto.Int64(i), nil +} + +// Int32P parses the given string representation of an integer +// and returns a pointer to an int32 whose value is same as the parsed integer. +func Int32P(val string) (*int32, error) { + i, err := Int32(val) + if err != nil { + return nil, err + } + return proto.Int32(i), err +} + +// Uint64P parses the given string representation of an integer +// and returns a pointer to a uint64 whose value is same as the parsed integer. +func Uint64P(val string) (*uint64, error) { + i, err := Uint64(val) + if err != nil { + return nil, err + } + return proto.Uint64(i), err +} + +// Uint32P parses the given string representation of an integer +// and returns a pointer to a uint32 whose value is same as the parsed integer. +func Uint32P(val string) (*uint32, error) { + i, err := Uint32(val) + if err != nil { + return nil, err + } + return proto.Uint32(i), err +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go new file mode 100644 index 0000000..8549dfb --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/runtime/query.go @@ -0,0 +1,378 @@ +package runtime + +import ( + "errors" + "fmt" + "net/url" + "regexp" + "strconv" + "strings" + "time" + + "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "google.golang.org/grpc/grpclog" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/types/known/durationpb" + field_mask "google.golang.org/protobuf/types/known/fieldmaskpb" + "google.golang.org/protobuf/types/known/structpb" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" +) + +var valuesKeyRegexp = regexp.MustCompile(`^(.*)\[(.*)\]$`) + +var currentQueryParser QueryParameterParser = &DefaultQueryParser{} + +// QueryParameterParser defines interface for all query parameter parsers +type QueryParameterParser interface { + Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error +} + +// PopulateQueryParameters parses query parameters +// into "msg" using current query parser +func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { + return currentQueryParser.Parse(msg, values, filter) +} + +// DefaultQueryParser is a QueryParameterParser which implements the default +// query parameters parsing behavior. +// +// See https://github.com/grpc-ecosystem/grpc-gateway/issues/2632 for more context. +type DefaultQueryParser struct{} + +// Parse populates "values" into "msg". +// A value is ignored if its key starts with one of the elements in "filter". +func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error { + for key, values := range values { + if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 { + key = match[1] + values = append([]string{match[2]}, values...) + } + + msgValue := msg.ProtoReflect() + fieldPath := normalizeFieldPath(msgValue, strings.Split(key, ".")) + if filter.HasCommonPrefix(fieldPath) { + continue + } + if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil { + return err + } + } + return nil +} + +// PopulateFieldFromPath sets a value in a nested Protobuf structure. +func PopulateFieldFromPath(msg proto.Message, fieldPathString string, value string) error { + fieldPath := strings.Split(fieldPathString, ".") + return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}) +} + +func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string { + newFieldPath := make([]string, 0, len(fieldPath)) + for i, fieldName := range fieldPath { + fields := msgValue.Descriptor().Fields() + fieldDesc := fields.ByTextName(fieldName) + if fieldDesc == nil { + fieldDesc = fields.ByJSONName(fieldName) + } + if fieldDesc == nil { + // return initial field path values if no matching message field was found + return fieldPath + } + + newFieldPath = append(newFieldPath, string(fieldDesc.Name())) + + // If this is the last element, we're done + if i == len(fieldPath)-1 { + break + } + + // Only singular message fields are allowed + if fieldDesc.Message() == nil || fieldDesc.Cardinality() == protoreflect.Repeated { + return fieldPath + } + + // Get the nested message + msgValue = msgValue.Get(fieldDesc).Message() + } + + return newFieldPath +} + +func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error { + if len(fieldPath) < 1 { + return errors.New("no field path") + } + if len(values) < 1 { + return errors.New("no value provided") + } + + var fieldDescriptor protoreflect.FieldDescriptor + for i, fieldName := range fieldPath { + fields := msgValue.Descriptor().Fields() + + // Get field by name + fieldDescriptor = fields.ByName(protoreflect.Name(fieldName)) + if fieldDescriptor == nil { + fieldDescriptor = fields.ByJSONName(fieldName) + if fieldDescriptor == nil { + // We're not returning an error here because this could just be + // an extra query parameter that isn't part of the request. + grpclog.Infof("field not found in %q: %q", msgValue.Descriptor().FullName(), strings.Join(fieldPath, ".")) + return nil + } + } + + // Check if oneof already set + if of := fieldDescriptor.ContainingOneof(); of != nil && !of.IsSynthetic() { + if f := msgValue.WhichOneof(of); f != nil { + if fieldDescriptor.Message() == nil || fieldDescriptor.FullName() != f.FullName() { + return fmt.Errorf("field already set for oneof %q", of.FullName().Name()) + } + } + } + + // If this is the last element, we're done + if i == len(fieldPath)-1 { + break + } + + // Only singular message fields are allowed + if fieldDescriptor.Message() == nil || fieldDescriptor.Cardinality() == protoreflect.Repeated { + return fmt.Errorf("invalid path: %q is not a message", fieldName) + } + + // Get the nested message + msgValue = msgValue.Mutable(fieldDescriptor).Message() + } + + switch { + case fieldDescriptor.IsList(): + return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values) + case fieldDescriptor.IsMap(): + return populateMapField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).Map(), values) + } + + if len(values) > 1 { + return fmt.Errorf("too many values for field %q: %s", fieldDescriptor.FullName().Name(), strings.Join(values, ", ")) + } + + return populateField(fieldDescriptor, msgValue, values[0]) +} + +func populateField(fieldDescriptor protoreflect.FieldDescriptor, msgValue protoreflect.Message, value string) error { + v, err := parseField(fieldDescriptor, value) + if err != nil { + return fmt.Errorf("parsing field %q: %w", fieldDescriptor.FullName().Name(), err) + } + + msgValue.Set(fieldDescriptor, v) + return nil +} + +func populateRepeatedField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error { + for _, value := range values { + v, err := parseField(fieldDescriptor, value) + if err != nil { + return fmt.Errorf("parsing list %q: %w", fieldDescriptor.FullName().Name(), err) + } + list.Append(v) + } + + return nil +} + +func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protoreflect.Map, values []string) error { + if len(values) != 2 { + return fmt.Errorf("more than one value provided for key %q in map %q", values[0], fieldDescriptor.FullName()) + } + + key, err := parseField(fieldDescriptor.MapKey(), values[0]) + if err != nil { + return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err) + } + + value, err := parseField(fieldDescriptor.MapValue(), values[1]) + if err != nil { + return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err) + } + + mp.Set(key.MapKey(), value) + + return nil +} + +func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) { + switch fieldDescriptor.Kind() { + case protoreflect.BoolKind: + v, err := strconv.ParseBool(value) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfBool(v), nil + case protoreflect.EnumKind: + enum, err := protoregistry.GlobalTypes.FindEnumByName(fieldDescriptor.Enum().FullName()) + if err != nil { + if errors.Is(err, protoregistry.NotFound) { + return protoreflect.Value{}, fmt.Errorf("enum %q is not registered", fieldDescriptor.Enum().FullName()) + } + return protoreflect.Value{}, fmt.Errorf("failed to look up enum: %w", err) + } + // Look for enum by name + v := enum.Descriptor().Values().ByName(protoreflect.Name(value)) + if v == nil { + i, err := strconv.Atoi(value) + if err != nil { + return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value) + } + // Look for enum by number + if v = enum.Descriptor().Values().ByNumber(protoreflect.EnumNumber(i)); v == nil { + return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value) + } + } + return protoreflect.ValueOfEnum(v.Number()), nil + case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: + v, err := strconv.ParseInt(value, 10, 32) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfInt32(int32(v)), nil + case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: + v, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfInt64(v), nil + case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: + v, err := strconv.ParseUint(value, 10, 32) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfUint32(uint32(v)), nil + case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: + v, err := strconv.ParseUint(value, 10, 64) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfUint64(v), nil + case protoreflect.FloatKind: + v, err := strconv.ParseFloat(value, 32) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfFloat32(float32(v)), nil + case protoreflect.DoubleKind: + v, err := strconv.ParseFloat(value, 64) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfFloat64(v), nil + case protoreflect.StringKind: + return protoreflect.ValueOfString(value), nil + case protoreflect.BytesKind: + v, err := Bytes(value) + if err != nil { + return protoreflect.Value{}, err + } + return protoreflect.ValueOfBytes(v), nil + case protoreflect.MessageKind, protoreflect.GroupKind: + return parseMessage(fieldDescriptor.Message(), value) + default: + panic(fmt.Sprintf("unknown field kind: %v", fieldDescriptor.Kind())) + } +} + +func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (protoreflect.Value, error) { + var msg proto.Message + switch msgDescriptor.FullName() { + case "google.protobuf.Timestamp": + t, err := time.Parse(time.RFC3339Nano, value) + if err != nil { + return protoreflect.Value{}, err + } + timestamp := timestamppb.New(t) + if ok := timestamp.IsValid(); !ok { + return protoreflect.Value{}, fmt.Errorf("%s before 0001-01-01", value) + } + msg = timestamp + case "google.protobuf.Duration": + d, err := time.ParseDuration(value) + if err != nil { + return protoreflect.Value{}, err + } + msg = durationpb.New(d) + case "google.protobuf.DoubleValue": + v, err := strconv.ParseFloat(value, 64) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.Double(v) + case "google.protobuf.FloatValue": + v, err := strconv.ParseFloat(value, 32) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.Float(float32(v)) + case "google.protobuf.Int64Value": + v, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.Int64(v) + case "google.protobuf.Int32Value": + v, err := strconv.ParseInt(value, 10, 32) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.Int32(int32(v)) + case "google.protobuf.UInt64Value": + v, err := strconv.ParseUint(value, 10, 64) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.UInt64(v) + case "google.protobuf.UInt32Value": + v, err := strconv.ParseUint(value, 10, 32) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.UInt32(uint32(v)) + case "google.protobuf.BoolValue": + v, err := strconv.ParseBool(value) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.Bool(v) + case "google.protobuf.StringValue": + msg = wrapperspb.String(value) + case "google.protobuf.BytesValue": + v, err := Bytes(value) + if err != nil { + return protoreflect.Value{}, err + } + msg = wrapperspb.Bytes(v) + case "google.protobuf.FieldMask": + fm := &field_mask.FieldMask{} + fm.Paths = append(fm.Paths, strings.Split(value, ",")...) + msg = fm + case "google.protobuf.Value": + var v structpb.Value + if err := protojson.Unmarshal([]byte(value), &v); err != nil { + return protoreflect.Value{}, err + } + msg = &v + case "google.protobuf.Struct": + var v structpb.Struct + if err := protojson.Unmarshal([]byte(value), &v); err != nil { + return protoreflect.Value{}, err + } + msg = &v + default: + return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName())) + } + + return protoreflect.ValueOfMessage(msg.ProtoReflect()), nil +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/BUILD.bazel new file mode 100644 index 0000000..b894094 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/BUILD.bazel @@ -0,0 +1,31 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test") + +package(default_visibility = ["//visibility:public"]) + +go_library( + name = "utilities", + srcs = [ + "doc.go", + "pattern.go", + "readerfactory.go", + "string_array_flag.go", + "trie.go", + ], + importpath = "github.com/grpc-ecosystem/grpc-gateway/v2/utilities", +) + +go_test( + name = "utilities_test", + size = "small", + srcs = [ + "string_array_flag_test.go", + "trie_test.go", + ], + deps = [":utilities"], +) + +alias( + name = "go_default_library", + actual = ":utilities", + visibility = ["//visibility:public"], +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/doc.go new file mode 100644 index 0000000..cf79a4d --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/doc.go @@ -0,0 +1,2 @@ +// Package utilities provides members for internal use in grpc-gateway. +package utilities diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go new file mode 100644 index 0000000..38ca39c --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/pattern.go @@ -0,0 +1,22 @@ +package utilities + +// OpCode is an opcode of compiled path patterns. +type OpCode int + +// These constants are the valid values of OpCode. +const ( + // OpNop does nothing + OpNop = OpCode(iota) + // OpPush pushes a component to stack + OpPush + // OpLitPush pushes a component to stack if it matches to the literal + OpLitPush + // OpPushM concatenates the remaining components and pushes it to stack + OpPushM + // OpConcatN pops N items from stack, concatenates them and pushes it back to stack + OpConcatN + // OpCapture pops an item and binds it to the variable + OpCapture + // OpEnd is the least positive invalid opcode. + OpEnd +) diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/readerfactory.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/readerfactory.go new file mode 100644 index 0000000..01d26ed --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/readerfactory.go @@ -0,0 +1,19 @@ +package utilities + +import ( + "bytes" + "io" +) + +// IOReaderFactory takes in an io.Reader and returns a function that will allow you to create a new reader that begins +// at the start of the stream +func IOReaderFactory(r io.Reader) (func() io.Reader, error) { + b, err := io.ReadAll(r) + if err != nil { + return nil, err + } + + return func() io.Reader { + return bytes.NewReader(b) + }, nil +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go new file mode 100644 index 0000000..66aa5f2 --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/string_array_flag.go @@ -0,0 +1,33 @@ +package utilities + +import ( + "flag" + "strings" +) + +// flagInterface is a cut down interface to `flag` +type flagInterface interface { + Var(value flag.Value, name string, usage string) +} + +// StringArrayFlag defines a flag with the specified name and usage string. +// The return value is the address of a `StringArrayFlags` variable that stores the repeated values of the flag. +func StringArrayFlag(f flagInterface, name string, usage string) *StringArrayFlags { + value := &StringArrayFlags{} + f.Var(value, name, usage) + return value +} + +// StringArrayFlags is a wrapper of `[]string` to provider an interface for `flag.Var` +type StringArrayFlags []string + +// String returns a string representation of `StringArrayFlags` +func (i *StringArrayFlags) String() string { + return strings.Join(*i, ",") +} + +// Set appends a value to `StringArrayFlags` +func (i *StringArrayFlags) Set(value string) error { + *i = append(*i, value) + return nil +} diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go new file mode 100644 index 0000000..dd99b0e --- /dev/null +++ b/vendor/github.com/grpc-ecosystem/grpc-gateway/v2/utilities/trie.go @@ -0,0 +1,174 @@ +package utilities + +import ( + "sort" +) + +// DoubleArray is a Double Array implementation of trie on sequences of strings. +type DoubleArray struct { + // Encoding keeps an encoding from string to int + Encoding map[string]int + // Base is the base array of Double Array + Base []int + // Check is the check array of Double Array + Check []int +} + +// NewDoubleArray builds a DoubleArray from a set of sequences of strings. +func NewDoubleArray(seqs [][]string) *DoubleArray { + da := &DoubleArray{Encoding: make(map[string]int)} + if len(seqs) == 0 { + return da + } + + encoded := registerTokens(da, seqs) + sort.Sort(byLex(encoded)) + + root := node{row: -1, col: -1, left: 0, right: len(encoded)} + addSeqs(da, encoded, 0, root) + + for i := len(da.Base); i > 0; i-- { + if da.Check[i-1] != 0 { + da.Base = da.Base[:i] + da.Check = da.Check[:i] + break + } + } + return da +} + +func registerTokens(da *DoubleArray, seqs [][]string) [][]int { + var result [][]int + for _, seq := range seqs { + encoded := make([]int, 0, len(seq)) + for _, token := range seq { + if _, ok := da.Encoding[token]; !ok { + da.Encoding[token] = len(da.Encoding) + } + encoded = append(encoded, da.Encoding[token]) + } + result = append(result, encoded) + } + for i := range result { + result[i] = append(result[i], len(da.Encoding)) + } + return result +} + +type node struct { + row, col int + left, right int +} + +func (n node) value(seqs [][]int) int { + return seqs[n.row][n.col] +} + +func (n node) children(seqs [][]int) []*node { + var result []*node + lastVal := int(-1) + last := new(node) + for i := n.left; i < n.right; i++ { + if lastVal == seqs[i][n.col+1] { + continue + } + last.right = i + last = &node{ + row: i, + col: n.col + 1, + left: i, + } + result = append(result, last) + } + last.right = n.right + return result +} + +func addSeqs(da *DoubleArray, seqs [][]int, pos int, n node) { + ensureSize(da, pos) + + children := n.children(seqs) + var i int + for i = 1; ; i++ { + ok := func() bool { + for _, child := range children { + code := child.value(seqs) + j := i + code + ensureSize(da, j) + if da.Check[j] != 0 { + return false + } + } + return true + }() + if ok { + break + } + } + da.Base[pos] = i + for _, child := range children { + code := child.value(seqs) + j := i + code + da.Check[j] = pos + 1 + } + terminator := len(da.Encoding) + for _, child := range children { + code := child.value(seqs) + if code == terminator { + continue + } + j := i + code + addSeqs(da, seqs, j, *child) + } +} + +func ensureSize(da *DoubleArray, i int) { + for i >= len(da.Base) { + da.Base = append(da.Base, make([]int, len(da.Base)+1)...) + da.Check = append(da.Check, make([]int, len(da.Check)+1)...) + } +} + +type byLex [][]int + +func (l byLex) Len() int { return len(l) } +func (l byLex) Swap(i, j int) { l[i], l[j] = l[j], l[i] } +func (l byLex) Less(i, j int) bool { + si := l[i] + sj := l[j] + var k int + for k = 0; k < len(si) && k < len(sj); k++ { + if si[k] < sj[k] { + return true + } + if si[k] > sj[k] { + return false + } + } + return k < len(sj) +} + +// HasCommonPrefix determines if any sequence in the DoubleArray is a prefix of the given sequence. +func (da *DoubleArray) HasCommonPrefix(seq []string) bool { + if len(da.Base) == 0 { + return false + } + + var i int + for _, t := range seq { + code, ok := da.Encoding[t] + if !ok { + break + } + j := da.Base[i] + code + if len(da.Check) <= j || da.Check[j] != i+1 { + break + } + i = j + } + j := da.Base[i] + len(da.Encoding) + if len(da.Check) <= j || da.Check[j] != i+1 { + return false + } + return true +} diff --git a/vendor/github.com/iancoleman/strcase/.travis.yml b/vendor/github.com/iancoleman/strcase/.travis.yml new file mode 100644 index 0000000..79ebc56 --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: go +go: + - 1.10.x + - 1.11.x + - 1.12.x + - 1.13.x + - 1.14.x + - 1.15.x + - master diff --git a/vendor/github.com/iancoleman/strcase/LICENSE b/vendor/github.com/iancoleman/strcase/LICENSE new file mode 100644 index 0000000..3e87ff7 --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Ian Coleman +Copyright (c) 2018 Ma_124, + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, Subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or Substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/iancoleman/strcase/README.md b/vendor/github.com/iancoleman/strcase/README.md new file mode 100644 index 0000000..e72d9e9 --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/README.md @@ -0,0 +1,59 @@ +# strcase +[![Godoc Reference](https://godoc.org/github.com/iancoleman/strcase?status.svg)](http://godoc.org/github.com/iancoleman/strcase) +[![Build Status](https://travis-ci.com/iancoleman/strcase.svg)](https://travis-ci.com/iancoleman/strcase) +[![Coverage](http://gocover.io/_badge/github.com/iancoleman/strcase?0)](http://gocover.io/github.com/iancoleman/strcase) +[![Go Report Card](https://goreportcard.com/badge/github.com/iancoleman/strcase)](https://goreportcard.com/report/github.com/iancoleman/strcase) + +strcase is a go package for converting string case to various cases (e.g. [snake case](https://en.wikipedia.org/wiki/Snake_case) or [camel case](https://en.wikipedia.org/wiki/CamelCase)) to see the full conversion table below. + +## Example + +```go +s := "AnyKind of_string" +``` + +| Function | Result | +|-------------------------------------------|----------------------| +| `ToSnake(s)` | `any_kind_of_string` | +| `ToSnakeWithIgnore(s, '.')` | `any_kind.of_string` | +| `ToScreamingSnake(s)` | `ANY_KIND_OF_STRING` | +| `ToKebab(s)` | `any-kind-of-string` | +| `ToScreamingKebab(s)` | `ANY-KIND-OF-STRING` | +| `ToDelimited(s, '.')` | `any.kind.of.string` | +| `ToScreamingDelimited(s, '.', '', true)` | `ANY.KIND.OF.STRING` | +| `ToScreamingDelimited(s, '.', ' ', true)` | `ANY.KIND OF.STRING` | +| `ToCamel(s)` | `AnyKindOfString` | +| `ToLowerCamel(s)` | `anyKindOfString` | + + +## Install + +```bash +go get -u github.com/iancoleman/strcase +``` + +## Custom Acronyms for ToCamel && ToLowerCamel + +Often times text can contain specific acronyms which you need to be handled a certain way. +Out of the box `strcase` treats the string "ID" as "Id" or "id" but there is no way to cater +for every case in the wild. + +To configure your custom acronym globally you can use the following before running any conversion + +```go +import ( + "github.com/iancoleman/strcase" +) + +func init() { + // results in "Api" using ToCamel("API") + // results in "api" using ToLowerCamel("API") + strcase.ConfigureAcronym("API", "api") + + // results in "PostgreSQL" using ToCamel("PostgreSQL") + // results in "postgreSQL" using ToLowerCamel("PostgreSQL") + strcase.ConfigureAcronym("PostgreSQL", "PostgreSQL") + +} + +``` diff --git a/vendor/github.com/iancoleman/strcase/acronyms.go b/vendor/github.com/iancoleman/strcase/acronyms.go new file mode 100644 index 0000000..7a2fb09 --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/acronyms.go @@ -0,0 +1,13 @@ +package strcase + +import ( + "sync" +) + +var uppercaseAcronym = sync.Map{} + //"ID": "id", + +// ConfigureAcronym allows you to add additional words which will be considered acronyms +func ConfigureAcronym(key, val string) { + uppercaseAcronym.Store(key, val) +} diff --git a/vendor/github.com/iancoleman/strcase/camel.go b/vendor/github.com/iancoleman/strcase/camel.go new file mode 100644 index 0000000..6b88689 --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/camel.go @@ -0,0 +1,87 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ian Coleman + * Copyright (c) 2018 Ma_124, + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, Subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or Substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package strcase + +import ( + "strings" +) + +// Converts a string to CamelCase +func toCamelInitCase(s string, initCase bool) string { + s = strings.TrimSpace(s) + if s == "" { + return s + } + a, hasAcronym := uppercaseAcronym.Load(s) + if hasAcronym { + s = a.(string) + } + + n := strings.Builder{} + n.Grow(len(s)) + capNext := initCase + prevIsCap := false + for i, v := range []byte(s) { + vIsCap := v >= 'A' && v <= 'Z' + vIsLow := v >= 'a' && v <= 'z' + if capNext { + if vIsLow { + v += 'A' + v -= 'a' + } + } else if i == 0 { + if vIsCap { + v += 'a' + v -= 'A' + } + } else if prevIsCap && vIsCap && !hasAcronym { + v += 'a' + v -= 'A' + } + prevIsCap = vIsCap + + if vIsCap || vIsLow { + n.WriteByte(v) + capNext = false + } else if vIsNum := v >= '0' && v <= '9'; vIsNum { + n.WriteByte(v) + capNext = true + } else { + capNext = v == '_' || v == ' ' || v == '-' || v == '.' + } + } + return n.String() +} + +// ToCamel converts a string to CamelCase +func ToCamel(s string) string { + return toCamelInitCase(s, true) +} + +// ToLowerCamel converts a string to lowerCamelCase +func ToLowerCamel(s string) string { + return toCamelInitCase(s, false) +} diff --git a/vendor/github.com/iancoleman/strcase/doc.go b/vendor/github.com/iancoleman/strcase/doc.go new file mode 100644 index 0000000..5e1825b --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/doc.go @@ -0,0 +1,12 @@ +// Package strcase converts strings to various cases. See the conversion table below: +// | Function | Result | +// |---------------------------------|--------------------| +// | ToSnake(s) | any_kind_of_string | +// | ToScreamingSnake(s) | ANY_KIND_OF_STRING | +// | ToKebab(s) | any-kind-of-string | +// | ToScreamingKebab(s) | ANY-KIND-OF-STRING | +// | ToDelimited(s, '.') | any.kind.of.string | +// | ToScreamingDelimited(s, '.') | ANY.KIND.OF.STRING | +// | ToCamel(s) | AnyKindOfString | +// | ToLowerCamel(s) | anyKindOfString | +package strcase diff --git a/vendor/github.com/iancoleman/strcase/snake.go b/vendor/github.com/iancoleman/strcase/snake.go new file mode 100644 index 0000000..df018bc --- /dev/null +++ b/vendor/github.com/iancoleman/strcase/snake.go @@ -0,0 +1,115 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2015 Ian Coleman + * Copyright (c) 2018 Ma_124, + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, Subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or Substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +package strcase + +import ( + "strings" +) + +// ToSnake converts a string to snake_case +func ToSnake(s string) string { + return ToDelimited(s, '_') +} + +func ToSnakeWithIgnore(s string, ignore string) string { + return ToScreamingDelimited(s, '_', ignore, false) +} + +// ToScreamingSnake converts a string to SCREAMING_SNAKE_CASE +func ToScreamingSnake(s string) string { + return ToScreamingDelimited(s, '_', "", true) +} + +// ToKebab converts a string to kebab-case +func ToKebab(s string) string { + return ToDelimited(s, '-') +} + +// ToScreamingKebab converts a string to SCREAMING-KEBAB-CASE +func ToScreamingKebab(s string) string { + return ToScreamingDelimited(s, '-', "", true) +} + +// ToDelimited converts a string to delimited.snake.case +// (in this case `delimiter = '.'`) +func ToDelimited(s string, delimiter uint8) string { + return ToScreamingDelimited(s, delimiter, "", false) +} + +// ToScreamingDelimited converts a string to SCREAMING.DELIMITED.SNAKE.CASE +// (in this case `delimiter = '.'; screaming = true`) +// or delimited.snake.case +// (in this case `delimiter = '.'; screaming = false`) +func ToScreamingDelimited(s string, delimiter uint8, ignore string, screaming bool) string { + s = strings.TrimSpace(s) + n := strings.Builder{} + n.Grow(len(s) + 2) // nominal 2 bytes of extra space for inserted delimiters + for i, v := range []byte(s) { + vIsCap := v >= 'A' && v <= 'Z' + vIsLow := v >= 'a' && v <= 'z' + if vIsLow && screaming { + v += 'A' + v -= 'a' + } else if vIsCap && !screaming { + v += 'a' + v -= 'A' + } + + // treat acronyms as words, eg for JSONData -> JSON is a whole word + if i+1 < len(s) { + next := s[i+1] + vIsNum := v >= '0' && v <= '9' + nextIsCap := next >= 'A' && next <= 'Z' + nextIsLow := next >= 'a' && next <= 'z' + nextIsNum := next >= '0' && next <= '9' + // add underscore if next letter case type is changed + if (vIsCap && (nextIsLow || nextIsNum)) || (vIsLow && (nextIsCap || nextIsNum)) || (vIsNum && (nextIsCap || nextIsLow)) { + prevIgnore := ignore != "" && i > 0 && strings.ContainsAny(string(s[i-1]), ignore) + if !prevIgnore { + if vIsCap && nextIsLow { + if prevIsCap := i > 0 && s[i-1] >= 'A' && s[i-1] <= 'Z'; prevIsCap { + n.WriteByte(delimiter) + } + } + n.WriteByte(v) + if vIsLow || vIsNum || nextIsNum { + n.WriteByte(delimiter) + } + continue + } + } + } + + if (v == ' ' || v == '_' || v == '-' || v == '.') && !strings.ContainsAny(string(v), ignore) { + // replace space/underscore/hyphen/dot with delimiter + n.WriteByte(delimiter) + } else { + n.WriteByte(v) + } + } + + return n.String() +} diff --git a/vendor/github.com/jackc/pgpassfile/.travis.yml b/vendor/github.com/jackc/pgpassfile/.travis.yml new file mode 100644 index 0000000..e176228 --- /dev/null +++ b/vendor/github.com/jackc/pgpassfile/.travis.yml @@ -0,0 +1,9 @@ +language: go + +go: + - 1.x + - tip + +matrix: + allow_failures: + - go: tip diff --git a/vendor/github.com/jackc/pgpassfile/LICENSE b/vendor/github.com/jackc/pgpassfile/LICENSE new file mode 100644 index 0000000..c1c4f50 --- /dev/null +++ b/vendor/github.com/jackc/pgpassfile/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2019 Jack Christensen + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgpassfile/README.md b/vendor/github.com/jackc/pgpassfile/README.md new file mode 100644 index 0000000..661289e --- /dev/null +++ b/vendor/github.com/jackc/pgpassfile/README.md @@ -0,0 +1,8 @@ +[![](https://godoc.org/github.com/jackc/pgpassfile?status.svg)](https://godoc.org/github.com/jackc/pgpassfile) +[![Build Status](https://travis-ci.org/jackc/pgpassfile.svg)](https://travis-ci.org/jackc/pgpassfile) + +# pgpassfile + +Package pgpassfile is a parser PostgreSQL .pgpass files. + +Extracted and rewritten from original implementation in https://github.com/jackc/pgx. diff --git a/vendor/github.com/jackc/pgpassfile/pgpass.go b/vendor/github.com/jackc/pgpassfile/pgpass.go new file mode 100644 index 0000000..f7eed3c --- /dev/null +++ b/vendor/github.com/jackc/pgpassfile/pgpass.go @@ -0,0 +1,110 @@ +// Package pgpassfile is a parser PostgreSQL .pgpass files. +package pgpassfile + +import ( + "bufio" + "io" + "os" + "regexp" + "strings" +) + +// Entry represents a line in a PG passfile. +type Entry struct { + Hostname string + Port string + Database string + Username string + Password string +} + +// Passfile is the in memory data structure representing a PG passfile. +type Passfile struct { + Entries []*Entry +} + +// ReadPassfile reads the file at path and parses it into a Passfile. +func ReadPassfile(path string) (*Passfile, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + return ParsePassfile(f) +} + +// ParsePassfile reads r and parses it into a Passfile. +func ParsePassfile(r io.Reader) (*Passfile, error) { + passfile := &Passfile{} + + scanner := bufio.NewScanner(r) + for scanner.Scan() { + entry := parseLine(scanner.Text()) + if entry != nil { + passfile.Entries = append(passfile.Entries, entry) + } + } + + return passfile, scanner.Err() +} + +// Match (not colons or escaped colon or escaped backslash)+. Essentially gives a split on unescaped +// colon. +var colonSplitterRegexp = regexp.MustCompile("(([^:]|(\\:)))+") + +// var colonSplitterRegexp = regexp.MustCompile("((?:[^:]|(?:\\:)|(?:\\\\))+)") + +// parseLine parses a line into an *Entry. It returns nil on comment lines or any other unparsable +// line. +func parseLine(line string) *Entry { + const ( + tmpBackslash = "\r" + tmpColon = "\n" + ) + + line = strings.TrimSpace(line) + + if strings.HasPrefix(line, "#") { + return nil + } + + line = strings.Replace(line, `\\`, tmpBackslash, -1) + line = strings.Replace(line, `\:`, tmpColon, -1) + + parts := strings.Split(line, ":") + if len(parts) != 5 { + return nil + } + + // Unescape escaped colons and backslashes + for i := range parts { + parts[i] = strings.Replace(parts[i], tmpBackslash, `\`, -1) + parts[i] = strings.Replace(parts[i], tmpColon, `:`, -1) + } + + return &Entry{ + Hostname: parts[0], + Port: parts[1], + Database: parts[2], + Username: parts[3], + Password: parts[4], + } +} + +// FindPassword finds the password for the provided hostname, port, database, and username. For a +// Unix domain socket hostname must be set to "localhost". An empty string will be returned if no +// match is found. +// +// See https://www.postgresql.org/docs/current/libpq-pgpass.html for more password file information. +func (pf *Passfile) FindPassword(hostname, port, database, username string) (password string) { + for _, e := range pf.Entries { + if (e.Hostname == "*" || e.Hostname == hostname) && + (e.Port == "*" || e.Port == port) && + (e.Database == "*" || e.Database == database) && + (e.Username == "*" || e.Username == username) { + return e.Password + } + } + return "" +} diff --git a/vendor/github.com/jackc/pgservicefile/LICENSE b/vendor/github.com/jackc/pgservicefile/LICENSE new file mode 100644 index 0000000..f1b4c28 --- /dev/null +++ b/vendor/github.com/jackc/pgservicefile/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2020 Jack Christensen + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgservicefile/README.md b/vendor/github.com/jackc/pgservicefile/README.md new file mode 100644 index 0000000..2fc7e01 --- /dev/null +++ b/vendor/github.com/jackc/pgservicefile/README.md @@ -0,0 +1,7 @@ +[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgservicefile.svg)](https://pkg.go.dev/github.com/jackc/pgservicefile) +[![Build Status](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgservicefile/actions/workflows/ci.yml) + + +# pgservicefile + +Package pgservicefile is a parser for PostgreSQL service files (e.g. `.pg_service.conf`). diff --git a/vendor/github.com/jackc/pgservicefile/pgservicefile.go b/vendor/github.com/jackc/pgservicefile/pgservicefile.go new file mode 100644 index 0000000..c62caa7 --- /dev/null +++ b/vendor/github.com/jackc/pgservicefile/pgservicefile.go @@ -0,0 +1,81 @@ +// Package pgservicefile is a parser for PostgreSQL service files (e.g. .pg_service.conf). +package pgservicefile + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "strings" +) + +type Service struct { + Name string + Settings map[string]string +} + +type Servicefile struct { + Services []*Service + servicesByName map[string]*Service +} + +// GetService returns the named service. +func (sf *Servicefile) GetService(name string) (*Service, error) { + service, present := sf.servicesByName[name] + if !present { + return nil, errors.New("not found") + } + return service, nil +} + +// ReadServicefile reads the file at path and parses it into a Servicefile. +func ReadServicefile(path string) (*Servicefile, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + return ParseServicefile(f) +} + +// ParseServicefile reads r and parses it into a Servicefile. +func ParseServicefile(r io.Reader) (*Servicefile, error) { + servicefile := &Servicefile{} + + var service *Service + scanner := bufio.NewScanner(r) + lineNum := 0 + for scanner.Scan() { + lineNum += 1 + line := scanner.Text() + line = strings.TrimSpace(line) + + if line == "" || strings.HasPrefix(line, "#") { + // ignore comments and empty lines + } else if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { + service = &Service{Name: line[1 : len(line)-1], Settings: make(map[string]string)} + servicefile.Services = append(servicefile.Services, service) + } else if service != nil { + parts := strings.SplitN(line, "=", 2) + if len(parts) != 2 { + return nil, fmt.Errorf("unable to parse line %d", lineNum) + } + + key := strings.TrimSpace(parts[0]) + value := strings.TrimSpace(parts[1]) + + service.Settings[key] = value + } else { + return nil, fmt.Errorf("line %d is not in a section", lineNum) + } + } + + servicefile.servicesByName = make(map[string]*Service, len(servicefile.Services)) + for _, service := range servicefile.Services { + servicefile.servicesByName[service.Name] = service + } + + return servicefile, scanner.Err() +} diff --git a/vendor/github.com/jackc/pgx/v5/.gitignore b/vendor/github.com/jackc/pgx/v5/.gitignore new file mode 100644 index 0000000..a2ebbe9 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/.gitignore @@ -0,0 +1,27 @@ +# 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 + +.envrc +/.testdb + +.DS_Store diff --git a/vendor/github.com/jackc/pgx/v5/.golangci.yml b/vendor/github.com/jackc/pgx/v5/.golangci.yml new file mode 100644 index 0000000..ec98840 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/.golangci.yml @@ -0,0 +1,28 @@ +# See for configurations: https://golangci-lint.run/usage/configuration/ +version: "2" + +linters: + default: none + enable: + - govet + - ineffassign + - unconvert + - gocritic + +# See: https://golangci-lint.run/usage/formatters/ +formatters: + enable: + - gofmt # https://pkg.go.dev/cmd/gofmt + - gofumpt # https://github.com/mvdan/gofumpt + + settings: + gofmt: + simplify: true # Simplify code: gofmt with `-s` option. + + gofumpt: + # Module path which contains the source code being formatted. + # Default: "" + module-path: github.com/jackc/pgx/v5 # Should match with module in go.mod + # Choose whether to use the extra rules. + # Default: false + extra-rules: true diff --git a/vendor/github.com/jackc/pgx/v5/CHANGELOG.md b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md new file mode 100644 index 0000000..12e633a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/CHANGELOG.md @@ -0,0 +1,605 @@ +# 5.10.0 (June 3, 2026) + +This release includes a significant amount of hardening against malicious or compromised PostgreSQL servers, +contributed by Sean Chittenden at CrowdStrike, Inc. This work bounds binary decoders against attacker-controlled +message sizes, caps server-supplied SCRAM iteration counts, adds `require_auth` to restrict which authentication +methods a server may use (mitigating downgrade attacks under `sslmode=prefer`), and ensures cancellation requests are +sent over TLS when the original connection used TLS. + +## Features + +* Add `require_auth` to restrict accepted server authentication methods (Sean Chittenden at CrowdStrike, Inc.) +* Add `ParseConfigOptions.ConnStringAllowedKeys` to restrict allowed connection string keys (Sean Chittenden at CrowdStrike, Inc.) +* Add `StructArgs` and `StrictStructArgs` for `@`-named queries (Tubelight30) +* Add `ErrConnClosed` sentinel error and unwrap it from `connLockError` (Charlie Tonneslan) +* pgxpool: check if connection is expired before acquire (arthurdotwork) + +## Security Hardening + +* Encrypt `CancelRequest` connection when the primary connection used TLS (Sean Chittenden at CrowdStrike, Inc.) +* Cap server-supplied SCRAM iteration count (Sean Chittenden at CrowdStrike, Inc.) +* Default Frontend max message body length to ~1 GiB (Sean Chittenden at CrowdStrike, Inc.) +* Bound hstore binary decode against malicious server input (Sean Chittenden at CrowdStrike, Inc.) +* Bound array binary decode element length against remaining message bytes (Sean Chittenden at CrowdStrike, Inc.) +* Bound array element count against remaining message bytes (Sean Chittenden at CrowdStrike, Inc.) +* Bound range, multirange, and tsvector binary decoders (Sean Chittenden at CrowdStrike, Inc.) +* Document secure connection configuration (Sean Chittenden at CrowdStrike, Inc.) +* Fix panic on malformed geometric text; return an error instead (MaIII) + +## Fixes + +* Fix scanning `"char"` (OID 18) into `*string` in binary format (luongs3) +* Fix handling of typed-nil `driver.Valuer` in array and composite codecs (Donncha Fahy) +* Fix `CopyData.Data` hex decoding in `UnmarshalJSON` (Charlie Tonneslan) +* Fix data race when context is cancelled during connect +* Fix `parseKeywordValueSettings` rejecting trailing whitespace (alliasgher) +* pgconn: preserve full error chain in `normalizeTimeoutError` (Charlie Tonneslan) +* pgconn: use a fresh context for the fallback connection in `connectPreferred` (Charlie Tonneslan) +* pgxpool: fix `MaxLifetimeDestroyCount` and ping order for acquire-time expiry check +* Add missing error check of `rows.Err` to load types (Jen Altavilla) + +# 5.9.2 (April 18, 2026) + +Fix SQL Injection via placeholder confusion with dollar quoted string literals (GHSA-j88v-2chj-qfwx) + +SQL injection can occur when: + +1. The non-default simple protocol is used. +2. A dollar quoted string literal is used in the SQL query. +3. That query contains text that would be would be interpreted outside as a placeholder outside of a string literal. +4. The value of that placeholder is controllable by the attacker. + +e.g. + +```go +attackValue := `$tag$; drop table canary; --` +_, err = tx.Exec(ctx, `select $tag$ $1 $tag$, $1`, pgx.QueryExecModeSimpleProtocol, attackValue) +``` + +This is unlikely to occur outside of a contrived scenario. + +# 5.9.1 (March 22, 2026) + +* Fix: batch result format corruption when using cached prepared statements (reported by Dirkjan Bussink) + +# 5.9.0 (March 21, 2026) + +This release includes a number of new features such as SCRAM-SHA-256-PLUS support, OAuth authentication support, and +PostgreSQL protocol 3.2 support. + +It significantly reduces the amount of network traffic when using prepared statements (which are used automatically by +default) by avoiding unnecessary Describe Portal messages. This also reduces local memory usage. + +It also includes multiple fixes for potential DoS due to panic or OOM if connected to a malicious server that sends +deliberately malformed messages. + +* Require Go 1.25+ +* Add SCRAM-SHA-256-PLUS support (Adam Brightwell) +* Add OAuth authentication support for PostgreSQL 18 (David Schneider) +* Add PostgreSQL protocol 3.2 support (Dirkjan Bussink) +* Add tsvector type support (Adam Brightwell) +* Skip Describe Portal for cached prepared statements reducing network round trips +* Make LoadTypes query easier to support on "postgres-like" servers (Jelte Fennema-Nio) +* Default empty user to current OS user matching libpq behavior (ShivangSrivastava) +* Optimize LRU statement cache with custom linked list and node pooling (Mathias Bogaert) +* Optimize date scanning by replacing regex with manual parsing (Mathias Bogaert) +* Optimize pgio append/set functions with direct byte shifts (Mathias Bogaert) +* Make RowsAffected faster (Abhishek Chanda) +* Fix: Pipeline.Close panic when server sends multiple FATAL errors (Varun Chawla) +* Fix: ContextWatcher goroutine leak (Hank Donnay) +* Fix: stdlib discard connections with open transactions in ResetSession (Jeremy Schneider) +* Fix: pipelineBatchResults.Exec silently swallowing lastRows error +* Fix: ColumnTypeLength using BPCharArrayOID instead of BPCharOID +* Fix: TSVector text encoding returning nil for valid empty tsvector +* Fix: wrong error messages for Int2 and Int4 underflow +* Fix: Numeric nil Int pointer dereference with Valid: true +* Fix: reversed strings.ContainsAny arguments in Numeric.ScanScientific +* Fix: message length parsing on 32-bit platforms +* Fix: FunctionCallResponse.Decode mishandling of signed result size +* Fix: returning wrong error in configTLS when DecryptPEMBlock fails (Maxim Motyshen) +* Fix: misleading ParseConfig error when default_query_exec_mode is invalid (Skarm) +* Fix: missed Unwatch in Pipeline error paths +* Clarify too many failed acquire attempts error message +* Better error wrapping with context and SQL statement (Aneesh Makala) +* Enable govet and ineffassign linters (Federico Guerinoni) +* Guard against various malformed binary messages (arrays, hstore, multirange, protocol messages) +* Fix various godoc comments (ferhat elmas) +* Fix typos in comments (Oleksandr Redko) + +# 5.8.0 (December 26, 2025) + +* Require Go 1.24+ +* Remove golang.org/x/crypto dependency +* Add OptionShouldPing to control ResetSession ping behavior (ilyam8) +* Fix: Avoid overflow when MaxConns is set to MaxInt32 +* Fix: Close batch pipeline after a query error (Anthonin Bonnefoy) +* Faster shutdown of pgxpool.Pool background goroutines (Blake Gentry) +* Add pgxpool ping timeout (Amirsalar Safaei) +* Fix: Rows.FieldDescriptions for empty query +* Scan unknown types into *any as string or []byte based on format code +* Optimize pgtype.Numeric (Philip Dubé) +* Add AfterNetConnect hook to pgconn.Config +* Fix: Handle for preparing statements that fail during the Describe phase +* Fix overflow in numeric scanning (Ilia Demianenko) +* Fix: json/jsonb sql.Scanner source type is []byte +* Migrate from math/rand to math/rand/v2 (Mathias Bogaert) +* Optimize internal iobufpool (Mathias Bogaert) +* Optimize stmtcache invalidation (Mathias Bogaert) +* Fix: missing error case in interval parsing (Maxime Soulé) +* Fix: invalidate statement/description cache in Exec (James Hartig) +* ColumnTypeLength method return the type length for varbit type (DengChan) +* Array and Composite codecs handle typed nils + +# 5.7.6 (September 8, 2025) + +* Use ParseConfigError in pgx.ParseConfig and pgxpool.ParseConfig (Yurasov Ilia) +* Add PrepareConn hook to pgxpool (Jonathan Hall) +* Reduce allocations in QueryContext (Dominique Lefevre) +* Add MarshalJSON and UnmarshalJSON for pgtype.Uint32 (Panos Koutsovasilis) +* Configure ping behavior on pgxpool with ShouldPing (Christian Kiely) +* zeronull int types implement Int64Valuer and Int64Scanner (Li Zeghong) +* Fix panic when receiving terminate connection message during CopyFrom (Michal Drausowski) +* Fix statement cache not being invalidated on error during batch (Muhammadali Nazarov) + +# 5.7.5 (May 17, 2025) + +* Support sslnegotiation connection option (divyam234) +* Update golang.org/x/crypto to v0.37.0. This placates security scanners that were unable to see that pgx did not use the behavior affected by https://pkg.go.dev/vuln/GO-2025-3487. +* TraceLog now logs Acquire and Release at the debug level (dave sinclair) +* Add support for PGTZ environment variable +* Add support for PGOPTIONS environment variable +* Unpin memory used by Rows quicker +* Remove PlanScan memoization. This resolves a rare issue where scanning could be broken for one type by first scanning another. The problem was in the memoization system and benchmarking revealed that memoization was not providing any meaningful benefit. + +# 5.7.4 (March 24, 2025) + +* Fix / revert change to scanning JSON `null` (Felix Röhrich) + +# 5.7.3 (March 21, 2025) + +* Expose EmptyAcquireWaitTime in pgxpool.Stat (vamshiaruru32) +* Improve SQL sanitizer performance (ninedraft) +* Fix Scan confusion with json(b), sql.Scanner, and automatic dereferencing (moukoublen, felix-roehrich) +* Fix Values() for xml type always returning nil instead of []byte +* Add ability to send Flush message in pipeline mode (zenkovev) +* Fix pgtype.Timestamp's JSON behavior to match PostgreSQL (pconstantinou) +* Better error messages when scanning structs (logicbomb) +* Fix handling of error on batch write (bonnefoa) +* Match libpq's connection fallback behavior more closely (felix-roehrich) +* Add MinIdleConns to pgxpool (djahandarie) + +# 5.7.2 (December 21, 2024) + +* Fix prepared statement already exists on batch prepare failure +* Add commit query to tx options (Lucas Hild) +* Fix pgtype.Timestamp json unmarshal (Shean de Montigny-Desautels) +* Add message body size limits in frontend and backend (zene) +* Add xid8 type +* Ensure planning encodes and scans cannot infinitely recurse +* Implement pgtype.UUID.String() (Konstantin Grachev) +* Switch from ExecParams to Exec in ValidateConnectTargetSessionAttrs functions (Alexander Rumyantsev) +* Update golang.org/x/crypto +* Fix json(b) columns prefer sql.Scanner interface like database/sql (Ludovico Russo) + +# 5.7.1 (September 10, 2024) + +* Fix data race in tracelog.TraceLog +* Update puddle to v2.2.2. This removes the import of nanotime via linkname. +* Update golang.org/x/crypto and golang.org/x/text + +# 5.7.0 (September 7, 2024) + +* Add support for sslrootcert=system (Yann Soubeyrand) +* Add LoadTypes to load multiple types in a single SQL query (Nick Farrell) +* Add XMLCodec supports encoding + scanning XML column type like json (nickcruess-soda) +* Add MultiTrace (Stepan Rabotkin) +* Add TraceLogConfig with customizable TimeKey (stringintech) +* pgx.ErrNoRows wraps sql.ErrNoRows to aid in database/sql compatibility with native pgx functions (merlin) +* Support scanning binary formatted uint32 into string / TextScanner (jennifersp) +* Fix interval encoding to allow 0s and avoid extra spaces (Carlos Pérez-Aradros Herce) +* Update pgservicefile - fixes panic when parsing invalid file +* Better error message when reading past end of batch +* Don't print url when url.Parse returns an error (Kevin Biju) +* Fix snake case name normalization collision in RowToStructByName with db tag (nolandseigler) +* Fix: Scan and encode types with underlying types of arrays + +# 5.6.0 (May 25, 2024) + +* Add StrictNamedArgs (Tomas Zahradnicek) +* Add support for macaddr8 type (Carlos Pérez-Aradros Herce) +* Add SeverityUnlocalized field to PgError / Notice +* Performance optimization of RowToStructByPos/Name (Zach Olstein) +* Allow customizing context canceled behavior for pgconn +* Add ScanLocation to pgtype.Timestamp[tz]Codec +* Add custom data to pgconn.PgConn +* Fix ResultReader.Read() to handle nil values +* Do not encode interval microseconds when they are 0 (Carlos Pérez-Aradros Herce) +* pgconn.SafeToRetry checks for wrapped errors (tjasko) +* Failed connection attempts include all errors +* Optimize LargeObject.Read (Mitar) +* Add tracing for connection acquire and release from pool (ngavinsir) +* Fix encode driver.Valuer not called when nil +* Add support for custom JSON marshal and unmarshal (Mitar) +* Use Go default keepalive for TCP connections (Hans-Joachim Kliemeck) + +# 5.5.5 (March 9, 2024) + +Use spaces instead of parentheses for SQL sanitization. + +This still solves the problem of negative numbers creating a line comment, but this avoids breaking edge cases such as +`set foo to $1` where the substitution is taking place in a location where an arbitrary expression is not allowed. + +# 5.5.4 (March 4, 2024) + +Fix CVE-2024-27304 + +SQL injection can occur if an attacker can cause a single query or bind message to exceed 4 GB in size. An integer +overflow in the calculated message size can cause the one large message to be sent as multiple messages under the +attacker's control. + +Thanks to Paul Gerste for reporting this issue. + +* Fix behavior of CollectRows to return empty slice if Rows are empty (Felix) +* Fix simple protocol encoding of json.RawMessage +* Fix *Pipeline.getResults should close pipeline on error +* Fix panic in TryFindUnderlyingTypeScanPlan (David Kurman) +* Fix deallocation of invalidated cached statements in a transaction +* Handle invalid sslkey file +* Fix scan float4 into sql.Scanner +* Fix pgtype.Bits not making copy of data from read buffer. This would cause the data to be corrupted by future reads. + +# 5.5.3 (February 3, 2024) + +* Fix: prepared statement already exists +* Improve CopyFrom auto-conversion of text-ish values +* Add ltree type support (Florent Viel) +* Make some properties of Batch and QueuedQuery public (Pavlo Golub) +* Add AppendRows function (Edoardo Spadolini) +* Optimize convert UUID [16]byte to string (Kirill Malikov) +* Fix: LargeObject Read and Write of more than ~1GB at a time (Mitar) + +# 5.5.2 (January 13, 2024) + +* Allow NamedArgs to start with underscore +* pgproto3: Maximum message body length support (jeremy.spriet) +* Upgrade golang.org/x/crypto to v0.17.0 +* Add snake_case support to RowToStructByName (Tikhon Fedulov) +* Fix: update description cache after exec prepare (James Hartig) +* Fix: pipeline checks if it is closed (James Hartig and Ryan Fowler) +* Fix: normalize timeout / context errors during TLS startup (Samuel Stauffer) +* Add OnPgError for easier centralized error handling (James Hartig) + +# 5.5.1 (December 9, 2023) + +* Add CopyFromFunc helper function. (robford) +* Add PgConn.Deallocate method that uses PostgreSQL protocol Close message. +* pgx uses new PgConn.Deallocate method. This allows deallocating statements to work in a failed transaction. This fixes a case where the prepared statement map could become invalid. +* Fix: Prefer driver.Valuer over json.Marshaler for json fields. (Jacopo) +* Fix: simple protocol SQL sanitizer previously panicked if an invalid $0 placeholder was used. This now returns an error instead. (maksymnevajdev) +* Add pgtype.Numeric.ScanScientific (Eshton Robateau) + +# 5.5.0 (November 4, 2023) + +* Add CollectExactlyOneRow. (Julien GOTTELAND) +* Add OpenDBFromPool to create *database/sql.DB from *pgxpool.Pool. (Lev Zakharov) +* Prepare can automatically choose statement name based on sql. This makes it easier to explicitly manage prepared statements. +* Statement cache now uses deterministic, stable statement names. +* database/sql prepared statement names are deterministically generated. +* Fix: SendBatch wasn't respecting context cancellation. +* Fix: Timeout error from pipeline is now normalized. +* Fix: database/sql encoding json.RawMessage to []byte. +* CancelRequest: Wait for the cancel request to be acknowledged by the server. This should improve PgBouncer compatibility. (Anton Levakin) +* stdlib: Use Ping instead of CheckConn in ResetSession +* Add json.Marshaler and json.Unmarshaler for Float4, Float8 (Kirill Mironov) + +# 5.4.3 (August 5, 2023) + +* Fix: QCharArrayOID was defined with the wrong OID (Christoph Engelbert) +* Fix: connect_timeout for sslmode=allow|prefer (smaher-edb) +* Fix: pgxpool: background health check cannot overflow pool +* Fix: Check for nil in defer when sending batch (recover properly from panic) +* Fix: json scan of non-string pointer to pointer +* Fix: zeronull.Timestamptz should use pgtype.Timestamptz +* Fix: NewConnsCount was not correctly counting connections created by Acquire directly. (James Hartig) +* RowTo(AddrOf)StructByPos ignores fields with "-" db tag +* Optimization: improve text format numeric parsing (horpto) + +# 5.4.2 (July 11, 2023) + +* Fix: RowScanner errors are fatal to Rows +* Fix: Enable failover efforts when pg_hba.conf disallows non-ssl connections (Brandon Kauffman) +* Hstore text codec internal improvements (Evan Jones) +* Fix: Stop timers for background reader when not in use. Fixes memory leak when closing connections (Adrian-Stefan Mares) +* Fix: Stop background reader as soon as possible. +* Add PgConn.SyncConn(). This combined with the above fix makes it safe to directly use the underlying net.Conn. + +# 5.4.1 (June 18, 2023) + +* Fix: concurrency bug with pgtypeDefaultMap and simple protocol (Lev Zakharov) +* Add TxOptions.BeginQuery to allow overriding the default BEGIN query + +# 5.4.0 (June 14, 2023) + +* Replace platform specific syscalls for non-blocking IO with more traditional goroutines and deadlines. This returns to the v4 approach with some additional improvements and fixes. This restores the ability to use a pgx.Conn over an ssh.Conn as well as other non-TCP or Unix socket connections. In addition, it is a significantly simpler implementation that is less likely to have cross platform issues. +* Optimization: The default type registrations are now shared among all connections. This saves about 100KB of memory per connection. `pgtype.Type` and `pgtype.Codec` values are now required to be immutable after registration. This was already necessary in most cases but wasn't documented until now. (Lev Zakharov) +* Fix: Ensure pgxpool.Pool.QueryRow.Scan releases connection on panic +* CancelRequest: don't try to read the reply (Nicola Murino) +* Fix: correctly handle bool type aliases (Wichert Akkerman) +* Fix: pgconn.CancelRequest: Fix unix sockets: don't use RemoteAddr() +* Fix: pgx.Conn memory leak with prepared statement caching (Evan Jones) +* Add BeforeClose to pgxpool.Pool (Evan Cordell) +* Fix: various hstore fixes and optimizations (Evan Jones) +* Fix: RowToStructByPos with embedded unexported struct +* Support different bool string representations (Lev Zakharov) +* Fix: error when using BatchResults.Exec on a select that returns an error after some rows. +* Fix: pipelineBatchResults.Exec() not returning error from ResultReader +* Fix: pipeline batch results not closing pipeline when error occurs while reading directly from results instead of using + a callback. +* Fix: scanning a table type into a struct +* Fix: scan array of record to pointer to slice of struct +* Fix: handle null for json (Cemre Mengu) +* Batch Query callback is called even when there is an error +* Add RowTo(AddrOf)StructByNameLax (Audi P. Risa P) + +# 5.3.1 (February 27, 2023) + +* Fix: Support v4 and v5 stdlib in same program (Tomáš Procházka) +* Fix: sql.Scanner not being used in certain cases +* Add text format jsonpath support +* Fix: fake non-blocking read adaptive wait time + +# 5.3.0 (February 11, 2023) + +* Fix: json values work with sql.Scanner +* Fixed / improved error messages (Mark Chambers and Yevgeny Pats) +* Fix: support scan into single dimensional arrays +* Fix: MaxConnLifetimeJitter setting actually jitter (Ben Weintraub) +* Fix: driver.Value representation of bytea should be []byte not string +* Fix: better handling of unregistered OIDs +* CopyFrom can use query cache to avoid extra round trip to get OIDs (Alejandro Do Nascimento Mora) +* Fix: encode to json ignoring driver.Valuer +* Support sql.Scanner on renamed base type +* Fix: pgtype.Numeric text encoding of negative numbers (Mark Chambers) +* Fix: connect with multiple hostnames when one can't be resolved +* Upgrade puddle to remove dependency on uber/atomic and fix alignment issue on 32-bit platform +* Fix: scanning json column into **string +* Multiple reductions in memory allocations +* Fake non-blocking read adapts its max wait time +* Improve CopyFrom performance and reduce memory usage +* Fix: encode []any to array +* Fix: LoadType for composite with dropped attributes (Felix Röhrich) +* Support v4 and v5 stdlib in same program +* Fix: text format array decoding with string of "NULL" +* Prefer binary format for arrays + +# 5.2.0 (December 5, 2022) + +* `tracelog.TraceLog` implements the pgx.PrepareTracer interface. (Vitalii Solodilov) +* Optimize creating begin transaction SQL string (Petr Evdokimov and ksco) +* `Conn.LoadType` supports range and multirange types (Vitalii Solodilov) +* Fix scan `uint` and `uint64` `ScanNumeric`. This resolves a PostgreSQL `numeric` being incorrectly scanned into `uint` and `uint64`. + +# 5.1.1 (November 17, 2022) + +* Fix simple query sanitizer where query text contains a Unicode replacement character. +* Remove erroneous `name` argument from `DeallocateAll()`. Technically, this is a breaking change, but given that method was only added 5 days ago this change was accepted. (Bodo Kaiser) + +# 5.1.0 (November 12, 2022) + +* Update puddle to v2.1.2. This resolves a race condition and a deadlock in pgxpool. +* `QueryRewriter.RewriteQuery` now returns an error. Technically, this is a breaking change for any external implementers, but given the minimal likelihood that there are actually any external implementers this change was accepted. +* Expose `GetSSLPassword` support to pgx. +* Fix encode `ErrorResponse` unknown field handling. This would only affect pgproto3 being used directly as a proxy with a non-PostgreSQL server that included additional error fields. +* Fix date text format encoding with 5 digit years. +* Fix date values passed to a `sql.Scanner` as `string` instead of `time.Time`. +* DateCodec.DecodeValue can return `pgtype.InfinityModifier` instead of `string` for infinite values. This now matches the behavior of the timestamp types. +* Add domain type support to `Conn.LoadType()`. +* Add `RowToStructByName` and `RowToAddrOfStructByName`. (Pavlo Golub) +* Add `Conn.DeallocateAll()` to clear all prepared statements including the statement cache. (Bodo Kaiser) + +# 5.0.4 (October 24, 2022) + +* Fix: CollectOneRow prefers PostgreSQL error over pgx.ErrorNoRows +* Fix: some reflect Kind checks to first check for nil +* Bump golang.org/x/text dependency to placate snyk +* Fix: RowToStructByPos on structs with multiple anonymous sub-structs (Baptiste Fontaine) +* Fix: Exec checks if tx is closed + +# 5.0.3 (October 14, 2022) + +* Fix `driver.Valuer` handling edge cases that could cause infinite loop or crash + +# v5.0.2 (October 8, 2022) + +* Fix date encoding in text format to always use 2 digits for month and day +* Prefer driver.Valuer over wrap plans when encoding +* Fix scan to pointer to pointer to renamed type +* Allow scanning NULL even if PG and Go types are incompatible + +# v5.0.1 (September 24, 2022) + +* Fix 32-bit atomic usage +* Add MarshalJSON for Float8 (yogipristiawan) +* Add `[` and `]` to text encoding of `Lseg` +* Fix sqlScannerWrapper NULL handling + +# v5.0.0 (September 17, 2022) + +## Merged Packages + +`github.com/jackc/pgtype`, `github.com/jackc/pgconn`, and `github.com/jackc/pgproto3` are now included in the main +`github.com/jackc/pgx` repository. Previously there was confusion as to where issues should be reported, additional +release work due to releasing multiple packages, and less clear changelogs. + +## pgconn + +`CommandTag` is now an opaque type instead of directly exposing an underlying `[]byte`. + +The return value `ResultReader.Values()` is no longer safe to retain a reference to after a subsequent call to `NextRow()` or `Close()`. + +`Trace()` method adds low level message tracing similar to the `PQtrace` function in `libpq`. + +pgconn now uses non-blocking IO. This is a significant internal restructuring, but it should not cause any visible changes on its own. However, it is important in implementing other new features. + +`CheckConn()` checks a connection's liveness by doing a non-blocking read. This can be used to detect database restarts or network interruptions without executing a query or a ping. + +pgconn now supports pipeline mode. + +`*PgConn.ReceiveResults` removed. Use pipeline mode instead. + +`Timeout()` no longer considers `context.Canceled` as a timeout error. `context.DeadlineExceeded` still is considered a timeout error. + +## pgxpool + +`Connect` and `ConnectConfig` have been renamed to `New` and `NewWithConfig` respectively. The `LazyConnect` option has been removed. Pools always lazily connect. + +## pgtype + +The `pgtype` package has been significantly changed. + +### NULL Representation + +Previously, types had a `Status` field that could be `Undefined`, `Null`, or `Present`. This has been changed to a +`Valid` `bool` field to harmonize with how `database/sql` represents `NULL` and to make the zero value useable. + +Previously, a type that implemented `driver.Valuer` would have the `Value` method called even on a nil pointer. All nils +whether typed or untyped now represent `NULL`. + +### Codec and Value Split + +Previously, the type system combined decoding and encoding values with the value types. e.g. Type `Int8` both handled +encoding and decoding the PostgreSQL representation and acted as a value object. This caused some difficulties when +there was not an exact 1 to 1 relationship between the Go types and the PostgreSQL types For example, scanning a +PostgreSQL binary `numeric` into a Go `float64` was awkward (see https://github.com/jackc/pgtype/issues/147). This +concepts have been separated. A `Codec` only has responsibility for encoding and decoding values. Value types are +generally defined by implementing an interface that a particular `Codec` understands (e.g. `PointScanner` and +`PointValuer` for the PostgreSQL `point` type). + +### Array Types + +All array types are now handled by `ArrayCodec` instead of using code generation for each new array type. This also +means that less common array types such as `point[]` are now supported. `Array[T]` supports PostgreSQL multi-dimensional +arrays. + +### Composite Types + +Composite types must be registered before use. `CompositeFields` may still be used to construct and destruct composite +values, but any type may now implement `CompositeIndexGetter` and `CompositeIndexScanner` to be used as a composite. + +### Range Types + +Range types are now handled with types `RangeCodec` and `Range[T]`. This allows additional user defined range types to +easily be handled. Multirange types are handled similarly with `MultirangeCodec` and `Multirange[T]`. + +### pgxtype + +`LoadDataType` moved to `*Conn` as `LoadType`. + +### Bytea + +The `Bytea` and `GenericBinary` types have been replaced. Use the following instead: + +* `[]byte` - For normal usage directly use `[]byte`. +* `DriverBytes` - Uses driver memory only available until next database method call. Avoids a copy and an allocation. +* `PreallocBytes` - Uses preallocated byte slice to avoid an allocation. +* `UndecodedBytes` - Avoids any decoding. Allows working with raw bytes. + +### Dropped lib/pq Support + +`pgtype` previously supported and was tested against [lib/pq](https://github.com/lib/pq). While it will continue to work +in most cases this is no longer supported. + +### database/sql Scan + +Previously, most `Scan` implementations would convert `[]byte` to `string` automatically to decode a text value. Now +only `string` is handled. This is to allow the possibility of future binary support in `database/sql` mode by +considering `[]byte` to be binary format and `string` text format. This change should have no effect for any use with +`pgx`. The previous behavior was only necessary for `lib/pq` compatibility. + +Added `*Map.SQLScanner` to create a `sql.Scanner` for types such as `[]int32` and `Range[T]` that do not implement +`sql.Scanner` directly. + +### Number Type Fields Include Bit size + +`Int2`, `Int4`, `Int8`, `Float4`, `Float8`, and `Uint32` fields now include bit size. e.g. `Int` is renamed to `Int64`. +This matches the convention set by `database/sql`. In addition, for comparable types like `pgtype.Int8` and +`sql.NullInt64` the structures are identical. This means they can be directly converted one to another. + +### 3rd Party Type Integrations + +* Extracted integrations with https://github.com/shopspring/decimal and https://github.com/gofrs/uuid to + https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid respectively. This trims + the pgx dependency tree. + +### Other Changes + +* `Bit` and `Varbit` are both replaced by the `Bits` type. +* `CID`, `OID`, `OIDValue`, and `XID` are replaced by the `Uint32` type. +* `Hstore` is now defined as `map[string]*string`. +* `JSON` and `JSONB` types removed. Use `[]byte` or `string` directly. +* `QChar` type removed. Use `rune` or `byte` directly. +* `Inet` and `Cidr` types removed. Use `netip.Addr` and `netip.Prefix` directly. These types are more memory efficient than the previous `net.IPNet`. +* `Macaddr` type removed. Use `net.HardwareAddr` directly. +* Renamed `pgtype.ConnInfo` to `pgtype.Map`. +* Renamed `pgtype.DataType` to `pgtype.Type`. +* Renamed `pgtype.None` to `pgtype.Finite`. +* `RegisterType` now accepts a `*Type` instead of `Type`. +* Assorted array helper methods and types made private. + +## stdlib + +* Removed `AcquireConn` and `ReleaseConn` as that functionality has been built in since Go 1.13. + +## Reduced Memory Usage by Reusing Read Buffers + +Previously, the connection read buffer would allocate large chunks of memory and never reuse them. This allowed +transferring ownership to anything such as scanned values without incurring an additional allocation and memory copy. +However, this came at the cost of overall increased memory allocation size. But worse it was also possible to pin large +chunks of memory by retaining a reference to a small value that originally came directly from the read buffer. Now +ownership remains with the read buffer and anything needing to retain a value must make a copy. + +## Query Execution Modes + +Control over automatic prepared statement caching and simple protocol use are now combined into query execution mode. +See documentation for `QueryExecMode`. + +## QueryRewriter Interface and NamedArgs + +pgx now supports named arguments with the `NamedArgs` type. This is implemented via the new `QueryRewriter` interface which +allows arbitrary rewriting of query SQL and arguments. + +## RowScanner Interface + +The `RowScanner` interface allows a single argument to Rows.Scan to scan the entire row. + +## Rows Result Helpers + +* `CollectRows` and `RowTo*` functions simplify collecting results into a slice. +* `CollectOneRow` collects one row using `RowTo*` functions. +* `ForEachRow` simplifies scanning each row and executing code using the scanned values. `ForEachRow` replaces `QueryFunc`. + +## Tx Helpers + +Rather than every type that implemented `Begin` or `BeginTx` methods also needing to implement `BeginFunc` and +`BeginTxFunc` these methods have been converted to functions that take a db that implements `Begin` or `BeginTx`. + +## Improved Batch Query Ergonomics + +Previously, the code for building a batch went in one place before the call to `SendBatch`, and the code for reading the +results went in one place after the call to `SendBatch`. This could make it difficult to match up the query and the code +to handle the results. Now `Queue` returns a `QueuedQuery` which has methods `Query`, `QueryRow`, and `Exec` which can +be used to register a callback function that will handle the result. Callback functions are called automatically when +`BatchResults.Close` is called. + +## SendBatch Uses Pipeline Mode When Appropriate + +Previously, a batch with 10 unique parameterized statements executed 100 times would entail 11 network round trips. 1 +for each prepare / describe and 1 for executing them all. Now pipeline mode is used to prepare / describe all statements +in a single network round trip. So it would only take 2 round trips. + +## Tracing and Logging + +Internal logging support has been replaced with tracing hooks. This allows custom tracing integration with tools like OpenTelemetry. Package tracelog provides an adapter for pgx v4 loggers to act as a tracer. + +All integrations with 3rd party loggers have been extracted to separate repositories. This trims the pgx dependency +tree. diff --git a/vendor/github.com/jackc/pgx/v5/CLAUDE.md b/vendor/github.com/jackc/pgx/v5/CLAUDE.md new file mode 100644 index 0000000..71a8fc1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/CLAUDE.md @@ -0,0 +1,73 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +pgx is a PostgreSQL driver and toolkit for Go (`github.com/jackc/pgx/v5`). It provides both a native PostgreSQL interface and a `database/sql` compatible driver. Requires Go 1.25+ and supports PostgreSQL 14+ and CockroachDB. + +## Build & Test Commands + +```bash +# Run all tests (requires PGX_TEST_DATABASE to be set) +go test ./... + +# Run a specific test +go test -run TestFunctionName ./... + +# Run tests for a specific package +go test ./pgconn/... + +# Run tests with race detector +go test -race ./... + +# DevContainer: run tests against specific PostgreSQL versions +./test.sh pg18 # Default: PostgreSQL 18 +./test.sh pg16 -run TestConnect # Specific test against PG16 +./test.sh crdb # CockroachDB +./test.sh all # All targets (pg14-18 + crdb) + +# Format (always run after making changes) +goimports -w . + +# Lint +golangci-lint run ./... +``` + +## Test Database Setup + +Tests require `PGX_TEST_DATABASE` environment variable. In the devcontainer, `test.sh` handles this. For local development: + +```bash +export PGX_TEST_DATABASE="host=localhost user=postgres password=postgres dbname=pgx_test" +``` + +The test database needs extensions: `hstore`, `ltree`, and a `uint64` domain. See `testsetup/postgresql_setup.sql` for full setup. Many tests are skipped unless additional `PGX_TEST_*` env vars are set (for TLS, SCRAM, MD5, unix socket, PgBouncer testing). + +## Architecture + +The codebase is a layered architecture, bottom-up: + +- **pgproto3/** — PostgreSQL wire protocol v3 encoder/decoder. Defines `FrontendMessage` and `BackendMessage` types for every protocol message. +- **pgconn/** — Low-level connection layer (roughly libpq-equivalent). Handles authentication, TLS, query execution, COPY protocol, and notifications. `PgConn` is the core type. +- **pgx** (root package) — High-level query interface built on `pgconn`. Provides `Conn`, `Rows`, `Tx`, `Batch`, `CopyFrom`, and generic helpers like `CollectRows`/`ForEachRow`. Includes automatic statement caching (LRU). +- **pgtype/** — Type system mapping between Go and PostgreSQL types (70+ types). Key interfaces: `Codec`, `Type`, `TypeMap`. Custom types (enums, composites, domains) are registered through `TypeMap`. +- **pgxpool/** — Concurrency-safe connection pool built on `puddle/v2`. `Pool` is the main type; wraps `pgx.Conn`. +- **stdlib/** — `database/sql` compatibility adapter. + +Supporting packages: +- **internal/stmtcache/** — Prepared statement cache with LRU eviction +- **internal/sanitize/** — SQL query sanitization +- **tracelog/** — Logging adapter that implements tracer interfaces +- **multitracer/** — Composes multiple tracers into one +- **pgxtest/** — Test helpers for running tests across connection types + +## Key Design Conventions + +- **Semantic versioning** — strictly followed. Do not break the public API (no removing or renaming exported types, functions, methods, or fields; no changing function signatures). +- **Minimal dependencies** — adding new dependencies is strongly discouraged (see CONTRIBUTING.md). +- **Context-based** — all blocking operations take `context.Context`. +- **Tracer interfaces** — observability via `QueryTracer`, `BatchTracer`, `CopyFromTracer`, `PrepareTracer` on `ConnConfig.Tracer`. +- **Formatting** — always run `goimports -w .` after making changes to ensure code is properly formatted. CI checks formatting via `gofmt -l -s -w . && git diff --exit-code`. `gofumpt` with extra rules is also enforced via `golangci-lint`. +- **Linters** — `govet`, `ineffassign`, and `unconvert` only (configured in `.golangci.yml`). +- **CI matrix** — tests run against Go 1.25/1.26 × PostgreSQL 14-18 + CockroachDB, on Linux and Windows. Race detector enabled on Linux only. diff --git a/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md new file mode 100644 index 0000000..2283ae6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/CONTRIBUTING.md @@ -0,0 +1,139 @@ +# Contributing + +## Discuss Significant Changes + +Before you invest a significant amount of time on a change, please create a discussion or issue describing your +proposal. This will help to ensure your proposed change has a reasonable chance of being merged. + +## Avoid Dependencies + +Adding a dependency is a big deal. While on occasion a new dependency may be accepted, the default answer to any change +that adds a dependency is no. + +## AI + +Using AI is acceptable (not that it can really be stopped) under one the following conditions. + +* AI was used, but you deeply understand the code and you can answer questions regarding your change. You are not going + to answer questions with "I don't know", AI did it. You are not going to "answer" questions by relaying them to your + agent. This is wasteful of the code reviewer's time. +* AI was used to solve a problem without your deep understanding. This can still be a good starting point for a fix or + feature. But you need to clearly state that this is an AI proposal. You should include additional information such as + the AI used and what prompts were used. You should also be aware that large, complicated, or subtle changes may be + rejected simply because the reviewer is not confident in a change that no human understands. + +## Development Environment Setup + +pgx tests naturally require a PostgreSQL database. It will connect to the database specified in the `PGX_TEST_DATABASE` +environment variable. The `PGX_TEST_DATABASE` environment variable can either be a URL or key-value pairs. In addition, +the standard `PG*` environment variables will be respected. Consider using [direnv](https://github.com/direnv/direnv) to +simplify environment variable handling. + +### Devcontainer + +The easiest way to start development is with the included devcontainer. It includes containers for each supported +PostgreSQL version as well as CockroachDB. `./test.sh all` will run the tests against all database types. + +### Using an Existing PostgreSQL Cluster Outside of a Devcontainer + +If you already have a PostgreSQL development server this is the quickest way to start and run the majority of the pgx +test suite. Some tests will be skipped that require server configuration changes (e.g. those testing different +authentication methods). + +Create and setup a test database: + +``` +export PGDATABASE=pgx_test +createdb +psql -c 'create extension hstore;' +psql -c 'create extension ltree;' +psql -c 'create domain uint64 as numeric(20,0);' +``` + +Ensure a `postgres` user exists. This happens by default in normal PostgreSQL installs, but some installation methods +such as Homebrew do not. + +``` +createuser -s postgres +``` + +Ensure your `PGX_TEST_DATABASE` environment variable points to the database you just created and run the tests. + +``` +export PGX_TEST_DATABASE="host=/private/tmp database=pgx_test" +go test ./... +``` + +This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing different connection methods). + +### Creating a New PostgreSQL Cluster Exclusively for Testing Outside of a Devcontainer + +The following environment variables need to be set both for initial setup and whenever the tests are run. (direnv is +highly recommended). Depending on your platform, you may need to change the host for `PGX_TEST_UNIX_SOCKET_CONN_STRING`. + +``` +export PGPORT=5015 +export PGUSER=postgres +export PGDATABASE=pgx_test +export POSTGRESQL_DATA_DIR=postgresql + +export PGX_TEST_DATABASE="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" +export PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/private/tmp database=pgx_test" +export PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" +export PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_scram password=secret database=pgx_test channel_binding=disable" +export PGX_TEST_SCRAM_PLUS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test channel_binding=require" +export PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 database=pgx_test user=pgx_md5 password=secret" +export PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 user=pgx_pw password=secret" +export PGX_TEST_TLS_CONN_STRING="host=localhost user=pgx_ssl password=secret sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem channel_binding=disable" +export PGX_SSL_PASSWORD=certpw +export PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost user=pgx_sslcert sslmode=verify-full sslrootcert=`pwd`/.testdb/ca.pem database=pgx_test sslcert=`pwd`/.testdb/pgx_sslcert.crt sslkey=`pwd`/.testdb/pgx_sslcert.key" +``` + +Create a new database cluster. + +``` +initdb --locale=en_US -E UTF-8 --username=postgres .testdb/$POSTGRESQL_DATA_DIR + +echo "listen_addresses = '127.0.0.1'" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf +echo "port = $PGPORT" >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf +cat testsetup/postgresql_ssl.conf >> .testdb/$POSTGRESQL_DATA_DIR/postgresql.conf +cp testsetup/pg_hba.conf .testdb/$POSTGRESQL_DATA_DIR/pg_hba.conf + +cd .testdb + +# Generate CA, server, and encrypted client certificates. +go run ../testsetup/generate_certs.go + +# Copy certificates to server directory and set permissions. +cp ca.pem $POSTGRESQL_DATA_DIR/root.crt +cp localhost.key $POSTGRESQL_DATA_DIR/server.key +chmod 600 $POSTGRESQL_DATA_DIR/server.key +cp localhost.crt $POSTGRESQL_DATA_DIR/server.crt + +cd .. +``` + + +Start the new cluster. This will be necessary whenever you are running pgx tests. + +``` +postgres -D .testdb/$POSTGRESQL_DATA_DIR +``` + +Setup the test database in the new cluster. + +``` +createdb +psql --no-psqlrc -f testsetup/postgresql_setup.sql +``` + +### PgBouncer + +There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set. + +### Optional Tests + +pgx supports multiple connection types and means of authentication. These tests are optional. They will only run if the +appropriate environment variables are set. In addition, there may be tests specific to particular PostgreSQL versions, +non-PostgreSQL servers (e.g. CockroachDB), or connection poolers (e.g. PgBouncer). `go test ./... -v | grep SKIP` to see +if any tests are being skipped. diff --git a/vendor/github.com/jackc/pgx/v5/LICENSE b/vendor/github.com/jackc/pgx/v5/LICENSE new file mode 100644 index 0000000..5c486c3 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2013-2021 Jack Christensen + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/pgx/v5/README.md b/vendor/github.com/jackc/pgx/v5/README.md new file mode 100644 index 0000000..aa35e4a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/README.md @@ -0,0 +1,192 @@ +[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/pgx/v5.svg)](https://pkg.go.dev/github.com/jackc/pgx/v5) +[![Build Status](https://github.com/jackc/pgx/actions/workflows/ci.yml/badge.svg)](https://github.com/jackc/pgx/actions/workflows/ci.yml) + +# pgx - PostgreSQL Driver and Toolkit + +pgx is a pure Go driver and toolkit for PostgreSQL. + +The pgx driver is a low-level, high performance interface that exposes PostgreSQL-specific features such as `LISTEN` / +`NOTIFY` and `COPY`. It also includes an adapter for the standard `database/sql` interface. + +The toolkit component is a related set of packages that implement PostgreSQL functionality such as parsing the wire protocol +and type mapping between PostgreSQL and Go. These underlying packages can be used to implement alternative drivers, +proxies, load balancers, logical replication clients, etc. + +## Example Usage + +```go +package main + +import ( + "context" + "fmt" + "os" + + "github.com/jackc/pgx/v5" +) + +func main() { + // urlExample := "postgres://username:password@localhost:5432/database_name" + conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) + if err != nil { + fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err) + os.Exit(1) + } + defer conn.Close(context.Background()) + + var name string + var weight int64 + err = conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight) + if err != nil { + fmt.Fprintf(os.Stderr, "QueryRow failed: %v\n", err) + os.Exit(1) + } + + fmt.Println(name, weight) +} +``` + +See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information. + +## Features + +* Support for approximately 70 different PostgreSQL types +* Automatic statement preparation and caching +* Batch queries +* Single-round trip query mode +* Full TLS connection control +* Binary format support for custom types (allows for much quicker encoding/decoding) +* `COPY` protocol support for faster bulk data loads +* Tracing and logging support +* Connection pool with after-connect hook for arbitrary connection setup +* `LISTEN` / `NOTIFY` +* Conversion of PostgreSQL arrays to Go slice mappings for integers, floats, and strings +* `hstore` support +* `json` and `jsonb` support +* Maps `inet` and `cidr` PostgreSQL types to `netip.Addr` and `netip.Prefix` +* Large object support +* NULL mapping to pointer to pointer +* Supports `database/sql.Scanner` and `database/sql/driver.Valuer` interfaces for custom types +* Notice response handling +* Simulated nested transactions with savepoints + +## Choosing Between the pgx and database/sql Interfaces + +The pgx interface is faster. Many PostgreSQL specific features such as `LISTEN` / `NOTIFY` and `COPY` are not available +through the `database/sql` interface. + +The pgx interface is recommended when: + +1. The application only targets PostgreSQL. +2. No other libraries that require `database/sql` are in use. + +It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed. + +## Testing + +See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions. + +## Architecture + +See the presentation at Golang Estonia, [PGX Top to Bottom](https://www.youtube.com/watch?v=sXMSWhcHCf8) for a description of pgx architecture. + +## Supported Go and PostgreSQL Versions + +pgx supports the same versions of Go and PostgreSQL that are supported by their respective teams. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases and for [PostgreSQL](https://www.postgresql.org/support/versioning/) the major releases in the last 5 years. This means pgx supports Go 1.25 and higher and PostgreSQL 14 and higher. pgx also is tested against the latest version of [CockroachDB](https://www.cockroachlabs.com/product/). + +## Version Policy + +pgx follows semantic versioning for the documented public API on stable releases. `v5` is the latest stable major version. + +## PGX Family Libraries + +### [github.com/jackc/pglogrepl](https://github.com/jackc/pglogrepl) + +pglogrepl provides functionality to act as a client for PostgreSQL logical replication. + +### [github.com/jackc/pgmock](https://github.com/jackc/pgmock) + +pgmock offers the ability to create a server that mocks the PostgreSQL wire protocol. This is used internally to test pgx by purposely inducing unusual errors. pgproto3 and pgmock together provide most of the foundational tooling required to implement a PostgreSQL proxy or MitM (such as for a custom connection pooler). + +### [github.com/jackc/tern](https://github.com/jackc/tern) + +tern is a stand-alone SQL migration system. + +### [github.com/jackc/pgerrcode](https://github.com/jackc/pgerrcode) + +pgerrcode contains constants for the PostgreSQL error codes. + +## Adapters for 3rd Party Types + +* [github.com/jackc/pgx-gofrs-uuid](https://github.com/jackc/pgx-gofrs-uuid) +* [github.com/jackc/pgx-shopspring-decimal](https://github.com/jackc/pgx-shopspring-decimal) +* [github.com/ColeBurch/pgx-govalues-decimal](https://github.com/ColeBurch/pgx-govalues-decimal) +* [github.com/twpayne/pgx-geos](https://github.com/twpayne/pgx-geos) ([PostGIS](https://postgis.net/) and [GEOS](https://libgeos.org/) via [go-geos](https://github.com/twpayne/go-geos)) +* [github.com/vgarvardt/pgx-google-uuid](https://github.com/vgarvardt/pgx-google-uuid) + + +## Adapters for 3rd Party Tracers + +* [github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer) +* [github.com/exaring/otelpgx](https://github.com/exaring/otelpgx) + +## Adapters for 3rd Party Loggers + +These adapters can be used with the tracelog package. + +* [github.com/jackc/pgx-go-kit-log](https://github.com/jackc/pgx-go-kit-log) +* [github.com/jackc/pgx-log15](https://github.com/jackc/pgx-log15) +* [github.com/jackc/pgx-logrus](https://github.com/jackc/pgx-logrus) +* [github.com/jackc/pgx-zap](https://github.com/jackc/pgx-zap) +* [github.com/jackc/pgx-zerolog](https://github.com/jackc/pgx-zerolog) +* [github.com/mcosta74/pgx-slog](https://github.com/mcosta74/pgx-slog) +* [github.com/kataras/pgx-golog](https://github.com/kataras/pgx-golog) + +## 3rd Party Libraries with PGX Support + +### [github.com/pashagolub/pgxmock](https://github.com/pashagolub/pgxmock) + +pgxmock is a mock library implementing pgx interfaces. +pgxmock has one and only purpose - to simulate pgx behavior in tests, without needing a real database connection. + +### [github.com/georgysavva/scany](https://github.com/georgysavva/scany) + +Library for scanning data from a database into Go structs and more. + +### [github.com/vingarcia/ksql](https://github.com/vingarcia/ksql) + +A carefully designed SQL client for making using SQL easier, +more productive, and less error-prone on Golang. + +### [github.com/otan/gopgkrb5](https://github.com/otan/gopgkrb5) + +Adds GSSAPI / Kerberos authentication support. + +### [github.com/wcamarao/pmx](https://github.com/wcamarao/pmx) + +Explicit data mapping and scanning library for Go structs and slices. + +### [github.com/stephenafamo/scan](https://github.com/stephenafamo/scan) + +Type safe and flexible package for scanning database data into Go types. +Supports, structs, maps, slices and custom mapping functions. + +### [github.com/z0ne-dev/mgx](https://github.com/z0ne-dev/mgx) + +Code first migration library for native pgx (no database/sql abstraction). + +### [github.com/amirsalarsafaei/sqlc-pgx-monitoring](https://github.com/amirsalarsafaei/sqlc-pgx-monitoring) + +A database monitoring/metrics library for pgx and sqlc. Trace, log and monitor your sqlc query performance using OpenTelemetry. + +### [https://github.com/nikolayk812/pgx-outbox](https://github.com/nikolayk812/pgx-outbox) + +Simple Golang implementation for transactional outbox pattern for PostgreSQL using jackc/pgx driver. + +### [https://github.com/Arlandaren/pgxWrappy](https://github.com/Arlandaren/pgxWrappy) + +Simplifies working with the pgx library, providing convenient scanning of nested structures. + +### [https://github.com/KoNekoD/pgx-colon-query-rewriter](https://github.com/KoNekoD/pgx-colon-query-rewriter) + +Implementation of the pgx query rewriter to use ':' instead of '@' in named query parameters. diff --git a/vendor/github.com/jackc/pgx/v5/Rakefile b/vendor/github.com/jackc/pgx/v5/Rakefile new file mode 100644 index 0000000..3e3aa50 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/Rakefile @@ -0,0 +1,18 @@ +require "erb" + +rule '.go' => '.go.erb' do |task| + erb = ERB.new(File.read(task.source)) + File.write(task.name, "// Code generated from #{task.source}. DO NOT EDIT.\n\n" + erb.result(binding)) + sh "goimports", "-w", task.name +end + +generated_code_files = [ + "pgtype/int.go", + "pgtype/int_test.go", + "pgtype/integration_benchmark_test.go", + "pgtype/zeronull/int.go", + "pgtype/zeronull/int_test.go" +] + +desc "Generate code" +task generate: generated_code_files diff --git a/vendor/github.com/jackc/pgx/v5/batch.go b/vendor/github.com/jackc/pgx/v5/batch.go new file mode 100644 index 0000000..805cc39 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/batch.go @@ -0,0 +1,537 @@ +package pgx + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5/pgconn" +) + +// QueuedQuery is a query that has been queued for execution via a [Batch]. +type QueuedQuery struct { + SQL string + Arguments []any + Fn batchItemFunc + sd *pgconn.StatementDescription +} + +type batchItemFunc func(br BatchResults) error + +// Query sets fn to be called when the response to qq is received. +func (qq *QueuedQuery) Query(fn func(rows Rows) error) { + qq.Fn = func(br BatchResults) error { + rows, _ := br.Query() + defer rows.Close() + + err := fn(rows) + if err != nil { + return err + } + rows.Close() + + return rows.Err() + } +} + +// Query sets fn to be called when the response to qq is received. +func (qq *QueuedQuery) QueryRow(fn func(row Row) error) { + qq.Fn = func(br BatchResults) error { + row := br.QueryRow() + return fn(row) + } +} + +// Exec sets fn to be called when the response to qq is received. +// +// Note: for simple batch insert uses where it is not required to handle +// each potential error individually, it's sufficient to not set any callbacks, +// and just handle the return value of [BatchResults.Close]. +func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) { + qq.Fn = func(br BatchResults) error { + ct, err := br.Exec() + if err != nil { + return err + } + + return fn(ct) + } +} + +// Batch queries are a way of bundling multiple queries together to avoid +// unnecessary network round trips. A Batch must only be sent once. +type Batch struct { + QueuedQueries []*QueuedQuery +} + +// Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option +// argument that is supported is [QueryRewriter]. Queries are executed using the connection's DefaultQueryExecMode +// (see [ConnConfig.DefaultQueryExecMode]). +// +// While query can contain multiple statements if the connection's DefaultQueryExecMode is [QueryExecModeSimpleProtocol], +// this should be avoided. QueuedQuery.Fn must not be set as it will only be called for the first query. That is, +// [QueuedQuery.Query], [QueuedQuery.QueryRow], and [QueuedQuery.Exec] must not be called. In addition, any error +// messages or tracing that include the current query may reference the wrong query. +func (b *Batch) Queue(query string, arguments ...any) *QueuedQuery { + qq := &QueuedQuery{ + SQL: query, + Arguments: arguments, + } + b.QueuedQueries = append(b.QueuedQueries, qq) + return qq +} + +// Len returns number of queries that have been queued so far. +func (b *Batch) Len() int { + return len(b.QueuedQueries) +} + +type BatchResults interface { + // Exec reads the results from the next query in the batch as if the query has been sent with [Conn.Exec]. Prefer + // calling Exec on the QueuedQuery, or just calling Close. + Exec() (pgconn.CommandTag, error) + + // Query reads the results from the next query in the batch as if the query has been sent with [Conn.Query]. Prefer + // calling [QueuedQuery.Query]. + Query() (Rows, error) + + // QueryRow reads the results from the next query in the batch as if the query has been sent with [Conn.QueryRow]. + // Prefer calling [QueuedQuery.QueryRow]. + QueryRow() Row + + // Close closes the batch operation. All unread results are read and any callback functions registered with + // [QueuedQuery.Query], [QueuedQuery.QueryRow], or [QueuedQuery.Exec] will be called. If a callback function returns an + // error or the batch encounters an error subsequent callback functions will not be called. + // + // For simple batch inserts inside a transaction or similar queries, it's sufficient to not set any callbacks, + // and just handle the return value of Close. + // + // Close must be called before the underlying connection can be used again. Any error that occurred during a batch + // operation may have made it impossible to resyncronize the connection with the server. In this case the underlying + // connection will have been closed. + // + // Close is safe to call multiple times. If it returns an error subsequent calls will return the same error. Callback + // functions will not be rerun. + Close() error +} + +type batchResults struct { + ctx context.Context + conn *Conn + mrr *pgconn.MultiResultReader + err error + b *Batch + qqIdx int + closed bool + endTraced bool +} + +// Exec reads the results from the next query in the batch as if the query has been sent with Exec. +func (br *batchResults) Exec() (pgconn.CommandTag, error) { + if br.err != nil { + return pgconn.CommandTag{}, br.err + } + if br.closed { + return pgconn.CommandTag{}, fmt.Errorf("batch already closed") + } + + query, arguments, _ := br.nextQueryAndArgs() + + if !br.mrr.NextResult() { + err := br.mrr.Close() + if err == nil { + err = errors.New("no more results in batch") + } + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + Err: err, + }) + } + return pgconn.CommandTag{}, err + } + + commandTag, err := br.mrr.ResultReader().Close() + if err != nil { + br.err = err + br.mrr.Close() + } + + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + CommandTag: commandTag, + Err: br.err, + }) + } + + return commandTag, br.err +} + +// Query reads the results from the next query in the batch as if the query has been sent with Query. +func (br *batchResults) Query() (Rows, error) { + query, arguments, ok := br.nextQueryAndArgs() + if !ok { + query = "batch query" + } + + if br.err != nil { + return &baseRows{err: br.err, closed: true}, br.err + } + + if br.closed { + alreadyClosedErr := fmt.Errorf("batch already closed") + return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr + } + + rows := br.conn.getRows(br.ctx, query, arguments) + rows.batchTracer = br.conn.batchTracer + + if !br.mrr.NextResult() { + rows.err = br.mrr.Close() + if rows.err == nil { + rows.err = errors.New("no more results in batch") + } + rows.closed = true + + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + Err: rows.err, + }) + } + + return rows, rows.err + } + + rows.resultReader = br.mrr.ResultReader() + return rows, nil +} + +// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow. +func (br *batchResults) QueryRow() Row { + rows, _ := br.Query() + return (*connRow)(rows.(*baseRows)) +} + +// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to +// resyncronize the connection with the server. In this case the underlying connection will have been closed. +func (br *batchResults) Close() error { + defer func() { + if !br.endTraced { + if br.conn != nil && br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err}) + } + br.endTraced = true + } + + invalidateCachesOnBatchResultsError(br.conn, br.b, br.err) + }() + + if br.err != nil { + return br.err + } + + if br.closed { + return nil + } + + // Read and run fn for all remaining items + for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + if br.b.QueuedQueries[br.qqIdx].Fn != nil { + err := br.b.QueuedQueries[br.qqIdx].Fn(br) + if err != nil { + br.err = err + } + } else { + br.Exec() + } + } + + br.closed = true + + err := br.mrr.Close() + if br.err == nil { + br.err = err + } + + return br.err +} + +func (br *batchResults) earlyError() error { + return br.err +} + +func (br *batchResults) nextQueryAndArgs() (query string, args []any, ok bool) { + if br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + bi := br.b.QueuedQueries[br.qqIdx] + query = bi.SQL + args = bi.Arguments + ok = true + br.qqIdx++ + } + return query, args, ok +} + +type pipelineBatchResults struct { + ctx context.Context + conn *Conn + pipeline *pgconn.Pipeline + lastRows *baseRows + err error + b *Batch + qqIdx int + closed bool + endTraced bool +} + +// Exec reads the results from the next query in the batch as if the query has been sent with Exec. +func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) { + if br.err != nil { + return pgconn.CommandTag{}, br.err + } + if br.closed { + return pgconn.CommandTag{}, fmt.Errorf("batch already closed") + } + if br.lastRows != nil && br.lastRows.err != nil { + br.err = br.lastRows.err + return pgconn.CommandTag{}, br.err + } + + query, arguments, err := br.nextQueryAndArgs() + if err != nil { + return pgconn.CommandTag{}, err + } + + results, err := br.pipeline.GetResults() + if err != nil { + br.err = err + return pgconn.CommandTag{}, br.err + } + var commandTag pgconn.CommandTag + switch results := results.(type) { + case *pgconn.ResultReader: + commandTag, br.err = results.Close() + default: + return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results) + } + + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + CommandTag: commandTag, + Err: br.err, + }) + } + + return commandTag, br.err +} + +// Query reads the results from the next query in the batch as if the query has been sent with Query. +func (br *pipelineBatchResults) Query() (Rows, error) { + if br.err != nil { + return &baseRows{err: br.err, closed: true}, br.err + } + + if br.closed { + alreadyClosedErr := fmt.Errorf("batch already closed") + return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr + } + + if br.lastRows != nil && br.lastRows.err != nil { + br.err = br.lastRows.err + return &baseRows{err: br.err, closed: true}, br.err + } + + query, arguments, err := br.nextQueryAndArgs() + if err != nil { + return &baseRows{err: err, closed: true}, err + } + + rows := br.conn.getRows(br.ctx, query, arguments) + rows.batchTracer = br.conn.batchTracer + br.lastRows = rows + + results, err := br.pipeline.GetResults() + if err != nil { + br.err = err + rows.err = err + rows.closed = true + + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{ + SQL: query, + Args: arguments, + Err: err, + }) + } + } else { + switch results := results.(type) { + case *pgconn.ResultReader: + rows.resultReader = results + default: + err = fmt.Errorf("unexpected pipeline result: %T", results) + br.err = err + rows.err = err + rows.closed = true + } + } + + return rows, rows.err +} + +// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow. +func (br *pipelineBatchResults) QueryRow() Row { + rows, _ := br.Query() + return (*connRow)(rows.(*baseRows)) +} + +// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to +// resyncronize the connection with the server. In this case the underlying connection will have been closed. +func (br *pipelineBatchResults) Close() error { + defer func() { + if !br.endTraced { + if br.conn.batchTracer != nil { + br.conn.batchTracer.TraceBatchEnd(br.ctx, br.conn, TraceBatchEndData{Err: br.err}) + } + br.endTraced = true + } + + invalidateCachesOnBatchResultsError(br.conn, br.b, br.err) + }() + + if br.err == nil && br.lastRows != nil && br.lastRows.err != nil { + br.err = br.lastRows.err + } + + if br.closed { + return br.err + } + + // Read and run fn for all remaining items + for br.err == nil && !br.closed && br.b != nil && br.qqIdx < len(br.b.QueuedQueries) { + if br.b.QueuedQueries[br.qqIdx].Fn != nil { + err := br.b.QueuedQueries[br.qqIdx].Fn(br) + if err != nil { + br.err = err + } + } else { + br.Exec() + } + } + + br.closed = true + + err := br.pipeline.Close() + if br.err == nil { + br.err = err + } + + return br.err +} + +func (br *pipelineBatchResults) earlyError() error { + return br.err +} + +func (br *pipelineBatchResults) nextQueryAndArgs() (query string, args []any, err error) { + if br.b == nil { + return "", nil, errors.New("no reference to batch") + } + + if br.qqIdx >= len(br.b.QueuedQueries) { + return "", nil, errors.New("no more results in batch") + } + + bi := br.b.QueuedQueries[br.qqIdx] + br.qqIdx++ + return bi.SQL, bi.Arguments, nil +} + +type emptyBatchResults struct { + conn *Conn + closed bool +} + +// Exec reads the results from the next query in the batch as if the query has been sent with Exec. +func (br *emptyBatchResults) Exec() (pgconn.CommandTag, error) { + if br.closed { + return pgconn.CommandTag{}, fmt.Errorf("batch already closed") + } + return pgconn.CommandTag{}, errors.New("no more results in batch") +} + +// Query reads the results from the next query in the batch as if the query has been sent with Query. +func (br *emptyBatchResults) Query() (Rows, error) { + if br.closed { + alreadyClosedErr := fmt.Errorf("batch already closed") + return &baseRows{err: alreadyClosedErr, closed: true}, alreadyClosedErr + } + + rows := br.conn.getRows(context.Background(), "", nil) + rows.err = errors.New("no more results in batch") + rows.closed = true + return rows, rows.err +} + +// QueryRow reads the results from the next query in the batch as if the query has been sent with QueryRow. +func (br *emptyBatchResults) QueryRow() Row { + rows, _ := br.Query() + return (*connRow)(rows.(*baseRows)) +} + +// Close closes the batch operation. Any error that occurred during a batch operation may have made it impossible to +// resyncronize the connection with the server. In this case the underlying connection will have been closed. +func (br *emptyBatchResults) Close() error { + br.closed = true + return nil +} + +// invalidates statement and description caches on batch results error +func invalidateCachesOnBatchResultsError(conn *Conn, b *Batch, err error) { + if err != nil && conn != nil && b != nil { + if sc := conn.statementCache; sc != nil { + for _, bi := range b.QueuedQueries { + sc.Invalidate(bi.SQL) + } + } + + if sc := conn.descriptionCache; sc != nil { + for _, bi := range b.QueuedQueries { + sc.Invalidate(bi.SQL) + } + } + } +} + +// ErrPreprocessingBatch occurs when an error is encountered while preprocessing a batch. +// The two preprocessing steps are "prepare" (server-side SQL parse/plan) and +// "build" (client-side argument encoding). +type ErrPreprocessingBatch struct { + step string // "prepare" or "build" + sql string + err error +} + +func newErrPreprocessingBatch(step, sql string, err error) ErrPreprocessingBatch { + return ErrPreprocessingBatch{step: step, sql: sql, err: err} +} + +func (e ErrPreprocessingBatch) Error() string { + // intentionally not including the SQL query in the error message + // to avoid leaking potentially sensitive information into logs. + // If the user wants the SQL, they can call SQL(). + return fmt.Sprintf("error preprocessing batch (%s): %v", e.step, e.err) +} + +func (e ErrPreprocessingBatch) Unwrap() error { + return e.err +} + +func (e ErrPreprocessingBatch) SQL() string { + return e.sql +} diff --git a/vendor/github.com/jackc/pgx/v5/conn.go b/vendor/github.com/jackc/pgx/v5/conn.go new file mode 100644 index 0000000..bc5d064 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/conn.go @@ -0,0 +1,1472 @@ +package pgx + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/jackc/pgx/v5/internal/sanitize" + "github.com/jackc/pgx/v5/internal/stmtcache" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" +) + +// ConnConfig contains all the options used to establish a connection. It must be created by [ParseConfig] and +// then it can be modified. A manually initialized ConnConfig will cause [ConnectConfig] to panic. +type ConnConfig struct { + pgconn.Config + + Tracer QueryTracer + + // Original connection string that was parsed into config. + connString string + + // StatementCacheCapacity is maximum size of the statement cache used when executing a query with "cache_statement" + // query exec mode. + StatementCacheCapacity int + + // DescriptionCacheCapacity is the maximum size of the description cache used when executing a query with + // "cache_describe" query exec mode. + DescriptionCacheCapacity int + + // DefaultQueryExecMode controls the default mode for executing queries. By default pgx uses the extended protocol + // and automatically prepares and caches prepared statements. However, this may be incompatible with proxies such as + // PGBouncer. In this case it may be preferable to use [QueryExecModeExec] or [QueryExecModeSimpleProtocol]. The same + // functionality can be controlled on a per query basis by passing a [QueryExecMode] as the first query argument. + DefaultQueryExecMode QueryExecMode + + createdByParseConfig bool // Used to enforce created by ParseConfig rule. +} + +// ParseConfigOptions contains options that control how a config is built such as getsslpassword. +type ParseConfigOptions struct { + pgconn.ParseConfigOptions +} + +// Copy returns a deep copy of the config that is safe to use and modify. +// The only exception is the tls.Config: +// according to the tls.Config docs it must not be modified after creation. +func (cc *ConnConfig) Copy() *ConnConfig { + newConfig := new(ConnConfig) + *newConfig = *cc + newConfig.Config = *newConfig.Config.Copy() + return newConfig +} + +// ConnString returns the connection string as parsed by pgx.ParseConfig into pgx.ConnConfig. +func (cc *ConnConfig) ConnString() string { return cc.connString } + +// Conn is a PostgreSQL connection handle. It is not safe for concurrent usage. Use a connection pool to manage access +// to multiple database connections from multiple goroutines. +type Conn struct { + pgConn *pgconn.PgConn + config *ConnConfig // config used when establishing this connection + preparedStatements map[string]*pgconn.StatementDescription + failedDescribeStatement string + statementCache stmtcache.Cache + descriptionCache stmtcache.Cache + + queryTracer QueryTracer + batchTracer BatchTracer + copyFromTracer CopyFromTracer + prepareTracer PrepareTracer + + notifications []*pgconn.Notification + + doneChan chan struct{} + closedChan chan error + + typeMap *pgtype.Map + + wbuf []byte + eqb ExtendedQueryBuilder +} + +// Identifier a PostgreSQL identifier or name. Identifiers can be composed of +// multiple parts such as ["schema", "table"] or ["table", "column"]. +type Identifier []string + +// Sanitize returns a sanitized string safe for SQL interpolation. +func (ident Identifier) Sanitize() string { + parts := make([]string, len(ident)) + for i := range ident { + s := strings.ReplaceAll(ident[i], string([]byte{0}), "") + parts[i] = `"` + strings.ReplaceAll(s, `"`, `""`) + `"` + } + return strings.Join(parts, ".") +} + +var ( + // ErrNoRows occurs when rows are expected but none are returned. + ErrNoRows = newProxyErr(sql.ErrNoRows, "no rows in result set") + // ErrTooManyRows occurs when more rows than expected are returned. + ErrTooManyRows = errors.New("too many rows in result set") +) + +func newProxyErr(background error, msg string) error { + return &proxyError{ + msg: msg, + background: background, + } +} + +type proxyError struct { + msg string + background error +} + +func (err *proxyError) Error() string { return err.msg } + +func (err *proxyError) Unwrap() error { return err.background } + +var ( + errDisabledStatementCache = fmt.Errorf("cannot use QueryExecModeCacheStatement with disabled statement cache") + errDisabledDescriptionCache = fmt.Errorf("cannot use QueryExecModeCacheDescribe with disabled description cache") +) + +// Connect establishes a connection with a PostgreSQL server with a connection string. See +// [pgconn.Connect] for details. +func Connect(ctx context.Context, connString string) (*Conn, error) { + connConfig, err := ParseConfig(connString) + if err != nil { + return nil, err + } + return connect(ctx, connConfig) +} + +// ConnectWithOptions behaves exactly like Connect with the addition of options. At the present options is only used to +// provide a [pgconn.GetSSLPasswordFunc] function. +func ConnectWithOptions(ctx context.Context, connString string, options ParseConfigOptions) (*Conn, error) { + connConfig, err := ParseConfigWithOptions(connString, options) + if err != nil { + return nil, err + } + return connect(ctx, connConfig) +} + +// ConnectConfig establishes a connection with a PostgreSQL server with a configuration struct. +// connConfig must have been created by [ParseConfig]. +func ConnectConfig(ctx context.Context, connConfig *ConnConfig) (*Conn, error) { + // In general this improves safety. In particular avoid the config.Config.OnNotification mutation from affecting other + // connections with the same config. See https://github.com/jackc/pgx/issues/618. + connConfig = connConfig.Copy() + + return connect(ctx, connConfig) +} + +// ParseConfigWithOptions behaves exactly as [ParseConfig] does with the addition of options. At the present options is +// only used to provide a [pgconn.GetSSLPasswordFunc] function. +func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*ConnConfig, error) { + config, err := pgconn.ParseConfigWithOptions(connString, options.ParseConfigOptions) + if err != nil { + return nil, err + } + + statementCacheCapacity := 512 + if s, ok := config.RuntimeParams["statement_cache_capacity"]; ok { + delete(config.RuntimeParams, "statement_cache_capacity") + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse statement_cache_capacity", err) + } + statementCacheCapacity = int(n) + } + + descriptionCacheCapacity := 512 + if s, ok := config.RuntimeParams["description_cache_capacity"]; ok { + delete(config.RuntimeParams, "description_cache_capacity") + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse description_cache_capacity", err) + } + descriptionCacheCapacity = int(n) + } + + defaultQueryExecMode := QueryExecModeCacheStatement + if s, ok := config.RuntimeParams["default_query_exec_mode"]; ok { + delete(config.RuntimeParams, "default_query_exec_mode") + switch s { + case "cache_statement": + defaultQueryExecMode = QueryExecModeCacheStatement + case "cache_describe": + defaultQueryExecMode = QueryExecModeCacheDescribe + case "describe_exec": + defaultQueryExecMode = QueryExecModeDescribeExec + case "exec": + defaultQueryExecMode = QueryExecModeExec + case "simple_protocol": + defaultQueryExecMode = QueryExecModeSimpleProtocol + default: + return nil, pgconn.NewParseConfigError( + connString, "invalid default_query_exec_mode", fmt.Errorf("unknown value %q", s), + ) + } + } + + connConfig := &ConnConfig{ + Config: *config, + createdByParseConfig: true, + StatementCacheCapacity: statementCacheCapacity, + DescriptionCacheCapacity: descriptionCacheCapacity, + DefaultQueryExecMode: defaultQueryExecMode, + connString: connString, + } + + return connConfig, nil +} + +// ParseConfig creates a ConnConfig from a connection string. ParseConfig handles all options that [pgconn.ParseConfig] +// does. In addition, it accepts the following options: +// +// - default_query_exec_mode. +// Possible values: "cache_statement", "cache_describe", "describe_exec", "exec", and "simple_protocol". See +// QueryExecMode constant documentation for the meaning of these values. Default: "cache_statement". +// +// - statement_cache_capacity. +// The maximum size of the statement cache used when executing a query with "cache_statement" query exec mode. +// Default: 512. +// +// - description_cache_capacity. +// The maximum size of the description cache used when executing a query with "cache_describe" query exec mode. +// Default: 512. +func ParseConfig(connString string) (*ConnConfig, error) { + return ParseConfigWithOptions(connString, ParseConfigOptions{}) +} + +// connect connects to a database. connect takes ownership of config. The caller must not use or access it again. +func connect(ctx context.Context, config *ConnConfig) (c *Conn, err error) { + if connectTracer, ok := config.Tracer.(ConnectTracer); ok { + ctx = connectTracer.TraceConnectStart(ctx, TraceConnectStartData{ConnConfig: config}) + defer func() { + connectTracer.TraceConnectEnd(ctx, TraceConnectEndData{Conn: c, Err: err}) + }() + } + + // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from + // zero values. + if !config.createdByParseConfig { + panic("config must be created by ParseConfig") + } + + c = &Conn{ + config: config, + typeMap: pgtype.NewMap(), + queryTracer: config.Tracer, + } + + if t, ok := c.queryTracer.(BatchTracer); ok { + c.batchTracer = t + } + if t, ok := c.queryTracer.(CopyFromTracer); ok { + c.copyFromTracer = t + } + if t, ok := c.queryTracer.(PrepareTracer); ok { + c.prepareTracer = t + } + + // Only install pgx notification system if no other callback handler is present. + if config.Config.OnNotification == nil { + config.Config.OnNotification = c.bufferNotifications + } + + c.pgConn, err = pgconn.ConnectConfig(ctx, &config.Config) + if err != nil { + return nil, err + } + + c.preparedStatements = make(map[string]*pgconn.StatementDescription) + c.doneChan = make(chan struct{}) + c.closedChan = make(chan error) + c.wbuf = make([]byte, 0, 1024) + + if c.config.StatementCacheCapacity > 0 { + c.statementCache = stmtcache.NewLRUCache(c.config.StatementCacheCapacity) + } + + if c.config.DescriptionCacheCapacity > 0 { + c.descriptionCache = stmtcache.NewLRUCache(c.config.DescriptionCacheCapacity) + } + + return c, nil +} + +// Close closes a connection. It is safe to call Close on an already closed +// connection. +func (c *Conn) Close(ctx context.Context) error { + if c.IsClosed() { + return nil + } + + err := c.pgConn.Close(ctx) + return err +} + +// Prepare creates a prepared statement with name and sql. sql can contain placeholders for bound parameters. These +// placeholders are referenced positionally as $1, $2, etc. name can be used instead of sql with [Conn.Query], +// [Conn.QueryRow], and [Conn.Exec] to execute the statement. It can also be used with [Batch.Queue]. +// +// The underlying PostgreSQL identifier for the prepared statement will be name if name != sql or a digest of sql if +// name == sql. +// +// Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same name and sql arguments. This +// allows a code path to Prepare and Query/Exec without concern for if the statement has already been prepared. +func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.StatementDescription, err error) { + if c.failedDescribeStatement != "" { + err = c.Deallocate(ctx, c.failedDescribeStatement) + if err != nil { + return nil, fmt.Errorf("failed to deallocate previously failed statement %q: %w", c.failedDescribeStatement, err) + } + c.failedDescribeStatement = "" + } + + if c.prepareTracer != nil { + ctx = c.prepareTracer.TracePrepareStart(ctx, c, TracePrepareStartData{Name: name, SQL: sql}) + } + + if name != "" { + var ok bool + if sd, ok = c.preparedStatements[name]; ok && sd.SQL == sql { + if c.prepareTracer != nil { + c.prepareTracer.TracePrepareEnd(ctx, c, TracePrepareEndData{AlreadyPrepared: true}) + } + return sd, nil + } + } + + if c.prepareTracer != nil { + defer func() { + c.prepareTracer.TracePrepareEnd(ctx, c, TracePrepareEndData{Err: err}) + }() + } + + var psName, psKey string + if name == sql { + digest := sha256.Sum256([]byte(sql)) + psName = "stmt_" + hex.EncodeToString(digest[0:24]) + psKey = sql + } else { + psName = name + psKey = name + } + + sd, err = c.pgConn.Prepare(ctx, psName, sql, nil) + if err != nil { + var pErr *pgconn.PrepareError + if errors.As(err, &pErr) { + c.failedDescribeStatement = psKey + } + return nil, err + } + + if psKey != "" { + c.preparedStatements[psKey] = sd + } + + return sd, nil +} + +// Deallocate releases a prepared statement. Calling Deallocate on a non-existent prepared statement will succeed. +func (c *Conn) Deallocate(ctx context.Context, name string) error { + var psName string + sd := c.preparedStatements[name] + if sd != nil { + psName = sd.Name + } else { + psName = name + } + + err := c.pgConn.Deallocate(ctx, psName) + if err != nil { + return err + } + + if sd != nil { + delete(c.preparedStatements, name) + } + + return nil +} + +// DeallocateAll releases all previously prepared statements from the server and client, where it also resets the statement and description cache. +func (c *Conn) DeallocateAll(ctx context.Context) error { + c.preparedStatements = map[string]*pgconn.StatementDescription{} + if c.config.StatementCacheCapacity > 0 { + c.statementCache = stmtcache.NewLRUCache(c.config.StatementCacheCapacity) + } + if c.config.DescriptionCacheCapacity > 0 { + c.descriptionCache = stmtcache.NewLRUCache(c.config.DescriptionCacheCapacity) + } + _, err := c.pgConn.Exec(ctx, "deallocate all").ReadAll() + return err +} + +func (c *Conn) bufferNotifications(_ *pgconn.PgConn, n *pgconn.Notification) { + c.notifications = append(c.notifications, n) +} + +// WaitForNotification waits for a PostgreSQL notification. It wraps the underlying pgconn notification system in a +// slightly more convenient form. +func (c *Conn) WaitForNotification(ctx context.Context) (*pgconn.Notification, error) { + var n *pgconn.Notification + + // Return already received notification immediately + if len(c.notifications) > 0 { + n = c.notifications[0] + c.notifications = c.notifications[1:] + return n, nil + } + + err := c.pgConn.WaitForNotification(ctx) + if len(c.notifications) > 0 { + n = c.notifications[0] + c.notifications = c.notifications[1:] + } + return n, err +} + +// IsClosed reports if the connection has been closed. +func (c *Conn) IsClosed() bool { + return c.pgConn.IsClosed() +} + +func (c *Conn) die() { + if c.IsClosed() { + return + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() // force immediate hard cancel + c.pgConn.Close(ctx) +} + +func quoteIdentifier(s string) string { + return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` +} + +// Ping delegates to the underlying *pgconn.PgConn.Ping. +func (c *Conn) Ping(ctx context.Context) error { + return c.pgConn.Ping(ctx) +} + +// PgConn returns the underlying *pgconn.PgConn. This is an escape hatch method that allows lower level access to the +// PostgreSQL connection than pgx exposes. +// +// It is strongly recommended that the connection be idle (no in-progress queries) before the underlying *pgconn.PgConn +// is used and the connection must be returned to the same state before any *pgx.Conn methods are again used. +func (c *Conn) PgConn() *pgconn.PgConn { return c.pgConn } + +// TypeMap returns the connection info used for this connection. +func (c *Conn) TypeMap() *pgtype.Map { return c.typeMap } + +// Config returns a copy of config that was used to establish this connection. +func (c *Conn) Config() *ConnConfig { return c.config.Copy() } + +// Exec executes sql. sql can be either a prepared statement name or an SQL string. arguments should be referenced +// positionally from the sql string as $1, $2, etc. +func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { + if c.queryTracer != nil { + ctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: arguments}) + } + + if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { + return pgconn.CommandTag{}, err + } + + commandTag, err := c.exec(ctx, sql, arguments...) + + if c.queryTracer != nil { + c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{CommandTag: commandTag, Err: err}) + } + + return commandTag, err +} + +func (c *Conn) exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) { + mode := c.config.DefaultQueryExecMode + var queryRewriter QueryRewriter + +optionLoop: + for len(arguments) > 0 { + switch arg := arguments[0].(type) { + case QueryExecMode: + mode = arg + arguments = arguments[1:] + case QueryRewriter: + queryRewriter = arg + arguments = arguments[1:] + default: + break optionLoop + } + } + + if queryRewriter != nil { + sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments) + if err != nil { + return pgconn.CommandTag{}, fmt.Errorf("rewrite query failed: %w", err) + } + } + + // Always use simple protocol when there are no arguments. + if len(arguments) == 0 { + mode = QueryExecModeSimpleProtocol + } + + defer func() { + if err != nil { + if sc := c.statementCache; sc != nil { + sc.Invalidate(sql) + } + + if sc := c.descriptionCache; sc != nil { + sc.Invalidate(sql) + } + } + }() + + if sd, ok := c.preparedStatements[sql]; ok { + return c.execPrepared(ctx, sd, arguments) + } + + switch mode { + case QueryExecModeCacheStatement: + if c.statementCache == nil { + return pgconn.CommandTag{}, errDisabledStatementCache + } + sd := c.statementCache.Get(sql) + if sd == nil { + sd, err = c.Prepare(ctx, stmtcache.StatementName(sql), sql) + if err != nil { + return pgconn.CommandTag{}, err + } + c.statementCache.Put(sd) + } + + return c.execPrepared(ctx, sd, arguments) + case QueryExecModeCacheDescribe: + if c.descriptionCache == nil { + return pgconn.CommandTag{}, errDisabledDescriptionCache + } + sd := c.descriptionCache.Get(sql) + if sd == nil { + sd, err = c.Prepare(ctx, "", sql) + if err != nil { + return pgconn.CommandTag{}, err + } + c.descriptionCache.Put(sd) + } + + return c.execParams(ctx, sd, arguments) + case QueryExecModeDescribeExec: + sd, err := c.Prepare(ctx, "", sql) + if err != nil { + return pgconn.CommandTag{}, err + } + return c.execPrepared(ctx, sd, arguments) + case QueryExecModeExec: + return c.execSQLParams(ctx, sql, arguments) + case QueryExecModeSimpleProtocol: + return c.execSimpleProtocol(ctx, sql, arguments) + default: + return pgconn.CommandTag{}, fmt.Errorf("unknown QueryExecMode: %v", mode) + } +} + +func (c *Conn) execSimpleProtocol(ctx context.Context, sql string, arguments []any) (commandTag pgconn.CommandTag, err error) { + if len(arguments) > 0 { + sql, err = c.sanitizeForSimpleQuery(sql, arguments...) + if err != nil { + return pgconn.CommandTag{}, err + } + } + + mrr := c.pgConn.Exec(ctx, sql) + for mrr.NextResult() { + commandTag, _ = mrr.ResultReader().Close() + } + err = mrr.Close() + return commandTag, err +} + +func (c *Conn) execParams(ctx context.Context, sd *pgconn.StatementDescription, arguments []any) (pgconn.CommandTag, error) { + err := c.eqb.Build(c.typeMap, sd, arguments) + if err != nil { + return pgconn.CommandTag{}, err + } + + result := c.pgConn.ExecParams(ctx, sd.SQL, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, c.eqb.ResultFormats).Read() + c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. + return result.CommandTag, result.Err +} + +func (c *Conn) execPrepared(ctx context.Context, sd *pgconn.StatementDescription, arguments []any) (pgconn.CommandTag, error) { + err := c.eqb.Build(c.typeMap, sd, arguments) + if err != nil { + return pgconn.CommandTag{}, err + } + + result := c.pgConn.ExecStatement(ctx, sd, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats).Read() + c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. + return result.CommandTag, result.Err +} + +func (c *Conn) execSQLParams(ctx context.Context, sql string, args []any) (pgconn.CommandTag, error) { + err := c.eqb.Build(c.typeMap, nil, args) + if err != nil { + return pgconn.CommandTag{}, err + } + + result := c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats).Read() + c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. + return result.CommandTag, result.Err +} + +func (c *Conn) getRows(ctx context.Context, sql string, args []any) *baseRows { + r := &baseRows{} + + r.ctx = ctx + r.queryTracer = c.queryTracer + r.typeMap = c.typeMap + r.startTime = time.Now() + r.sql = sql + r.args = args + r.conn = c + + return r +} + +type QueryExecMode int32 + +const ( + _ QueryExecMode = iota + + // Automatically prepare and cache statements. This uses the extended protocol. Queries are executed in a single round + // trip after the statement is cached. This is the default. If the database schema is modified or the search_path is + // changed after a statement is cached then the first execution of a previously cached query may fail. e.g. If the + // number of columns returned by a "SELECT *" changes or the type of a column is changed. + QueryExecModeCacheStatement + + // Cache statement descriptions (i.e. argument and result types) and assume they do not change. This uses the extended + // protocol. Queries are executed in a single round trip after the description is cached. If the database schema is + // modified or the search_path is changed after a statement is cached then the first execution of a previously cached + // query may fail. e.g. If the number of columns returned by a "SELECT *" changes or the type of a column is changed. + QueryExecModeCacheDescribe + + // Get the statement description on every execution. This uses the extended protocol. Queries require two round trips + // to execute. It does not use named prepared statements. But it does use the unnamed prepared statement to get the + // statement description on the first round trip and then uses it to execute the query on the second round trip. This + // may cause problems with connection poolers that switch the underlying connection between round trips. It is safe + // even when the database schema is modified concurrently. + QueryExecModeDescribeExec + + // Assume the PostgreSQL query parameter types based on the Go type of the arguments. This uses the extended protocol + // with text formatted parameters and results. Queries are executed in a single round trip. Type mappings can be + // registered with pgtype.Map.RegisterDefaultPgType. Queries will be rejected that have arguments that are + // unregistered or ambiguous. e.g. A map[string]string may have the PostgreSQL type json or hstore. Modes that know + // the PostgreSQL type can use a map[string]string directly as an argument. This mode cannot. + // + // On rare occasions user defined types may behave differently when encoded in the text format instead of the binary + // format. For example, this could happen if a "type RomanNumeral int32" implements fmt.Stringer to format integers as + // Roman numerals (e.g. 7 is VII). The binary format would properly encode the integer 7 as the binary value for 7. + // But the text format would encode the integer 7 as the string "VII". As QueryExecModeExec uses the text format, it + // is possible that changing query mode from another mode to QueryExecModeExec could change the behavior of the query. + // This should not occur with types pgx supports directly and can be avoided by registering the types with + // pgtype.Map.RegisterDefaultPgType and implementing the appropriate type interfaces. In the cas of RomanNumeral, it + // should implement pgtype.Int64Valuer. + QueryExecModeExec + + // Use the simple protocol. Assume the PostgreSQL query parameter types based on the Go type of the arguments. This is + // especially significant for []byte values. []byte values are encoded as PostgreSQL bytea. string must be used + // instead for text type values including json and jsonb. Type mappings can be registered with + // pgtype.Map.RegisterDefaultPgType. Queries will be rejected that have arguments that are unregistered or ambiguous. + // e.g. A map[string]string may have the PostgreSQL type json or hstore. Modes that know the PostgreSQL type can use a + // map[string]string directly as an argument. This mode cannot. Queries are executed in a single round trip. + // + // QueryExecModeSimpleProtocol should have the user application visible behavior as QueryExecModeExec. This includes + // the warning regarding differences in text format and binary format encoding with user defined types. There may be + // other minor exceptions such as behavior when multiple result returning queries are erroneously sent in a single + // string. + // + // QueryExecModeSimpleProtocol uses client side parameter interpolation. All values are quoted and escaped. Prefer + // QueryExecModeExec over QueryExecModeSimpleProtocol whenever possible. In general QueryExecModeSimpleProtocol should + // only be used if connecting to a proxy server, connection pool server, or non-PostgreSQL server that does not + // support the extended protocol. + QueryExecModeSimpleProtocol +) + +func (m QueryExecMode) String() string { + switch m { + case QueryExecModeCacheStatement: + return "cache statement" + case QueryExecModeCacheDescribe: + return "cache describe" + case QueryExecModeDescribeExec: + return "describe exec" + case QueryExecModeExec: + return "exec" + case QueryExecModeSimpleProtocol: + return "simple protocol" + default: + return "invalid" + } +} + +// QueryResultFormats controls the result format (text=0, binary=1) of a query by result column position. +type QueryResultFormats []int16 + +// QueryResultFormatsByOID controls the result format (text=0, binary=1) of a query by the result column OID. +type QueryResultFormatsByOID map[uint32]int16 + +// QueryRewriter rewrites a query when used as the first arguments to a query method. +type QueryRewriter interface { + RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) +} + +// Query sends a query to the server and returns a Rows to read the results. Only errors encountered sending the query +// and initializing Rows will be returned. Err() on the returned Rows must be checked after the Rows is closed to +// determine if the query executed successfully. +// +// The returned Rows must be closed before the connection can be used again. It is safe to attempt to read from the +// returned Rows even if an error is returned. The error will be the available in rows.Err() after rows are closed. It +// is allowed to ignore the error returned from Query and handle it in Rows. +// +// It is possible for a call of FieldDescriptions on the returned Rows to return nil even if the Query call did not +// return an error. +// +// It is possible for a query to return one or more rows before encountering an error. In most cases the rows should be +// collected before processing rather than processed while receiving each row. This avoids the possibility of the +// application processing rows from a query that the server rejected. The CollectRows function is useful here. +// +// An implementor of QueryRewriter may be passed as the first element of args. It can rewrite the sql and change or +// replace args. For example, NamedArgs is QueryRewriter that implements named arguments. +// +// For extra control over how the query is executed, the types QueryExecMode, QueryResultFormats, and +// QueryResultFormatsByOID may be used as the first args to control exactly how the query is executed. This is rarely +// needed. See the documentation for those types for details. +func (c *Conn) Query(ctx context.Context, sql string, args ...any) (Rows, error) { + if c.queryTracer != nil { + ctx = c.queryTracer.TraceQueryStart(ctx, c, TraceQueryStartData{SQL: sql, Args: args}) + } + + if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { + if c.queryTracer != nil { + c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err}) + } + return &baseRows{err: err, closed: true}, err + } + + var resultFormats QueryResultFormats + var resultFormatsByOID QueryResultFormatsByOID + mode := c.config.DefaultQueryExecMode + var queryRewriter QueryRewriter + +optionLoop: + for len(args) > 0 { + switch arg := args[0].(type) { + case QueryResultFormats: + resultFormats = arg + args = args[1:] + case QueryResultFormatsByOID: + resultFormatsByOID = arg + args = args[1:] + case QueryExecMode: + mode = arg + args = args[1:] + case QueryRewriter: + queryRewriter = arg + args = args[1:] + default: + break optionLoop + } + } + + if queryRewriter != nil { + var err error + originalSQL := sql + originalArgs := args + sql, args, err = queryRewriter.RewriteQuery(ctx, c, sql, args) + if err != nil { + rows := c.getRows(ctx, originalSQL, originalArgs) + err = fmt.Errorf("rewrite query failed: %w", err) + rows.fatal(err) + return rows, err + } + } + + // Bypass any statement caching. + if sql == "" { + mode = QueryExecModeSimpleProtocol + } + + c.eqb.reset() + rows := c.getRows(ctx, sql, args) + + var err error + sd, explicitPreparedStatement := c.preparedStatements[sql] + switch { + case sd != nil || mode == QueryExecModeCacheStatement || mode == QueryExecModeCacheDescribe || mode == QueryExecModeDescribeExec: + if sd == nil { + sd, err = c.getStatementDescription(ctx, mode, sql) + if err != nil { + rows.fatal(err) + return rows, err + } + } + + if len(sd.ParamOIDs) != len(args) { + rows.fatal(fmt.Errorf("expected %d arguments, got %d", len(sd.ParamOIDs), len(args))) + return rows, rows.err + } + + rows.sql = sd.SQL + + err = c.eqb.Build(c.typeMap, sd, args) + if err != nil { + rows.fatal(err) + return rows, rows.err + } + + if resultFormatsByOID != nil { + resultFormats = make([]int16, len(sd.Fields)) + for i := range resultFormats { + resultFormats[i] = resultFormatsByOID[sd.Fields[i].DataTypeOID] + } + } + + if resultFormats == nil { + resultFormats = c.eqb.ResultFormats + } + + if !explicitPreparedStatement && mode == QueryExecModeCacheDescribe { + rows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, sd.ParamOIDs, c.eqb.ParamFormats, resultFormats) + } else { + rows.resultReader = c.pgConn.ExecStatement(ctx, sd, c.eqb.ParamValues, c.eqb.ParamFormats, resultFormats) + } + case mode == QueryExecModeExec: + err := c.eqb.Build(c.typeMap, nil, args) + if err != nil { + rows.fatal(err) + return rows, rows.err + } + + rows.resultReader = c.pgConn.ExecParams(ctx, sql, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats) + case mode == QueryExecModeSimpleProtocol: + sql, err = c.sanitizeForSimpleQuery(sql, args...) + if err != nil { + rows.fatal(err) + return rows, err + } + + mrr := c.pgConn.Exec(ctx, sql) + if mrr.NextResult() { + rows.resultReader = mrr.ResultReader() + rows.multiResultReader = mrr + } else { + err = mrr.Close() + rows.fatal(err) + return rows, err + } + + return rows, nil + default: + err = fmt.Errorf("unknown QueryExecMode: %v", mode) + rows.fatal(err) + return rows, rows.err + } + + c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. + + return rows, rows.err +} + +// getStatementDescription returns the statement description of the sql query +// according to the given mode. +// +// If the mode is one that doesn't require to know the param and result OIDs +// then nil is returned without error. +func (c *Conn) getStatementDescription( + ctx context.Context, + mode QueryExecMode, + sql string, +) (sd *pgconn.StatementDescription, err error) { + switch mode { + case QueryExecModeCacheStatement: + if c.statementCache == nil { + return nil, errDisabledStatementCache + } + sd = c.statementCache.Get(sql) + if sd == nil { + sd, err = c.Prepare(ctx, stmtcache.StatementName(sql), sql) + if err != nil { + return nil, err + } + c.statementCache.Put(sd) + } + case QueryExecModeCacheDescribe: + if c.descriptionCache == nil { + return nil, errDisabledDescriptionCache + } + sd = c.descriptionCache.Get(sql) + if sd == nil { + sd, err = c.Prepare(ctx, "", sql) + if err != nil { + return nil, err + } + c.descriptionCache.Put(sd) + } + case QueryExecModeDescribeExec: + return c.Prepare(ctx, "", sql) + } + return sd, err +} + +// QueryRow is a convenience wrapper over Query. Any error that occurs while +// querying is deferred until calling Scan on the returned Row. That Row will +// error with ErrNoRows if no rows are returned. +func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row { + rows, _ := c.Query(ctx, sql, args...) + return (*connRow)(rows.(*baseRows)) +} + +// SendBatch sends all queued queries to the server at once. All queries are run in an implicit transaction unless +// explicit transaction control statements are executed. The returned [BatchResults] must be closed before the connection +// is used again. +// +// Depending on the QueryExecMode, all queries may be prepared before any are executed. This means that creating a table +// and using it in a subsequent query in the same batch can fail. +func (c *Conn) SendBatch(ctx context.Context, b *Batch) (br BatchResults) { + if len(b.QueuedQueries) == 0 { + return &emptyBatchResults{conn: c} + } + + if c.batchTracer != nil { + ctx = c.batchTracer.TraceBatchStart(ctx, c, TraceBatchStartData{Batch: b}) + defer func() { + err := br.(interface{ earlyError() error }).earlyError() + if err != nil { + c.batchTracer.TraceBatchEnd(ctx, c, TraceBatchEndData{Err: err}) + } + }() + } + + if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil { + return &batchResults{ctx: ctx, conn: c, err: err} + } + + for _, bi := range b.QueuedQueries { + var queryRewriter QueryRewriter + sql := bi.SQL + arguments := bi.Arguments + + optionLoop: + for len(arguments) > 0 { + // Update Batch.Queue function comment when additional options are implemented + switch arg := arguments[0].(type) { + case QueryRewriter: + queryRewriter = arg + arguments = arguments[1:] + default: + break optionLoop + } + } + + if queryRewriter != nil { + var err error + sql, arguments, err = queryRewriter.RewriteQuery(ctx, c, sql, arguments) + if err != nil { + return &batchResults{ctx: ctx, conn: c, err: fmt.Errorf("rewrite query failed: %w", err)} + } + } + + bi.SQL = sql + bi.Arguments = arguments + } + + // TODO: changing mode per batch? Update Batch.Queue function comment when implemented + mode := c.config.DefaultQueryExecMode + if mode == QueryExecModeSimpleProtocol { + return c.sendBatchQueryExecModeSimpleProtocol(ctx, b) + } + + // All other modes use extended protocol and thus can use prepared statements. + for _, bi := range b.QueuedQueries { + if sd, ok := c.preparedStatements[bi.SQL]; ok { + bi.sd = sd + } + } + + switch mode { + case QueryExecModeExec: + return c.sendBatchQueryExecModeExec(ctx, b) + case QueryExecModeCacheStatement: + return c.sendBatchQueryExecModeCacheStatement(ctx, b) + case QueryExecModeCacheDescribe: + return c.sendBatchQueryExecModeCacheDescribe(ctx, b) + case QueryExecModeDescribeExec: + return c.sendBatchQueryExecModeDescribeExec(ctx, b) + default: + panic("unknown QueryExecMode") + } +} + +func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batch) *batchResults { + var sb strings.Builder + for i, bi := range b.QueuedQueries { + if i > 0 { + sb.WriteByte(';') + } + sql, err := c.sanitizeForSimpleQuery(bi.SQL, bi.Arguments...) + if err != nil { + return &batchResults{ctx: ctx, conn: c, err: err} + } + sb.WriteString(sql) + } + mrr := c.pgConn.Exec(ctx, sb.String()) + return &batchResults{ + ctx: ctx, + conn: c, + mrr: mrr, + b: b, + qqIdx: 0, + } +} + +func (c *Conn) sendBatchQueryExecModeExec(ctx context.Context, b *Batch) *batchResults { + batch := &pgconn.Batch{} + + for _, bi := range b.QueuedQueries { + sd := bi.sd + if sd != nil { + err := c.eqb.Build(c.typeMap, sd, bi.Arguments) + if err != nil { + return &batchResults{ctx: ctx, conn: c, err: err} + } + + batch.ExecPrepared(sd.Name, c.eqb.ParamValues, c.eqb.ParamFormats, c.eqb.ResultFormats) + } else { + err := c.eqb.Build(c.typeMap, nil, bi.Arguments) + if err != nil { + return &batchResults{ctx: ctx, conn: c, err: err} + } + batch.ExecParams(bi.SQL, c.eqb.ParamValues, nil, c.eqb.ParamFormats, c.eqb.ResultFormats) + } + } + + c.eqb.reset() // Allow c.eqb internal memory to be GC'ed as soon as possible. + + mrr := c.pgConn.ExecBatch(ctx, batch) + + return &batchResults{ + ctx: ctx, + conn: c, + mrr: mrr, + b: b, + qqIdx: 0, + } +} + +func (c *Conn) sendBatchQueryExecModeCacheStatement(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) { + if c.statementCache == nil { + return &pipelineBatchResults{ctx: ctx, conn: c, err: errDisabledStatementCache, closed: true} + } + + distinctNewQueries := []*pgconn.StatementDescription{} + distinctNewQueriesIdxMap := make(map[string]int) + + for _, bi := range b.QueuedQueries { + if bi.sd == nil { + sd := c.statementCache.Get(bi.SQL) + if sd != nil { + bi.sd = sd + } else { + if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { + bi.sd = distinctNewQueries[idx] + } else { + sd = &pgconn.StatementDescription{ + Name: stmtcache.StatementName(bi.SQL), + SQL: bi.SQL, + } + distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) + distinctNewQueries = append(distinctNewQueries, sd) + bi.sd = sd + } + } + } + } + + return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, c.statementCache) +} + +func (c *Conn) sendBatchQueryExecModeCacheDescribe(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) { + if c.descriptionCache == nil { + return &pipelineBatchResults{ctx: ctx, conn: c, err: errDisabledDescriptionCache, closed: true} + } + + distinctNewQueries := []*pgconn.StatementDescription{} + distinctNewQueriesIdxMap := make(map[string]int) + + for _, bi := range b.QueuedQueries { + if bi.sd == nil { + sd := c.descriptionCache.Get(bi.SQL) + if sd != nil { + bi.sd = sd + } else { + if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { + bi.sd = distinctNewQueries[idx] + } else { + sd = &pgconn.StatementDescription{ + SQL: bi.SQL, + } + distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) + distinctNewQueries = append(distinctNewQueries, sd) + bi.sd = sd + } + } + } + } + + return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, c.descriptionCache) +} + +func (c *Conn) sendBatchQueryExecModeDescribeExec(ctx context.Context, b *Batch) (pbr *pipelineBatchResults) { + distinctNewQueries := []*pgconn.StatementDescription{} + distinctNewQueriesIdxMap := make(map[string]int) + + for _, bi := range b.QueuedQueries { + if bi.sd == nil { + if idx, present := distinctNewQueriesIdxMap[bi.SQL]; present { + bi.sd = distinctNewQueries[idx] + } else { + sd := &pgconn.StatementDescription{ + SQL: bi.SQL, + } + distinctNewQueriesIdxMap[sd.SQL] = len(distinctNewQueries) + distinctNewQueries = append(distinctNewQueries, sd) + bi.sd = sd + } + } + } + + return c.sendBatchExtendedWithDescription(ctx, b, distinctNewQueries, nil) +} + +func (c *Conn) sendBatchExtendedWithDescription(ctx context.Context, b *Batch, distinctNewQueries []*pgconn.StatementDescription, sdCache stmtcache.Cache) (pbr *pipelineBatchResults) { + pipeline := c.pgConn.StartPipeline(ctx) + defer func() { + if pbr != nil && pbr.err != nil { + pipeline.Close() + } + }() + + // Prepare any needed queries + if len(distinctNewQueries) > 0 { + err := func() (err error) { + for _, sd := range distinctNewQueries { + pipeline.SendPrepare(sd.Name, sd.SQL, nil) + } + + // Store all statements we are preparing into the cache. It's fine if it overflows because HandleInvalidated will + // clean them up later. + if sdCache != nil { + for _, sd := range distinctNewQueries { + sdCache.Put(sd) + } + } + + // If something goes wrong preparing the statements, we need to invalidate the cache entries we just added. + defer func() { + if err != nil && sdCache != nil { + for _, sd := range distinctNewQueries { + sdCache.Invalidate(sd.SQL) + } + } + }() + + err = pipeline.Sync() + if err != nil { + return err + } + + for _, sd := range distinctNewQueries { + results, err := pipeline.GetResults() + if err != nil { + return newErrPreprocessingBatch("prepare", sd.SQL, err) + } + + resultSD, ok := results.(*pgconn.StatementDescription) + if !ok { + return fmt.Errorf("expected statement description, got %T", results) + } + + // Fill in the previously empty / pending statement descriptions. + sd.ParamOIDs = resultSD.ParamOIDs + sd.Fields = resultSD.Fields + } + + results, err := pipeline.GetResults() + if err != nil { + return err + } + + _, ok := results.(*pgconn.PipelineSync) + if !ok { + return fmt.Errorf("expected sync, got %T", results) + } + + return nil + }() + if err != nil { + return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} + } + } + + // Queue the queries. + for _, bi := range b.QueuedQueries { + err := c.eqb.Build(c.typeMap, bi.sd, bi.Arguments) + if err != nil { + err = newErrPreprocessingBatch("build", bi.SQL, err) + return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} + } + + if bi.sd.Name == "" { + pipeline.SendQueryParams(bi.sd.SQL, c.eqb.ParamValues, bi.sd.ParamOIDs, c.eqb.ParamFormats, c.eqb.ResultFormats) + } else { + // Copy ResultFormats because SendQueryStatement stores the slice for later use, and eqb.Build reuses the + // backing array on the next iteration. + resultFormats := make([]int16, len(c.eqb.ResultFormats)) + copy(resultFormats, c.eqb.ResultFormats) + pipeline.SendQueryStatement(bi.sd, c.eqb.ParamValues, c.eqb.ParamFormats, resultFormats) + } + } + + err := pipeline.Sync() + if err != nil { + return &pipelineBatchResults{ctx: ctx, conn: c, err: err, closed: true} + } + + return &pipelineBatchResults{ + ctx: ctx, + conn: c, + pipeline: pipeline, + b: b, + } +} + +func (c *Conn) sanitizeForSimpleQuery(sql string, args ...any) (string, error) { + if c.pgConn.ParameterStatus("standard_conforming_strings") != "on" { + return "", errors.New("simple protocol queries must be run with standard_conforming_strings=on") + } + + if c.pgConn.ParameterStatus("client_encoding") != "UTF8" { + return "", errors.New("simple protocol queries must be run with client_encoding=UTF8") + } + + var err error + valueArgs := make([]any, len(args)) + for i, a := range args { + valueArgs[i], err = convertSimpleArgument(c.typeMap, a) + if err != nil { + return "", err + } + } + + return sanitize.SanitizeSQL(sql, valueArgs...) +} + +// LoadType inspects the database for typeName and produces a [pgtype.Type] suitable for registration. typeName must be +// the name of a type where the underlying type(s) is already understood by pgx. It is for derived types. In particular, +// typeName must be one of the following: +// - An array type name of a type that is already registered. e.g. "_foo" when "foo" is registered. +// - A composite type name where all field types are already registered. +// - A domain type name where the base type is already registered. +// - An enum type name. +// - A range type name where the element type is already registered. +// - A multirange type name where the element type is already registered. +func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, error) { + var oid uint32 + + err := c.QueryRow(ctx, "select $1::text::regtype::oid;", typeName).Scan(&oid) + if err != nil { + return nil, err + } + + var typtype string + var typbasetype uint32 + + err = c.QueryRow(ctx, "select typtype::text, typbasetype from pg_type where oid=$1", oid).Scan(&typtype, &typbasetype) + if err != nil { + return nil, err + } + + switch typtype { + case "b": // array + elementOID, err := c.getArrayElementOID(ctx, oid) + if err != nil { + return nil, err + } + + dt, ok := c.TypeMap().TypeForOID(elementOID) + if !ok { + return nil, errors.New("array element OID not registered") + } + + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}, nil + case "c": // composite + fields, err := c.getCompositeFields(ctx, oid) + if err != nil { + return nil, err + } + + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.CompositeCodec{Fields: fields}}, nil + case "d": // domain + dt, ok := c.TypeMap().TypeForOID(typbasetype) + if !ok { + return nil, errors.New("domain base type OID not registered") + } + + return &pgtype.Type{Name: typeName, OID: oid, Codec: dt.Codec}, nil + case "e": // enum + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.EnumCodec{}}, nil + case "r": // range + elementOID, err := c.getRangeElementOID(ctx, oid) + if err != nil { + return nil, err + } + + dt, ok := c.TypeMap().TypeForOID(elementOID) + if !ok { + return nil, errors.New("range element OID not registered") + } + + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.RangeCodec{ElementType: dt}}, nil + case "m": // multirange + elementOID, err := c.getMultiRangeElementOID(ctx, oid) + if err != nil { + return nil, err + } + + dt, ok := c.TypeMap().TypeForOID(elementOID) + if !ok { + return nil, errors.New("multirange element OID not registered") + } + + return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}}, nil + default: + return &pgtype.Type{}, errors.New("unknown typtype") + } +} + +func (c *Conn) getArrayElementOID(ctx context.Context, oid uint32) (uint32, error) { + var typelem uint32 + + err := c.QueryRow(ctx, "select typelem from pg_type where oid=$1", oid).Scan(&typelem) + if err != nil { + return 0, err + } + + return typelem, nil +} + +func (c *Conn) getRangeElementOID(ctx context.Context, oid uint32) (uint32, error) { + var typelem uint32 + + err := c.QueryRow(ctx, "select rngsubtype from pg_range where rngtypid=$1", oid).Scan(&typelem) + if err != nil { + return 0, err + } + + return typelem, nil +} + +func (c *Conn) getMultiRangeElementOID(ctx context.Context, oid uint32) (uint32, error) { + var typelem uint32 + + err := c.QueryRow(ctx, "select rngtypid from pg_range where rngmultitypid=$1", oid).Scan(&typelem) + if err != nil { + return 0, err + } + + return typelem, nil +} + +func (c *Conn) getCompositeFields(ctx context.Context, oid uint32) ([]pgtype.CompositeCodecField, error) { + var typrelid uint32 + + err := c.QueryRow(ctx, "select typrelid from pg_type where oid=$1", oid).Scan(&typrelid) + if err != nil { + return nil, err + } + + var fields []pgtype.CompositeCodecField + var fieldName string + var fieldOID uint32 + rows, _ := c.Query(ctx, `select attname, atttypid +from pg_attribute +where attrelid=$1 + and not attisdropped + and attnum > 0 +order by attnum`, + typrelid, + ) + _, err = ForEachRow(rows, []any{&fieldName, &fieldOID}, func() error { + dt, ok := c.TypeMap().TypeForOID(fieldOID) + if !ok { + return fmt.Errorf("unknown composite type field OID: %v", fieldOID) + } + fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt}) + return nil + }) + if err != nil { + return nil, err + } + + return fields, nil +} + +func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error { + if txStatus := c.pgConn.TxStatus(); txStatus != 'I' && txStatus != 'T' { + return nil + } + + if c.descriptionCache != nil { + c.descriptionCache.RemoveInvalidated() + } + + var invalidatedStatements []*pgconn.StatementDescription + if c.statementCache != nil { + invalidatedStatements = c.statementCache.GetInvalidated() + } + + if len(invalidatedStatements) == 0 { + return nil + } + + pipeline := c.pgConn.StartPipeline(ctx) + defer pipeline.Close() + + for _, sd := range invalidatedStatements { + pipeline.SendDeallocate(sd.Name) + } + + err := pipeline.Sync() + if err != nil { + return fmt.Errorf("failed to deallocate cached statement(s): %w", err) + } + + err = pipeline.Close() + if err != nil { + return fmt.Errorf("failed to deallocate cached statement(s): %w", err) + } + + c.statementCache.RemoveInvalidated() + for _, sd := range invalidatedStatements { + delete(c.preparedStatements, sd.Name) + } + + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/copy_from.go b/vendor/github.com/jackc/pgx/v5/copy_from.go new file mode 100644 index 0000000..038c568 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/copy_from.go @@ -0,0 +1,276 @@ +package pgx + +import ( + "bytes" + "context" + "fmt" + "io" + + "github.com/jackc/pgx/v5/internal/pgio" + "github.com/jackc/pgx/v5/pgconn" +) + +// CopyFromRows returns a [CopyFromSource] interface over the provided rows slice +// making it usable by [Conn.CopyFrom]. +func CopyFromRows(rows [][]any) CopyFromSource { + return ©FromRows{rows: rows, idx: -1} +} + +type copyFromRows struct { + rows [][]any + idx int +} + +func (ctr *copyFromRows) Next() bool { + ctr.idx++ + return ctr.idx < len(ctr.rows) +} + +func (ctr *copyFromRows) Values() ([]any, error) { + return ctr.rows[ctr.idx], nil +} + +func (ctr *copyFromRows) Err() error { + return nil +} + +// CopyFromSlice returns a [CopyFromSource] interface over a dynamic func +// making it usable by [Conn.CopyFrom]. +func CopyFromSlice(length int, next func(int) ([]any, error)) CopyFromSource { + return ©FromSlice{next: next, idx: -1, len: length} +} + +type copyFromSlice struct { + next func(int) ([]any, error) + idx int + len int + err error +} + +func (cts *copyFromSlice) Next() bool { + cts.idx++ + return cts.idx < cts.len +} + +func (cts *copyFromSlice) Values() ([]any, error) { + values, err := cts.next(cts.idx) + if err != nil { + cts.err = err + } + return values, err +} + +func (cts *copyFromSlice) Err() error { + return cts.err +} + +// CopyFromFunc returns a [CopyFromSource] interface that relies on nxtf for values. +// nxtf returns rows until it either signals an 'end of data' by returning row=nil and err=nil, +// or it returns an error. If nxtf returns an error, the copy is aborted. +func CopyFromFunc(nxtf func() (row []any, err error)) CopyFromSource { + return ©FromFunc{next: nxtf} +} + +type copyFromFunc struct { + next func() ([]any, error) + valueRow []any + err error +} + +func (g *copyFromFunc) Next() bool { + g.valueRow, g.err = g.next() + // only return true if valueRow exists and no error + return g.valueRow != nil && g.err == nil +} + +func (g *copyFromFunc) Values() ([]any, error) { + return g.valueRow, g.err +} + +func (g *copyFromFunc) Err() error { + return g.err +} + +// CopyFromSource is the interface used by [Conn.CopyFrom] as the source for copy data. +type CopyFromSource interface { + // Next returns true if there is another row and makes the next row data + // available to Values(). When there are no more rows available or an error + // has occurred it returns false. + Next() bool + + // Values returns the values for the current row. + Values() ([]any, error) + + // Err returns any error that has been encountered by the CopyFromSource. If + // this is not nil *Conn.CopyFrom will abort the copy. + Err() error +} + +type copyFrom struct { + conn *Conn + tableName Identifier + columnNames []string + rowSrc CopyFromSource + readerErrChan chan error + mode QueryExecMode +} + +func (ct *copyFrom) run(ctx context.Context) (int64, error) { + if ct.conn.copyFromTracer != nil { + ctx = ct.conn.copyFromTracer.TraceCopyFromStart(ctx, ct.conn, TraceCopyFromStartData{ + TableName: ct.tableName, + ColumnNames: ct.columnNames, + }) + } + + quotedTableName := ct.tableName.Sanitize() + cbuf := &bytes.Buffer{} + for i, cn := range ct.columnNames { + if i != 0 { + cbuf.WriteString(", ") + } + cbuf.WriteString(quoteIdentifier(cn)) + } + quotedColumnNames := cbuf.String() + + var sd *pgconn.StatementDescription + switch ct.mode { + case QueryExecModeExec, QueryExecModeSimpleProtocol: + // These modes don't support the binary format. Before the inclusion of the + // QueryExecModes, Conn.Prepare was called on every COPY operation to get + // the OIDs. These prepared statements were not cached. + // + // Since that's the same behavior provided by QueryExecModeDescribeExec, + // we'll default to that mode. + ct.mode = QueryExecModeDescribeExec + fallthrough + case QueryExecModeCacheStatement, QueryExecModeCacheDescribe, QueryExecModeDescribeExec: + var err error + sd, err = ct.conn.getStatementDescription( + ctx, + ct.mode, + fmt.Sprintf("select %s from %s", quotedColumnNames, quotedTableName), + ) + if err != nil { + return 0, fmt.Errorf("statement description failed: %w", err) + } + default: + return 0, fmt.Errorf("unknown QueryExecMode: %v", ct.mode) + } + + r, w := io.Pipe() + doneChan := make(chan struct{}) + + go func() { + defer close(doneChan) + + // Purposely NOT using defer w.Close(). See https://github.com/golang/go/issues/24283. + buf := ct.conn.wbuf + + buf = append(buf, "PGCOPY\n\377\r\n\000"...) + buf = pgio.AppendInt32(buf, 0) + buf = pgio.AppendInt32(buf, 0) + + moreRows := true + for moreRows { + var err error + moreRows, buf, err = ct.buildCopyBuf(buf, sd) + if err != nil { + w.CloseWithError(err) + return + } + + if ct.rowSrc.Err() != nil { + w.CloseWithError(ct.rowSrc.Err()) + return + } + + if len(buf) > 0 { + _, err = w.Write(buf) + if err != nil { + w.Close() + return + } + } + + buf = buf[:0] + } + + w.Close() + }() + + commandTag, err := ct.conn.pgConn.CopyFrom(ctx, r, fmt.Sprintf("copy %s ( %s ) from stdin binary;", quotedTableName, quotedColumnNames)) + + r.Close() + <-doneChan + + if ct.conn.copyFromTracer != nil { + ct.conn.copyFromTracer.TraceCopyFromEnd(ctx, ct.conn, TraceCopyFromEndData{ + CommandTag: commandTag, + Err: err, + }) + } + + return commandTag.RowsAffected(), err +} + +func (ct *copyFrom) buildCopyBuf(buf []byte, sd *pgconn.StatementDescription) (bool, []byte, error) { + const sendBufSize = 65536 - 5 // The packet has a 5-byte header + lastBufLen := 0 + largestRowLen := 0 + + for ct.rowSrc.Next() { + lastBufLen = len(buf) + + values, err := ct.rowSrc.Values() + if err != nil { + return false, nil, err + } + if len(values) != len(ct.columnNames) { + return false, nil, fmt.Errorf("expected %d values, got %d values", len(ct.columnNames), len(values)) + } + + buf = pgio.AppendInt16(buf, int16(len(ct.columnNames))) + for i, val := range values { + buf, err = encodeCopyValue(ct.conn.typeMap, buf, sd.Fields[i].DataTypeOID, val) + if err != nil { + return false, nil, err + } + } + + rowLen := len(buf) - lastBufLen + if rowLen > largestRowLen { + largestRowLen = rowLen + } + + // Try not to overflow size of the buffer PgConn.CopyFrom will be reading into. If that happens then the nature of + // io.Pipe means that the next Read will be short. This can lead to pathological send sizes such as 65531, 13, 65531 + // 13, 65531, 13, 65531, 13. + if len(buf) > sendBufSize-largestRowLen { + return true, buf, nil + } + } + + return false, buf, nil +} + +// CopyFrom uses the PostgreSQL copy protocol to perform bulk data insertion. It returns the number of rows copied and +// an error. +// +// CopyFrom requires all values use the binary format. A pgtype.Type that supports the binary format must be registered +// for the type of each column. Almost all types implemented by pgx support the binary format. +// +// Even though enum types appear to be strings they still must be registered to use with [Conn.CopyFrom]. This can be done with +// [Conn.LoadType] and [pgtype.Map.RegisterType]. +func (c *Conn) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { + ct := ©From{ + conn: c, + tableName: tableName, + columnNames: columnNames, + rowSrc: rowSrc, + readerErrChan: make(chan error), + mode: c.config.DefaultQueryExecMode, + } + + return ct.run(ctx) +} diff --git a/vendor/github.com/jackc/pgx/v5/derived_types.go b/vendor/github.com/jackc/pgx/v5/derived_types.go new file mode 100644 index 0000000..3916006 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/derived_types.go @@ -0,0 +1,261 @@ +package pgx + +import ( + "context" + "fmt" + "regexp" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/pgtype" +) + +/* +buildLoadDerivedTypesSQL generates the correct query for retrieving type information. + + pgVersion: the major version of the PostgreSQL server + typeNames: the names of the types to load. If nil, load all types. +*/ +func buildLoadDerivedTypesSQL(pgVersion int64, typeNames []string) string { + supportsMultirange := (pgVersion >= 14) + var typeNamesClause string + + if typeNames == nil { + // This should not occur; this will not return any types + typeNamesClause = "= ''" + } else { + typeNamesClause = "= ANY($1::text[])" + } + parts := make([]string, 0, 10) + + // Each of the type names provided might be found in pg_class or pg_type. + // Additionally, it may or may not include a schema portion. + parts = append(parts, ` +WITH RECURSIVE +-- find the OIDs in pg_class which match one of the provided type names +selected_classes(oid,reltype) AS ( + -- this query uses the namespace search path, so will match type names without a schema prefix + SELECT pg_class.oid, pg_class.reltype + FROM pg_catalog.pg_class + LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pg_class.relnamespace + WHERE pg_catalog.pg_table_is_visible(pg_class.oid) + AND relname `, typeNamesClause, ` +UNION ALL + -- this query will only match type names which include the schema prefix + SELECT pg_class.oid, pg_class.reltype + FROM pg_class + INNER JOIN pg_namespace ON (pg_class.relnamespace = pg_namespace.oid) + WHERE nspname || '.' || relname `, typeNamesClause, ` +), +selected_types(oid) AS ( + -- collect the OIDs from pg_types which correspond to the selected classes + SELECT reltype AS oid + FROM selected_classes +UNION ALL + -- as well as any other type names which match our criteria + SELECT pg_type.oid + FROM pg_type + LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid) + WHERE typname `, typeNamesClause, ` + OR nspname || '.' || typname `, typeNamesClause, ` +), +-- this builds a parent/child mapping of objects, allowing us to know +-- all the child (ie: dependent) types that a parent (type) requires +-- As can be seen, there are 3 ways this can occur (the last of which +-- is due to being a composite class, where the composite fields are children) +pc(parent, child) AS ( + SELECT parent.oid, parent.typelem + FROM pg_type parent + WHERE parent.typtype = 'b' AND parent.typelem != 0 +UNION ALL + SELECT parent.oid, parent.typbasetype + FROM pg_type parent + WHERE parent.typtypmod = -1 AND parent.typbasetype != 0 +UNION ALL + SELECT pg_type.oid, atttypid + FROM pg_attribute + INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid) + INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype) + WHERE NOT attisdropped + AND attnum > 0 +), +-- Now construct a recursive query which includes a 'depth' element. +-- This is used to ensure that the "youngest" children are registered before +-- their parents. +relationships(parent, child, depth) AS ( + SELECT DISTINCT 0::OID, selected_types.oid, 0 + FROM selected_types +UNION ALL + SELECT pg_type.oid AS parent, pg_attribute.atttypid AS child, 1 + FROM selected_classes c + inner join pg_type ON (c.reltype = pg_type.oid) + inner join pg_attribute on (c.oid = pg_attribute.attrelid) +UNION ALL + SELECT pc.parent, pc.child, relationships.depth + 1 + FROM pc + INNER JOIN relationships ON (pc.parent = relationships.child) +), +-- composite fields need to be encapsulated as a couple of arrays to provide the required information for registration +composite AS ( + SELECT pg_type.oid, ARRAY_AGG(attname ORDER BY attnum) AS attnames, ARRAY_AGG(atttypid ORDER BY ATTNUM) AS atttypids + FROM pg_attribute + INNER JOIN pg_class ON (pg_class.oid = pg_attribute.attrelid) + INNER JOIN pg_type ON (pg_type.oid = pg_class.reltype) + WHERE NOT attisdropped + AND attnum > 0 + GROUP BY pg_type.oid +) +-- Bring together this information, showing all the information which might possibly be required +-- to complete the registration, applying filters to only show the items which relate to the selected +-- types/classes. +SELECT typname, + pg_namespace.nspname, + typtype, + typbasetype, + typelem, + pg_type.oid,`) + if supportsMultirange { + parts = append(parts, ` + COALESCE(multirange.rngtypid, 0) AS rngtypid,`) + } else { + parts = append(parts, ` + 0 AS rngtypid,`) + } + parts = append(parts, ` + COALESCE(pg_range.rngsubtype, 0) AS rngsubtype, + attnames, atttypids + FROM relationships + INNER JOIN pg_type ON (pg_type.oid = relationships.child) + LEFT OUTER JOIN pg_range ON (pg_type.oid = pg_range.rngtypid)`) + if supportsMultirange { + parts = append(parts, ` + LEFT OUTER JOIN pg_range multirange ON (pg_type.oid = multirange.rngmultitypid)`) + } + + parts = append(parts, ` + LEFT OUTER JOIN composite USING (oid) + LEFT OUTER JOIN pg_namespace ON (pg_type.typnamespace = pg_namespace.oid) + WHERE NOT (typtype = 'b' AND typelem = 0)`) + parts = append(parts, ` + GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`) + if supportsMultirange { + parts = append(parts, ` + multirange.rngtypid,`) + } + parts = append(parts, ` + attnames, atttypids + ORDER BY MAX(depth) desc, typname;`) + return strings.Join(parts, "") +} + +type derivedTypeInfo struct { + Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32 + TypeName, Typtype, NspName string + Attnames []string + Atttypids []uint32 +} + +// LoadTypes performs a single (complex) query, returning all the required +// information to register the named types, as well as any other types directly +// or indirectly required to complete the registration. +// The result of this call can be passed into RegisterTypes to complete the process. +func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Type, error) { + m := c.TypeMap() + if len(typeNames) == 0 { + return nil, fmt.Errorf("No type names were supplied.") + } + + // Disregard server version errors. This will result in + // the SQL not support recent structures such as multirange + serverVersion, _ := serverVersion(c) + sql := buildLoadDerivedTypesSQL(serverVersion, typeNames) + rows, err := c.Query(ctx, sql, QueryResultFormats{TextFormatCode}, typeNames) + if err != nil { + return nil, fmt.Errorf("While generating load types query: %w", err) + } + defer rows.Close() + result := make([]*pgtype.Type, 0, 100) + for rows.Next() { + ti := derivedTypeInfo{} + err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids) + if err != nil { + return nil, fmt.Errorf("While scanning type information: %w", err) + } + var type_ *pgtype.Type + switch ti.Typtype { + case "b": // array + dt, ok := m.TypeForOID(ti.Typelem) + if !ok { + return nil, fmt.Errorf("Array element OID %v not registered while loading pgtype %q", ti.Typelem, ti.TypeName) + } + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt}} + case "c": // composite + var fields []pgtype.CompositeCodecField + for i, fieldName := range ti.Attnames { + dt, ok := m.TypeForOID(ti.Atttypids[i]) + if !ok { + return nil, fmt.Errorf("Unknown field for composite type %q: field %q (OID %v) is not already registered.", ti.TypeName, fieldName, ti.Atttypids[i]) + } + fields = append(fields, pgtype.CompositeCodecField{Name: fieldName, Type: dt}) + } + + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.CompositeCodec{Fields: fields}} + case "d": // domain + dt, ok := m.TypeForOID(ti.Typbasetype) + if !ok { + return nil, fmt.Errorf("Domain base type OID %v was not already registered, needed for %q", ti.Typbasetype, ti.TypeName) + } + + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: dt.Codec} + case "e": // enum + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.EnumCodec{}} + case "r": // range + dt, ok := m.TypeForOID(ti.Rngsubtype) + if !ok { + return nil, fmt.Errorf("Range element OID %v was not already registered, needed for %q", ti.Rngsubtype, ti.TypeName) + } + + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.RangeCodec{ElementType: dt}} + case "m": // multirange + dt, ok := m.TypeForOID(ti.Rngtypid) + if !ok { + return nil, fmt.Errorf("Multirange element OID %v was not already registered, needed for %q", ti.Rngtypid, ti.TypeName) + } + + type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.MultirangeCodec{ElementType: dt}} + default: + return nil, fmt.Errorf("Unknown typtype %q was found while registering %q", ti.Typtype, ti.TypeName) + } + + // the type_ is impossible to be null + m.RegisterType(type_) + if ti.NspName != "" { + nspType := &pgtype.Type{Name: ti.NspName + "." + type_.Name, OID: type_.OID, Codec: type_.Codec} + m.RegisterType(nspType) + result = append(result, nspType) + } + result = append(result, type_) + } + + if err := rows.Err(); err != nil { + return nil, fmt.Errorf("While processing rows: %w", err) + } + + return result, nil +} + +// serverVersion returns the postgresql server version. +func serverVersion(c *Conn) (int64, error) { + serverVersionStr := c.PgConn().ParameterStatus("server_version") + serverVersionStr = regexp.MustCompile(`^[0-9]+`).FindString(serverVersionStr) + // if not PostgreSQL do nothing + if serverVersionStr == "" { + return 0, fmt.Errorf("Cannot identify server version in %q", serverVersionStr) + } + + version, err := strconv.ParseInt(serverVersionStr, 10, 64) + if err != nil { + return 0, fmt.Errorf("postgres version parsing failed: %w", err) + } + return version, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/doc.go b/vendor/github.com/jackc/pgx/v5/doc.go new file mode 100644 index 0000000..5e48701 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/doc.go @@ -0,0 +1,220 @@ +// Package pgx is a PostgreSQL database driver. +/* +pgx provides a native PostgreSQL driver and can act as a [database/sql/driver]. The native PostgreSQL interface is similar +to the [database/sql] interface while providing better speed and access to PostgreSQL specific features. Use +[github.com/jackc/pgx/v5/stdlib] to use pgx as a database/sql compatible driver. See that package's documentation for +details. + +Establishing a Connection + +The primary way of establishing a connection is with [pgx.Connect]: + + conn, err := pgx.Connect(context.Background(), os.Getenv("DATABASE_URL")) + +The database connection string can be in URL or key/value format. Both PostgreSQL settings and pgx settings can be +specified here. In addition, a config struct can be created by [ParseConfig] and modified before establishing the +connection with [ConnectConfig] to configure settings such as tracing that cannot be configured with a connection +string. + +Connection Pool + +[*pgx.Conn] represents a single connection to the database and is not concurrency safe. Use package +[github.com/jackc/pgx/v5/pgxpool] for a concurrency safe connection pool. + +Query Interface + +pgx implements [Conn.Query] in the familiar database/sql style. However, pgx provides generic functions such as [CollectRows] and +[ForEachRow] that are a simpler and safer way of processing rows than manually calling defer [Rows.Close], [Rows.Next], +[Rows.Scan], and [Rows.Err]. + +[CollectRows] can be used collect all returned rows into a slice. + + rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 5) + numbers, err := pgx.CollectRows(rows, pgx.RowTo[int32]) + if err != nil { + return err + } + // numbers => [1 2 3 4 5] + +[ForEachRow] can be used to execute a callback function for every row. This is often easier than iterating over rows +directly. + + var sum, n int32 + rows, _ := conn.Query(context.Background(), "select generate_series(1,$1)", 10) + _, err := pgx.ForEachRow(rows, []any{&n}, func() error { + sum += n + return nil + }) + if err != nil { + return err + } + +pgx also implements [Conn.QueryRow] in the same style as database/sql. + + var name string + var weight int64 + err := conn.QueryRow(context.Background(), "select name, weight from widgets where id=$1", 42).Scan(&name, &weight) + if err != nil { + return err + } + +Use [Conn.Exec] to execute a query that does not return a result set. + + commandTag, err := conn.Exec(context.Background(), "delete from widgets where id=$1", 42) + if err != nil { + return err + } + if commandTag.RowsAffected() != 1 { + return errors.New("No row found to delete") + } + +PostgreSQL Data Types + +pgx uses the [pgtype] package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types +directly and is customizable and extendable. User defined data types such as enums, domains, and composite types may +require type registration. See that package's documentation for details. + +PostgreSQL arrays (including results from set-returning aggregates such as array_agg) +can be scanned directly into a matching Go slice. For scalar columns, pass the slice +as the scan destination: + + var ids []int64 + err := conn.QueryRow(ctx, "select array_agg(id) from things").Scan(&ids) + +For a column that is part of a row, combine the slice with the usual row-to-struct +helpers. A struct field of slice type will pick up the array_agg column when +collected via [CollectRows] and [RowToStructByName] (or +[RowToAddrOfStructByPos]): + + type ThingEntry struct { + GroupID int64 + ThingIDs []int64 `db:"thing_ids"` + } + + rows, _ := conn.Query(ctx, + "select group_id, array_agg(thing_id) as thing_ids from things group by group_id") + entries, err := pgx.CollectRows(rows, pgx.RowToStructByName[ThingEntry]) + +Transactions + +Transactions are started by calling [Conn.Begin]. + + tx, err := conn.Begin(context.Background()) + if err != nil { + return err + } + // Rollback is safe to call even if the tx is already closed, so if + // the tx commits successfully, this is a no-op + defer tx.Rollback(context.Background()) + + _, err = tx.Exec(context.Background(), "insert into foo(id) values (1)") + if err != nil { + return err + } + + err = tx.Commit(context.Background()) + if err != nil { + return err + } + +The [Tx] returned from [Conn.Begin] also implements the [Tx.Begin] method. This can be used to implement pseudo nested transactions. +These are internally implemented with savepoints. + +Use [Conn.BeginTx] to control the transaction mode. [Conn.BeginTx] also can be used to ensure a new transaction is created instead of +a pseudo nested transaction. + +[BeginFunc] and [BeginTxFunc] are functions that begin a transaction, execute a function, and commit or rollback the +transaction depending on the return value of the function. These can be simpler and less error prone to use. + + err = pgx.BeginFunc(context.Background(), conn, func(tx pgx.Tx) error { + _, err := tx.Exec(context.Background(), "insert into foo(id) values (1)") + return err + }) + if err != nil { + return err + } + +Prepared Statements + +Prepared statements can be manually created with the [Conn.Prepare] method. However, this is rarely necessary because pgx +includes an automatic statement cache by default. Queries run through the normal [Conn.Query], [Conn.QueryRow], and [Conn.Exec] +functions are automatically prepared on first execution and the prepared statement is reused on subsequent executions. +See [ParseConfig] for information on how to customize or disable the statement cache. + +Copy Protocol + +Use [Conn.CopyFrom] to efficiently insert multiple rows at a time using the PostgreSQL copy protocol. [Conn.CopyFrom] accepts a +[CopyFromSource] interface. If the data is already in a [][]any use [CopyFromRows] to wrap it in a [CopyFromSource] interface. +Or implement [CopyFromSource] to avoid buffering the entire data set in memory. + + rows := [][]any{ + {"John", "Smith", int32(36)}, + {"Jane", "Doe", int32(29)}, + } + + copyCount, err := conn.CopyFrom( + context.Background(), + pgx.Identifier{"people"}, + []string{"first_name", "last_name", "age"}, + pgx.CopyFromRows(rows), + ) + +When you already have a typed array using [CopyFromSlice] can be more convenient. + + rows := []User{ + {"John", "Smith", 36}, + {"Jane", "Doe", 29}, + } + + copyCount, err := conn.CopyFrom( + context.Background(), + pgx.Identifier{"people"}, + []string{"first_name", "last_name", "age"}, + pgx.CopyFromSlice(len(rows), func(i int) ([]any, error) { + return []any{rows[i].FirstName, rows[i].LastName, rows[i].Age}, nil + }), + ) + +CopyFrom can be faster than an insert with as few as 5 rows. + +Listen and Notify + +pgx can listen to the PostgreSQL notification system with the [Conn.WaitForNotification] method. It blocks until a +notification is received or the context is canceled. + + _, err := conn.Exec(context.Background(), "listen channelname") + if err != nil { + return err + } + + notification, err := conn.WaitForNotification(context.Background()) + if err != nil { + return err + } + // do something with notification + + +Tracing and Logging + +pgx supports tracing by setting [ConnConfig.Tracer]. To combine several tracers you can use the [github.com/jackc/pgx/v5/multitracer.Tracer]. + +In addition, the [github.com/jackc/pgx/v5/tracelog] package provides the [github.com/jackc/pgx/v5/tracelog.TraceLog] type which lets a +traditional logger act as a [QueryTracer]. + +For debug tracing of the actual PostgreSQL wire protocol messages see [github.com/jackc/pgx/v5/pgproto3]. + +Lower Level PostgreSQL Functionality + +[github.com/jackc/pgx/v5/pgconn] contains a lower level PostgreSQL driver roughly at the level of libpq. [Conn] is +implemented on top of [pgconn.PgConn]. The [Conn.PgConn] method can be used to access this lower layer. + +PgBouncer + +By default pgx automatically uses prepared statements. Prepared statements are incompatible with PgBouncer. This can be +disabled by setting a different [QueryExecMode] in [ConnConfig.DefaultQueryExecMode]. +*/ +package pgx + +import ( + _ "github.com/jackc/pgx/v5/pgconn" // Just for allowing godoc to resolve "pgconn" +) diff --git a/vendor/github.com/jackc/pgx/v5/extended_query_builder.go b/vendor/github.com/jackc/pgx/v5/extended_query_builder.go new file mode 100644 index 0000000..526b0e9 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/extended_query_builder.go @@ -0,0 +1,146 @@ +package pgx + +import ( + "fmt" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" +) + +// ExtendedQueryBuilder is used to choose the parameter formats, to format the parameters and to choose the result +// formats for an extended query. +type ExtendedQueryBuilder struct { + ParamValues [][]byte + paramValueBytes []byte + ParamFormats []int16 + ResultFormats []int16 +} + +// Build sets ParamValues, ParamFormats, and ResultFormats for use with *PgConn.ExecParams or *PgConn.ExecPrepared. If +// sd is nil then QueryExecModeExec behavior will be used. +func (eqb *ExtendedQueryBuilder) Build(m *pgtype.Map, sd *pgconn.StatementDescription, args []any) error { + eqb.reset() + + if sd == nil { + for i := range args { + err := eqb.appendParam(m, 0, pgtype.TextFormatCode, args[i]) + if err != nil { + err = fmt.Errorf("failed to encode args[%d]: %w", i, err) + return err + } + } + return nil + } + + if len(sd.ParamOIDs) != len(args) { + return fmt.Errorf("mismatched param and argument count") + } + + for i := range args { + err := eqb.appendParam(m, sd.ParamOIDs[i], -1, args[i]) + if err != nil { + err = fmt.Errorf("failed to encode args[%d]: %w", i, err) + return err + } + } + + for i := range sd.Fields { + eqb.appendResultFormat(m.FormatCodeForOID(sd.Fields[i].DataTypeOID)) + } + + return nil +} + +// appendParam appends a parameter to the query. format may be -1 to automatically choose the format. If arg is nil it +// must be an untyped nil. +func (eqb *ExtendedQueryBuilder) appendParam(m *pgtype.Map, oid uint32, format int16, arg any) error { + if format == -1 { + preferredFormat := eqb.chooseParameterFormatCode(m, oid, arg) + preferredErr := eqb.appendParam(m, oid, preferredFormat, arg) + if preferredErr == nil { + return nil + } + + var otherFormat int16 + if preferredFormat == TextFormatCode { + otherFormat = BinaryFormatCode + } else { + otherFormat = TextFormatCode + } + + otherErr := eqb.appendParam(m, oid, otherFormat, arg) + if otherErr == nil { + return nil + } + + return preferredErr // return the error from the preferred format + } + + v, err := eqb.encodeExtendedParamValue(m, oid, format, arg) + if err != nil { + return err + } + + eqb.ParamFormats = append(eqb.ParamFormats, format) + eqb.ParamValues = append(eqb.ParamValues, v) + + return nil +} + +// appendResultFormat appends a result format to the query. +func (eqb *ExtendedQueryBuilder) appendResultFormat(format int16) { + eqb.ResultFormats = append(eqb.ResultFormats, format) +} + +// reset readies eqb to build another query. +func (eqb *ExtendedQueryBuilder) reset() { + eqb.ParamValues = eqb.ParamValues[0:0] + eqb.paramValueBytes = eqb.paramValueBytes[0:0] + eqb.ParamFormats = eqb.ParamFormats[0:0] + eqb.ResultFormats = eqb.ResultFormats[0:0] + + if cap(eqb.ParamValues) > 64 { + eqb.ParamValues = make([][]byte, 0, 64) + } + + if cap(eqb.paramValueBytes) > 256 { + eqb.paramValueBytes = make([]byte, 0, 256) + } + + if cap(eqb.ParamFormats) > 64 { + eqb.ParamFormats = make([]int16, 0, 64) + } + if cap(eqb.ResultFormats) > 64 { + eqb.ResultFormats = make([]int16, 0, 64) + } +} + +func (eqb *ExtendedQueryBuilder) encodeExtendedParamValue(m *pgtype.Map, oid uint32, formatCode int16, arg any) ([]byte, error) { + if eqb.paramValueBytes == nil { + eqb.paramValueBytes = make([]byte, 0, 128) + } + + pos := len(eqb.paramValueBytes) + + buf, err := m.Encode(oid, formatCode, arg, eqb.paramValueBytes) + if err != nil { + return nil, err + } + if buf == nil { + return nil, nil + } + eqb.paramValueBytes = buf + return eqb.paramValueBytes[pos:], nil +} + +// chooseParameterFormatCode determines the correct format code for an +// argument to a prepared statement. It defaults to TextFormatCode if no +// determination can be made. +func (eqb *ExtendedQueryBuilder) chooseParameterFormatCode(m *pgtype.Map, oid uint32, arg any) int16 { + switch arg.(type) { + case string, *string: + return TextFormatCode + } + + return m.FormatCodeForOID(oid) +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go new file mode 100644 index 0000000..abc41f6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/iobufpool/iobufpool.go @@ -0,0 +1,78 @@ +// Package iobufpool implements a global segregated-fit pool of buffers for IO. +// +// It uses *[]byte instead of []byte to avoid the sync.Pool allocation with Put. Unfortunately, using a pointer to avoid +// an allocation is purposely not documented. https://github.com/golang/go/issues/16323 +package iobufpool + +import ( + "math/bits" + "sync" +) + +const minPoolExpOf2 = 8 + +var pools [18]*sync.Pool + +func init() { + for i := range pools { + bufLen := 1 << (minPoolExpOf2 + i) + pools[i] = &sync.Pool{ + New: func() any { + buf := make([]byte, bufLen) + return &buf + }, + } + } +} + +// Get gets a []byte of len size with cap <= size*2. +func Get(size int) *[]byte { + i := getPoolIdx(size) + if i >= len(pools) { + buf := make([]byte, size) + return &buf + } + + ptrBuf := (pools[i].Get().(*[]byte)) + *ptrBuf = (*ptrBuf)[:size] + + return ptrBuf +} + +func getPoolIdx(size int) int { + if size < 2 { + return 0 + } + idx := bits.Len(uint(size-1)) - minPoolExpOf2 + if idx < 0 { + return 0 + } + return idx +} + +// Put returns buf to the pool. +func Put(buf *[]byte) { + i := putPoolIdx(cap(*buf)) + if i < 0 { + return + } + + pools[i].Put(buf) +} + +func putPoolIdx(size int) int { + // Only exact power-of-2 sizes match pool buckets + if size&(size-1) != 0 { + return -1 + } + + // Calculate log2(size) using trailing zeros count + exp := bits.TrailingZeros(uint(size)) + idx := exp - minPoolExpOf2 + + if idx < 0 || idx >= len(pools) { + return -1 + } + + return idx +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/README.md b/vendor/github.com/jackc/pgx/v5/internal/pgio/README.md new file mode 100644 index 0000000..b2fc580 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/README.md @@ -0,0 +1,6 @@ +# pgio + +Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol. + +pgio provides functions for appending integers to a []byte while doing byte +order conversion. diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go b/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go new file mode 100644 index 0000000..ef2dcc7 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/doc.go @@ -0,0 +1,6 @@ +// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol. +/* +pgio provides functions for appending integers to a []byte while doing byte +order conversion. +*/ +package pgio diff --git a/vendor/github.com/jackc/pgx/v5/internal/pgio/write.go b/vendor/github.com/jackc/pgx/v5/internal/pgio/write.go new file mode 100644 index 0000000..3a6700d --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/pgio/write.go @@ -0,0 +1,32 @@ +package pgio + +func AppendUint16(buf []byte, n uint16) []byte { + return append(buf, byte(n>>8), byte(n)) +} + +func AppendUint32(buf []byte, n uint32) []byte { + return append(buf, byte(n>>24), byte(n>>16), byte(n>>8), byte(n)) +} + +func AppendUint64(buf []byte, n uint64) []byte { + return append(buf, + byte(n>>56), byte(n>>48), byte(n>>40), byte(n>>32), + byte(n>>24), byte(n>>16), byte(n>>8), byte(n), + ) +} + +func AppendInt16(buf []byte, n int16) []byte { + return AppendUint16(buf, uint16(n)) +} + +func AppendInt32(buf []byte, n int32) []byte { + return AppendUint32(buf, uint32(n)) +} + +func AppendInt64(buf []byte, n int64) []byte { + return AppendUint64(buf, uint64(n)) +} + +func SetInt32(buf []byte, n int32) { + *(*[4]byte)(buf) = [4]byte{byte(n >> 24), byte(n >> 16), byte(n >> 8), byte(n)} +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/sanitize/benchmark.sh b/vendor/github.com/jackc/pgx/v5/internal/sanitize/benchmark.sh new file mode 100644 index 0000000..b4ee3fe --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/sanitize/benchmark.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash + +current_branch=$(git rev-parse --abbrev-ref HEAD) +if [ "$current_branch" == "HEAD" ]; then + current_branch=$(git rev-parse HEAD) +fi + +restore_branch() { + echo "Restoring original branch/commit: $current_branch" + git checkout "$current_branch" +} +trap restore_branch EXIT + +# Check if there are uncommitted changes +if ! git diff --quiet || ! git diff --cached --quiet; then + echo "There are uncommitted changes. Please commit or stash them before running this script." + exit 1 +fi + +# Ensure that at least one commit argument is passed +if [ "$#" -lt 1 ]; then + echo "Usage: $0 ... " + exit 1 +fi + +commits=("$@") +benchmarks_dir=benchmarks + +if ! mkdir -p "${benchmarks_dir}"; then + echo "Unable to create dir for benchmarks data" + exit 1 +fi + +# Benchmark results +bench_files=() + +# Run benchmark for each listed commit +for i in "${!commits[@]}"; do + commit="${commits[i]}" + git checkout "$commit" || { + echo "Failed to checkout $commit" + exit 1 + } + + # Sanitized commit message + commit_message=$(git log -1 --pretty=format:"%s" | tr -c '[:alnum:]-_' '_') + + # Benchmark data will go there + bench_file="${benchmarks_dir}/${i}_${commit_message}.bench" + + if ! go test -bench=. -count=10 >"$bench_file"; then + echo "Benchmarking failed for commit $commit" + exit 1 + fi + + bench_files+=("$bench_file") +done + +# go install golang.org/x/perf/cmd/benchstat[@latest] +benchstat "${bench_files[@]}" diff --git a/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go new file mode 100644 index 0000000..033a414 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/sanitize/sanitize.go @@ -0,0 +1,541 @@ +package sanitize + +import ( + "bytes" + "encoding/hex" + "fmt" + "math" + "slices" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" +) + +// Part is either a string or an int. A string is raw SQL. An int is a +// argument placeholder. +type Part any + +type Query struct { + Parts []Part +} + +// utf.DecodeRune returns the utf8.RuneError for errors. But that is actually rune U+FFFD -- the unicode replacement +// character. utf8.RuneError is not an error if it is also width 3. +// +// https://github.com/jackc/pgx/issues/1380 +const replacementcharacterwidth = 3 + +const maxBufSize = 16384 // 16 Ki + +var bufPool = &pool[*bytes.Buffer]{ + new: func() *bytes.Buffer { + return &bytes.Buffer{} + }, + reset: func(b *bytes.Buffer) bool { + n := b.Len() + b.Reset() + return n < maxBufSize + }, +} + +var null = []byte("null") + +func (q *Query) Sanitize(args ...any) (string, error) { + argUse := make([]bool, len(args)) + buf := bufPool.get() + defer bufPool.put(buf) + + for _, part := range q.Parts { + switch part := part.(type) { + case string: + buf.WriteString(part) + case int: + argIdx := part - 1 + var p []byte + if argIdx < 0 { + return "", fmt.Errorf("first sql argument must be > 0") + } + + if argIdx >= len(args) { + return "", fmt.Errorf("insufficient arguments") + } + + // Prevent SQL injection via Line Comment Creation + // https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p + buf.WriteByte(' ') + + arg := args[argIdx] + switch arg := arg.(type) { + case nil: + p = null + case int64: + p = strconv.AppendInt(buf.AvailableBuffer(), arg, 10) + case float64: + p = strconv.AppendFloat(buf.AvailableBuffer(), arg, 'f', -1, 64) + case bool: + p = strconv.AppendBool(buf.AvailableBuffer(), arg) + case []byte: + p = QuoteBytes(buf.AvailableBuffer(), arg) + case string: + p = QuoteString(buf.AvailableBuffer(), arg) + case time.Time: + p = arg.Truncate(time.Microsecond). + AppendFormat(buf.AvailableBuffer(), "'2006-01-02 15:04:05.999999999Z07:00:00'") + default: + return "", fmt.Errorf("invalid arg type: %T", arg) + } + argUse[argIdx] = true + + buf.Write(p) + + // Prevent SQL injection via Line Comment Creation + // https://github.com/jackc/pgx/security/advisories/GHSA-m7wr-2xf7-cm9p + buf.WriteByte(' ') + default: + return "", fmt.Errorf("invalid Part type: %T", part) + } + } + + for i, used := range argUse { + if !used { + return "", fmt.Errorf("unused argument: %d", i) + } + } + return buf.String(), nil +} + +func NewQuery(sql string) (*Query, error) { + query := &Query{} + query.init(sql) + + return query, nil +} + +var sqlLexerPool = &pool[*sqlLexer]{ + new: func() *sqlLexer { + return &sqlLexer{} + }, + reset: func(sl *sqlLexer) bool { + *sl = sqlLexer{} + return true + }, +} + +func (q *Query) init(sql string) { + parts := q.Parts[:0] + if parts == nil { + // dirty, but fast heuristic to preallocate for ~90% usecases + n := strings.Count(sql, "$") + strings.Count(sql, "--") + 1 + parts = make([]Part, 0, n) + } + + l := sqlLexerPool.get() + defer sqlLexerPool.put(l) + + l.src = sql + l.stateFn = rawState + l.parts = parts + + for l.stateFn != nil { + l.stateFn = l.stateFn(l) + } + + q.Parts = l.parts +} + +func QuoteString(dst []byte, str string) []byte { + const quote = '\'' + + // Preallocate space for the worst case scenario + dst = slices.Grow(dst, len(str)*2+2) + + // Add opening quote + dst = append(dst, quote) + + // Iterate through the string without allocating + for i := 0; i < len(str); i++ { + if str[i] == quote { + dst = append(dst, quote, quote) + } else { + dst = append(dst, str[i]) + } + } + + // Add closing quote + dst = append(dst, quote) + + return dst +} + +func QuoteBytes(dst, buf []byte) []byte { + if len(buf) == 0 { + return append(dst, `'\x'`...) + } + + // Calculate required length + requiredLen := 3 + hex.EncodedLen(len(buf)) + 1 + + // Ensure dst has enough capacity + if cap(dst)-len(dst) < requiredLen { + newDst := make([]byte, len(dst), len(dst)+requiredLen) + copy(newDst, dst) + dst = newDst + } + + // Record original length and extend slice + origLen := len(dst) + dst = dst[:origLen+requiredLen] + + // Add prefix + dst[origLen] = '\'' + dst[origLen+1] = '\\' + dst[origLen+2] = 'x' + + // Encode bytes directly into dst + hex.Encode(dst[origLen+3:len(dst)-1], buf) + + // Add suffix + dst[len(dst)-1] = '\'' + + return dst +} + +type sqlLexer struct { + src string + start int + pos int + nested int // multiline comment nesting level. + dollarTag string // active tag while inside a dollar-quoted string (may be empty for $$). + stateFn stateFn + parts []Part +} + +type stateFn func(*sqlLexer) stateFn + +func rawState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case 'e', 'E': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '\'' { + l.pos += width + return escapeStringState + } + case '\'': + return singleQuoteState + case '"': + return doubleQuoteState + case '$': + nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:]) + if '0' <= nextRune && nextRune <= '9' { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos-width]) + } + l.start = l.pos + return placeholderState + } + // PostgreSQL dollar-quoted string: $[tag]$...$[tag]$. The $ was + // just consumed; try to match the rest of the opening tag. + // Without this, placeholders embedded inside dollar-quoted + // literals would be incorrectly substituted. + if tagLen, ok := scanDollarQuoteTag(l.src[l.pos:]); ok { + l.dollarTag = l.src[l.pos : l.pos+tagLen] + l.pos += tagLen + 1 // advance past tag and closing '$' + return dollarQuoteState + } + case '-': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '-' { + l.pos += width + return oneLineCommentState + } + case '/': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '*' { + l.pos += width + return multilineCommentState + } + case utf8.RuneError: + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + } +} + +func singleQuoteState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '\'': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '\'' { + return rawState + } + l.pos += width + case utf8.RuneError: + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + } +} + +func doubleQuoteState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '"': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '"' { + return rawState + } + l.pos += width + case utf8.RuneError: + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + } +} + +// placeholderState consumes a placeholder value. The $ must have already has +// already been consumed. The first rune must be a digit. +func placeholderState(l *sqlLexer) stateFn { + num := 0 + + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + if '0' <= r && r <= '9' { + // Clamp rather than silently wrap on pathological input like + // "$92233720368547758070" which would otherwise overflow int and + // could land on a valid args index. Any value above MaxInt32 far + // exceeds any plausible args length, so Sanitize will correctly + // return "insufficient arguments". + if num > (math.MaxInt32-9)/10 { + num = math.MaxInt32 + } else { + num = num*10 + int(r-'0') + } + } else { + l.parts = append(l.parts, num) + l.pos -= width + l.start = l.pos + return rawState + } + } +} + +// dollarQuoteState consumes the body of a PostgreSQL dollar-quoted string +// ($[tag]$...$[tag]$). The opening tag (including its terminating '$') has +// already been consumed. +func dollarQuoteState(l *sqlLexer) stateFn { + closer := "$" + l.dollarTag + "$" + idx := strings.Index(l.src[l.pos:], closer) + if idx < 0 { + // Unterminated — mirror the behavior of other quoted-string states by + // consuming the remaining input into the current part and stopping. + if len(l.src)-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:]) + l.start = len(l.src) + } + l.pos = len(l.src) + return nil + } + l.pos += idx + len(closer) + l.dollarTag = "" + return rawState +} + +// scanDollarQuoteTag checks whether src begins with an optional dollar-quoted +// string tag followed by a closing '$'. src must point just past the opening +// '$'. Returns the byte length of the tag (zero for an anonymous $$) and +// whether a valid tag was found. +// +// Tag grammar matches the PostgreSQL lexer (scan.l): +// +// dolq_start: [A-Za-z_\x80-\xff] +// dolq_cont: [A-Za-z0-9_\x80-\xff] +func scanDollarQuoteTag(src string) (int, bool) { + first := true + for i := 0; i < len(src); { + r, w := utf8.DecodeRuneInString(src[i:]) + if r == '$' { + return i, true + } + if !isDollarTagRune(r, first) { + return 0, false + } + first = false + i += w + } + return 0, false +} + +func isDollarTagRune(r rune, first bool) bool { + switch { + case r == '_': + return true + case 'a' <= r && r <= 'z': + return true + case 'A' <= r && r <= 'Z': + return true + case !first && '0' <= r && r <= '9': + return true + case r >= 0x80 && r != utf8.RuneError: + return true + } + return false +} + +func escapeStringState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '\\': + _, width = utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + case '\'': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '\'' { + return rawState + } + l.pos += width + case utf8.RuneError: + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + } +} + +func oneLineCommentState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '\\': + _, width = utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + case '\n', '\r': + return rawState + case utf8.RuneError: + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + } +} + +func multilineCommentState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '/': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '*' { + l.pos += width + l.nested++ + } + case '*': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '/' { + continue + } + + l.pos += width + if l.nested == 0 { + return rawState + } + l.nested-- + + case utf8.RuneError: + if width != replacementcharacterwidth { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } + } +} + +var queryPool = &pool[*Query]{ + new: func() *Query { + return &Query{} + }, + reset: func(q *Query) bool { + n := len(q.Parts) + q.Parts = q.Parts[:0] + return n < 64 // drop too large queries + }, +} + +// SanitizeSQL replaces placeholder values with args. It quotes and escapes args +// as necessary. This function is only safe when standard_conforming_strings is +// on. +func SanitizeSQL(sql string, args ...any) (string, error) { + query := queryPool.get() + query.init(sql) + defer queryPool.put(query) + + return query.Sanitize(args...) +} + +type pool[E any] struct { + p sync.Pool + new func() E + reset func(E) bool +} + +func (pool *pool[E]) get() E { + v, ok := pool.p.Get().(E) + if !ok { + v = pool.new() + } + + return v +} + +func (p *pool[E]) put(v E) { + if p.reset(v) { + p.p.Put(v) + } +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go new file mode 100644 index 0000000..b677d29 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/lru_cache.go @@ -0,0 +1,187 @@ +package stmtcache + +import ( + "github.com/jackc/pgx/v5/pgconn" +) + +// lruNode is a typed doubly-linked list node with freelist support. +type lruNode struct { + sd *pgconn.StatementDescription + prev *lruNode + next *lruNode +} + +// LRUCache implements Cache with a Least Recently Used (LRU) cache. +type LRUCache struct { + m map[string]*lruNode + head *lruNode + + tail *lruNode + len int + cap int + freelist *lruNode + + invalidStmts []*pgconn.StatementDescription + invalidSet map[string]struct{} +} + +// NewLRUCache creates a new LRUCache. cap is the maximum size of the cache. +func NewLRUCache(cap int) *LRUCache { + head := &lruNode{} + tail := &lruNode{} + head.next = tail + tail.prev = head + + return &LRUCache{ + cap: cap, + m: make(map[string]*lruNode, cap), + head: head, + tail: tail, + invalidSet: make(map[string]struct{}), + } +} + +// Get returns the statement description for sql. Returns nil if not found. +func (c *LRUCache) Get(key string) *pgconn.StatementDescription { + node, ok := c.m[key] + if !ok { + return nil + } + c.moveToFront(node) + return node.sd +} + +// Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache or +// sd.SQL has been invalidated and HandleInvalidated has not been called yet. +func (c *LRUCache) Put(sd *pgconn.StatementDescription) { + if sd.SQL == "" { + panic("cannot store statement description with empty SQL") + } + + if _, present := c.m[sd.SQL]; present { + return + } + + // The statement may have been invalidated but not yet handled. Do not readd it to the cache. + if _, invalidated := c.invalidSet[sd.SQL]; invalidated { + return + } + + if c.len == c.cap { + c.invalidateOldest() + } + + node := c.allocNode() + node.sd = sd + c.insertAfter(c.head, node) + c.m[sd.SQL] = node + c.len++ +} + +// Invalidate invalidates statement description identified by sql. Does nothing if not found. +func (c *LRUCache) Invalidate(sql string) { + node, ok := c.m[sql] + if !ok { + return + } + delete(c.m, sql) + c.invalidStmts = append(c.invalidStmts, node.sd) + c.invalidSet[sql] = struct{}{} + c.unlink(node) + c.len-- + c.freeNode(node) +} + +// InvalidateAll invalidates all statement descriptions. +func (c *LRUCache) InvalidateAll() { + for node := c.head.next; node != c.tail; { + next := node.next + c.invalidStmts = append(c.invalidStmts, node.sd) + c.invalidSet[node.sd.SQL] = struct{}{} + c.freeNode(node) + node = next + } + + clear(c.m) + c.head.next = c.tail + c.tail.prev = c.head + c.len = 0 +} + +// GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. +func (c *LRUCache) GetInvalidated() []*pgconn.StatementDescription { + return c.invalidStmts +} + +// RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a +// call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were +// never seen by the call to GetInvalidated. +func (c *LRUCache) RemoveInvalidated() { + c.invalidStmts = c.invalidStmts[:0] + clear(c.invalidSet) +} + +// Len returns the number of cached prepared statement descriptions. +func (c *LRUCache) Len() int { + return c.len +} + +// Cap returns the maximum number of cached prepared statement descriptions. +func (c *LRUCache) Cap() int { + return c.cap +} + +func (c *LRUCache) invalidateOldest() { + node := c.tail.prev + if node == c.head { + return + } + c.invalidStmts = append(c.invalidStmts, node.sd) + c.invalidSet[node.sd.SQL] = struct{}{} + delete(c.m, node.sd.SQL) + c.unlink(node) + c.len-- + c.freeNode(node) +} + +// List operations - sentinel nodes eliminate nil checks + +func (c *LRUCache) insertAfter(at, node *lruNode) { + node.prev = at + node.next = at.next + at.next.prev = node + at.next = node +} + +func (c *LRUCache) unlink(node *lruNode) { + node.prev.next = node.next + node.next.prev = node.prev +} + +func (c *LRUCache) moveToFront(node *lruNode) { + if node.prev == c.head { + return + } + c.unlink(node) + c.insertAfter(c.head, node) +} + +// Node pool operations - reuse evicted nodes to avoid allocations + +func (c *LRUCache) allocNode() *lruNode { + if c.freelist != nil { + node := c.freelist + c.freelist = node.next + node.next = nil + node.prev = nil + return node + } + return &lruNode{} +} + +func (c *LRUCache) freeNode(node *lruNode) { + node.sd = nil + node.prev = nil + node.next = c.freelist + c.freelist = node +} diff --git a/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go new file mode 100644 index 0000000..d57bdd2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/internal/stmtcache/stmtcache.go @@ -0,0 +1,45 @@ +// Package stmtcache is a cache for statement descriptions. +package stmtcache + +import ( + "crypto/sha256" + "encoding/hex" + + "github.com/jackc/pgx/v5/pgconn" +) + +// StatementName returns a statement name that will be stable for sql across multiple connections and program +// executions. +func StatementName(sql string) string { + digest := sha256.Sum256([]byte(sql)) + return "stmtcache_" + hex.EncodeToString(digest[0:24]) +} + +// Cache caches statement descriptions. +type Cache interface { + // Get returns the statement description for sql. Returns nil if not found. + Get(sql string) *pgconn.StatementDescription + + // Put stores sd in the cache. Put panics if sd.SQL is "". Put does nothing if sd.SQL already exists in the cache. + Put(sd *pgconn.StatementDescription) + + // Invalidate invalidates statement description identified by sql. Does nothing if not found. + Invalidate(sql string) + + // InvalidateAll invalidates all statement descriptions. + InvalidateAll() + + // GetInvalidated returns a slice of all statement descriptions invalidated since the last call to RemoveInvalidated. + GetInvalidated() []*pgconn.StatementDescription + + // RemoveInvalidated removes all invalidated statement descriptions. No other calls to Cache must be made between a + // call to GetInvalidated and RemoveInvalidated or RemoveInvalidated may remove statement descriptions that were + // never seen by the call to GetInvalidated. + RemoveInvalidated() + + // Len returns the number of cached prepared statement descriptions. + Len() int + + // Cap returns the maximum number of cached prepared statement descriptions. + Cap() int +} diff --git a/vendor/github.com/jackc/pgx/v5/large_objects.go b/vendor/github.com/jackc/pgx/v5/large_objects.go new file mode 100644 index 0000000..9d21afd --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/large_objects.go @@ -0,0 +1,161 @@ +package pgx + +import ( + "context" + "errors" + "io" + + "github.com/jackc/pgx/v5/pgtype" +) + +// The PostgreSQL wire protocol has a limit of 1 GB - 1 per message. See definition of +// PQ_LARGE_MESSAGE_LIMIT in the PostgreSQL source code. To allow for the other data +// in the message,maxLargeObjectMessageLength should be no larger than 1 GB - 1 KB. +var maxLargeObjectMessageLength = 1024*1024*1024 - 1024 + +// LargeObjects is a structure used to access the large objects API. It is only valid within the transaction where it +// was created. +// +// For more details see: http://www.postgresql.org/docs/current/static/largeobjects.html +type LargeObjects struct { + tx Tx +} + +type LargeObjectMode int32 + +const ( + LargeObjectModeWrite LargeObjectMode = 0x20000 + LargeObjectModeRead LargeObjectMode = 0x40000 +) + +// Create creates a new large object. If oid is zero, the server assigns an unused OID. +func (o *LargeObjects) Create(ctx context.Context, oid uint32) (uint32, error) { + err := o.tx.QueryRow(ctx, "select lo_create($1)", oid).Scan(&oid) + return oid, err +} + +// Open opens an existing large object with the given mode. ctx will also be used for all operations on the opened large +// object. +func (o *LargeObjects) Open(ctx context.Context, oid uint32, mode LargeObjectMode) (*LargeObject, error) { + var fd int32 + err := o.tx.QueryRow(ctx, "select lo_open($1, $2)", oid, mode).Scan(&fd) + if err != nil { + return nil, err + } + return &LargeObject{fd: fd, tx: o.tx, ctx: ctx}, nil +} + +// Unlink removes a large object from the database. +func (o *LargeObjects) Unlink(ctx context.Context, oid uint32) error { + var result int32 + err := o.tx.QueryRow(ctx, "select lo_unlink($1)", oid).Scan(&result) + if err != nil { + return err + } + + if result != 1 { + return errors.New("failed to remove large object") + } + + return nil +} + +// A LargeObject is a large object stored on the server. It is only valid within the transaction that it was initialized +// in. It uses the context it was initialized with for all operations. It implements these interfaces: +// +// io.Writer +// io.Reader +// io.Seeker +// io.Closer +type LargeObject struct { + ctx context.Context + tx Tx + fd int32 +} + +// Write writes p to the large object and returns the number of bytes written and an error if not all of p was written. +func (o *LargeObject) Write(p []byte) (int, error) { + nTotal := 0 + for { + expected := len(p) - nTotal + if expected == 0 { + break + } else if expected > maxLargeObjectMessageLength { + expected = maxLargeObjectMessageLength + } + + var n int + err := o.tx.QueryRow(o.ctx, "select lowrite($1, $2)", o.fd, p[nTotal:nTotal+expected]).Scan(&n) + if err != nil { + return nTotal, err + } + + if n < 0 { + return nTotal, errors.New("failed to write to large object") + } + + nTotal += n + + if n < expected { + return nTotal, errors.New("short write to large object") + } else if n > expected { + return nTotal, errors.New("invalid write to large object") + } + } + + return nTotal, nil +} + +// Read reads up to len(p) bytes into p returning the number of bytes read. +func (o *LargeObject) Read(p []byte) (int, error) { + nTotal := 0 + for { + expected := len(p) - nTotal + if expected == 0 { + break + } else if expected > maxLargeObjectMessageLength { + expected = maxLargeObjectMessageLength + } + + res := pgtype.PreallocBytes(p[nTotal:]) + err := o.tx.QueryRow(o.ctx, "select loread($1, $2)", o.fd, expected).Scan(&res) + // We compute expected so that it always fits into p, so it should never happen + // that PreallocBytes's ScanBytes had to allocate a new slice. + nTotal += len(res) + if err != nil { + return nTotal, err + } + + if len(res) < expected { + return nTotal, io.EOF + } else if len(res) > expected { + return nTotal, errors.New("invalid read of large object") + } + } + + return nTotal, nil +} + +// Seek moves the current location pointer to the new location specified by offset. +func (o *LargeObject) Seek(offset int64, whence int) (n int64, err error) { + err = o.tx.QueryRow(o.ctx, "select lo_lseek64($1, $2, $3)", o.fd, offset, whence).Scan(&n) + return n, err +} + +// Tell returns the current read or write location of the large object descriptor. +func (o *LargeObject) Tell() (n int64, err error) { + err = o.tx.QueryRow(o.ctx, "select lo_tell64($1)", o.fd).Scan(&n) + return n, err +} + +// Truncate the large object to size. +func (o *LargeObject) Truncate(size int64) (err error) { + _, err = o.tx.Exec(o.ctx, "select lo_truncate64($1, $2)", o.fd, size) + return err +} + +// Close the large object descriptor. +func (o *LargeObject) Close() error { + _, err := o.tx.Exec(o.ctx, "select lo_close($1)", o.fd) + return err +} diff --git a/vendor/github.com/jackc/pgx/v5/mise.toml b/vendor/github.com/jackc/pgx/v5/mise.toml new file mode 100644 index 0000000..78610d4 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/mise.toml @@ -0,0 +1,8 @@ +[tools] +go = '1.26.3' +"go:github.com/go-critic/go-critic/cmd/gocritic" = "latest" +"go:github.com/gordonklaus/ineffassign" = "latest" +"go:github.com/mdempsky/unconvert" = "latest" +"go:golang.org/x/tools/cmd/goimports" = "latest" +"go:mvdan.cc/gofumpt" = "latest" +ruby = '4.0.4' diff --git a/vendor/github.com/jackc/pgx/v5/named_args.go b/vendor/github.com/jackc/pgx/v5/named_args.go new file mode 100644 index 0000000..1300c91 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/named_args.go @@ -0,0 +1,410 @@ +package pgx + +import ( + "context" + "fmt" + "reflect" + "strconv" + "strings" + "unicode/utf8" +) + +// NamedArgs can be used as the first argument to a query method. It will replace every '@' named placeholder with a '$' +// ordinal placeholder and construct the appropriate arguments. +// +// For example, the following two queries are equivalent: +// +// conn.Query(ctx, "select * from widgets where foo = @foo and bar = @bar", pgx.NamedArgs{"foo": 1, "bar": 2}) +// conn.Query(ctx, "select * from widgets where foo = $1 and bar = $2", 1, 2) +// +// Named placeholders are case sensitive and must start with a letter or underscore. Subsequent characters can be +// letters, numbers, or underscores. + +type NamedArgs map[string]any + +// RewriteQuery implements the QueryRewriter interface. +func (na NamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) { + return rewriteQuery(na, sql, false) +} + +// StrictNamedArgs can be used in the same way as NamedArgs, but provided arguments are also checked to include all +// named arguments that the sql query uses, and no extra arguments. +type StrictNamedArgs map[string]any + +// RewriteQuery implements the QueryRewriter interface. +func (sna StrictNamedArgs) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) { + return rewriteQuery(sna, sql, true) +} + +type errorQueryRewriter struct { + err error +} + +func (r errorQueryRewriter) RewriteQuery(ctx context.Context, conn *Conn, sql string, args []any) (newSQL string, newArgs []any, err error) { + return "", nil, r.err +} + +// StructArgs converts exported fields of a struct into a QueryRewriter so it can +// be used as the first argument to a query method (e.g. "where id=@id"). +// +// Field names are taken from the `db` struct tag if present. Tag values may +// include comma-separated options (e.g. `db:"id,omitempty"`). A `db:"-"` field is +// ignored. If no `db` tag is present, the Go field name is used. +// +// sa may be a struct or a pointer to a struct. +func StructArgs(sa any) QueryRewriter { + args, err := structArgs(sa) + if err != nil { + return errorQueryRewriter{err: err} + } + return NamedArgs(args) +} + +// StrictStructArgs is like StructArgs but uses StrictNamedArgs rewriting +// semantics (i.e. errors if the SQL query references missing arguments or if +// extra arguments are provided). +func StrictStructArgs(sa any) QueryRewriter { + args, err := structArgs(sa) + if err != nil { + return errorQueryRewriter{err: err} + } + return StrictNamedArgs(args) +} + +func structArgs(sa any) (map[string]any, error) { + if sa == nil { + return nil, fmt.Errorf("StructArgs requires a struct or pointer to struct, got nil") + } + + v := reflect.ValueOf(sa) + t := v.Type() + + if t.Kind() == reflect.Pointer { + if v.IsNil() { + return nil, fmt.Errorf("StructArgs requires a non-nil pointer to struct") + } + v = v.Elem() + t = v.Type() + } + + if t.Kind() != reflect.Struct { + return nil, fmt.Errorf("StructArgs requires a struct or pointer to struct, got %s", t) + } + + out := make(map[string]any, t.NumField()) + for i := 0; i < t.NumField(); i++ { + sf := t.Field(i) + + // Ignore unexported fields. + if sf.PkgPath != "" { + continue + } + + key, ok, err := dbTagKey(sf) + if err != nil { + return nil, err + } + if !ok { + continue + } + + if _, exists := out[key]; exists { + return nil, fmt.Errorf("duplicate StructArgs key %q", key) + } + + out[key] = v.Field(i).Interface() + } + + return out, nil +} + +// dbTagKey derives the named-argument key for a struct field. Tag parsing matches +// RowToStructByName* in rows.go (structTagKey, Lookup, comma options, db:"-"). +// Anonymous embedded structs are skipped without flattening (unlike row scanning). +func dbTagKey(sf reflect.StructField) (key string, ok bool, err error) { + if sf.Anonymous { + ft := sf.Type + if ft.Kind() == reflect.Pointer { + ft = ft.Elem() + } + if ft.Kind() == reflect.Struct { + return "", false, nil + } + } + + dbTag, dbTagPresent := sf.Tag.Lookup(structTagKey) + if dbTagPresent { + dbTag, _, _ = strings.Cut(dbTag, ",") + } + if dbTag == "-" { + return "", false, nil + } + if dbTagPresent { + if dbTag == "" { + return "", false, fmt.Errorf("field %s has empty `%s` tag", sf.Name, structTagKey) + } + return dbTag, true, nil + } + + return sf.Name, true, nil +} + +type namedArg string + +type sqlLexer struct { + src string + start int + pos int + nested int // multiline comment nesting level. + stateFn stateFn + parts []any + + nameToOrdinal map[namedArg]int +} + +type stateFn func(*sqlLexer) stateFn + +func rewriteQuery(na map[string]any, sql string, isStrict bool) (newSQL string, newArgs []any, err error) { + l := &sqlLexer{ + src: sql, + stateFn: rawState, + nameToOrdinal: make(map[namedArg]int, len(na)), + } + + for l.stateFn != nil { + l.stateFn = l.stateFn(l) + } + + sb := strings.Builder{} + for _, p := range l.parts { + switch p := p.(type) { + case string: + sb.WriteString(p) + case namedArg: + sb.WriteRune('$') + sb.WriteString(strconv.Itoa(l.nameToOrdinal[p])) + } + } + + newArgs = make([]any, len(l.nameToOrdinal)) + for name, ordinal := range l.nameToOrdinal { + var found bool + newArgs[ordinal-1], found = na[string(name)] + if isStrict && !found { + return "", nil, fmt.Errorf("argument %s found in sql query but not present in StrictNamedArgs", name) + } + } + + if isStrict { + for name := range na { + if _, found := l.nameToOrdinal[namedArg(name)]; !found { + return "", nil, fmt.Errorf("argument %s of StrictNamedArgs not found in sql query", name) + } + } + } + + return sb.String(), newArgs, nil +} + +func rawState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case 'e', 'E': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '\'' { + l.pos += width + return escapeStringState + } + case '\'': + return singleQuoteState + case '"': + return doubleQuoteState + case '@': + nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:]) + if isLetter(nextRune) || nextRune == '_' { + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos-width]) + } + l.start = l.pos + return namedArgState + } + case '-': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '-' { + l.pos += width + return oneLineCommentState + } + case '/': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '*' { + l.pos += width + return multilineCommentState + } + case utf8.RuneError: + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } +} + +func isLetter(r rune) bool { + return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') +} + +func namedArgState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + if r == utf8.RuneError { + if l.pos-l.start > 0 { + na := namedArg(l.src[l.start:l.pos]) + if _, found := l.nameToOrdinal[na]; !found { + l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1 + } + l.parts = append(l.parts, na) + l.start = l.pos + } + return nil + } else if !(isLetter(r) || (r >= '0' && r <= '9') || r == '_') { + l.pos -= width + na := namedArg(l.src[l.start:l.pos]) + if _, found := l.nameToOrdinal[na]; !found { + l.nameToOrdinal[na] = len(l.nameToOrdinal) + 1 + } + l.parts = append(l.parts, na) + l.start = l.pos + return rawState + } + } +} + +func singleQuoteState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '\'': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '\'' { + return rawState + } + l.pos += width + case utf8.RuneError: + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } +} + +func doubleQuoteState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '"': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '"' { + return rawState + } + l.pos += width + case utf8.RuneError: + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } +} + +func escapeStringState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '\\': + _, width = utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + case '\'': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '\'' { + return rawState + } + l.pos += width + case utf8.RuneError: + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } +} + +func oneLineCommentState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '\\': + _, width = utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + case '\n', '\r': + return rawState + case utf8.RuneError: + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } +} + +func multilineCommentState(l *sqlLexer) stateFn { + for { + r, width := utf8.DecodeRuneInString(l.src[l.pos:]) + l.pos += width + + switch r { + case '/': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune == '*' { + l.pos += width + l.nested++ + } + case '*': + nextRune, width := utf8.DecodeRuneInString(l.src[l.pos:]) + if nextRune != '/' { + continue + } + + l.pos += width + if l.nested == 0 { + return rawState + } + l.nested-- + + case utf8.RuneError: + if l.pos-l.start > 0 { + l.parts = append(l.parts, l.src[l.start:l.pos]) + l.start = l.pos + } + return nil + } + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/README.md b/vendor/github.com/jackc/pgx/v5/pgconn/README.md new file mode 100644 index 0000000..1fe15c2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/README.md @@ -0,0 +1,29 @@ +# pgconn + +Package pgconn is a low-level PostgreSQL database driver. It operates at nearly the same level as the C library libpq. +It is primarily intended to serve as the foundation for higher level libraries such as https://github.com/jackc/pgx. +Applications should handle normal queries with a higher level library and only use pgconn directly when required for +low-level access to PostgreSQL functionality. + +## Example Usage + +```go +pgConn, err := pgconn.Connect(context.Background(), os.Getenv("DATABASE_URL")) +if err != nil { + log.Fatalln("pgconn failed to connect:", err) +} +defer pgConn.Close(context.Background()) + +result := pgConn.ExecParams(context.Background(), "SELECT email FROM users WHERE id=$1", [][]byte{[]byte("123")}, nil, nil, nil) +for result.NextRow() { + fmt.Println("User 123 has email:", string(result.Values()[0])) +} +_, err = result.Close() +if err != nil { + log.Fatalln("failed reading result:", err) +} +``` + +## Testing + +See CONTRIBUTING.md for setup instructions. diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go b/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go new file mode 100644 index 0000000..991f658 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/auth_oauth.go @@ -0,0 +1,67 @@ +package pgconn + +import ( + "context" + "encoding/json" + "errors" + "fmt" + + "github.com/jackc/pgx/v5/pgproto3" +) + +func (c *PgConn) oauthAuth(ctx context.Context) error { + if c.config.OAuthTokenProvider == nil { + return errors.New("OAuth authentication required but no token provider configured") + } + + token, err := c.config.OAuthTokenProvider(ctx) + if err != nil { + return fmt.Errorf("failed to obtain OAuth token: %w", err) + } + + // https://www.rfc-editor.org/rfc/rfc7628.html#section-3.1 + initialResponse := []byte("n,,\x01auth=Bearer " + token + "\x01\x01") + + saslInitialResponse := &pgproto3.SASLInitialResponse{ + AuthMechanism: "OAUTHBEARER", + Data: initialResponse, + } + c.frontend.Send(saslInitialResponse) + err = c.flushWithPotentialWriteReadDeadlock() + if err != nil { + return err + } + + msg, err := c.receiveMessage() + if err != nil { + return err + } + + switch m := msg.(type) { + case *pgproto3.AuthenticationOk: + return nil + case *pgproto3.AuthenticationSASLContinue: + // Server sent error response in SASL continue + // https://www.rfc-editor.org/rfc/rfc7628.html#section-3.2.2 + // https://www.rfc-editor.org/rfc/rfc7628.html#section-3.2.3 + errResponse := struct { + Status string `json:"status"` + Scope string `json:"scope"` + OpenIDConfiguration string `json:"openid-configuration"` + }{} + err := json.Unmarshal(m.Data, &errResponse) + if err != nil { + return fmt.Errorf("invalid OAuth error response from server: %w", err) + } + + // Per RFC 7628 section 3.2.3, we should send a SASLResponse which only contains \x01. + // However, since the connection will be closed anyway, we can skip this + return fmt.Errorf("OAuth authentication failed: %s", errResponse.Status) + + case *pgproto3.ErrorResponse: + return ErrorResponseToPgError(m) + + default: + return fmt.Errorf("unexpected message type during OAuth auth: %T", msg) + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go b/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go new file mode 100644 index 0000000..aeaf8cb --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/auth_scram.go @@ -0,0 +1,407 @@ +// SCRAM-SHA-256 and SCRAM-SHA-256-PLUS authentication +// +// Resources: +// https://tools.ietf.org/html/rfc5802 +// https://tools.ietf.org/html/rfc5929 +// https://tools.ietf.org/html/rfc8265 +// https://www.postgresql.org/docs/current/sasl-authentication.html +// +// Inspiration drawn from other implementations: +// https://github.com/lib/pq/pull/608 +// https://github.com/lib/pq/pull/788 +// https://github.com/lib/pq/pull/833 + +package pgconn + +import ( + "bytes" + "crypto/hmac" + "crypto/pbkdf2" + "crypto/rand" + "crypto/sha256" + "crypto/sha512" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "errors" + "fmt" + "hash" + "slices" + "strconv" + + "github.com/jackc/pgx/v5/pgproto3" + "golang.org/x/text/secure/precis" +) + +const ( + clientNonceLen = 18 + scramSHA256Name = "SCRAM-SHA-256" + scramSHA256PlusName = "SCRAM-SHA-256-PLUS" +) + +// Perform SCRAM authentication. +func (c *PgConn) scramAuth(serverAuthMechanisms []string) error { + sc, err := newScramClient(serverAuthMechanisms, c.config.Password) + if err != nil { + return err + } + + serverHasPlus := slices.Contains(sc.serverAuthMechanisms, scramSHA256PlusName) + if c.config.ChannelBinding == "require" && !serverHasPlus { + return errors.New("channel binding required but server does not support SCRAM-SHA-256-PLUS") + } + + // If we have a TLS connection and channel binding is not disabled, attempt to + // extract the server certificate hash for tls-server-end-point channel binding. + if tlsConn, ok := c.conn.(*tls.Conn); ok && c.config.ChannelBinding != "disable" { + certHash, err := getTLSCertificateHash(tlsConn) + if err != nil && c.config.ChannelBinding == "require" { + return fmt.Errorf("channel binding required but failed to get server certificate hash: %w", err) + } + + // Upgrade to SCRAM-SHA-256-PLUS if we have binding data and the server supports it. + if certHash != nil && serverHasPlus { + sc.authMechanism = scramSHA256PlusName + } + + sc.channelBindingData = certHash + sc.hasTLS = true + } + + if c.config.ChannelBinding == "require" && sc.channelBindingData == nil { + return errors.New("channel binding required but channel binding data is not available") + } + + // Send client-first-message in a SASLInitialResponse + saslInitialResponse := &pgproto3.SASLInitialResponse{ + AuthMechanism: sc.authMechanism, + Data: sc.clientFirstMessage(), + } + c.frontend.Send(saslInitialResponse) + err = c.flushWithPotentialWriteReadDeadlock() + if err != nil { + return err + } + + // Receive server-first-message payload in an AuthenticationSASLContinue. + saslContinue, err := c.rxSASLContinue() + if err != nil { + return err + } + err = sc.recvServerFirstMessage(saslContinue.Data) + if err != nil { + return err + } + + // Send client-final-message in a SASLResponse + saslResponse := &pgproto3.SASLResponse{ + Data: []byte(sc.clientFinalMessage()), + } + c.frontend.Send(saslResponse) + err = c.flushWithPotentialWriteReadDeadlock() + if err != nil { + return err + } + + // Receive server-final-message payload in an AuthenticationSASLFinal. + saslFinal, err := c.rxSASLFinal() + if err != nil { + return err + } + return sc.recvServerFinalMessage(saslFinal.Data) +} + +func (c *PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error) { + msg, err := c.receiveMessage() + if err != nil { + return nil, err + } + switch m := msg.(type) { + case *pgproto3.AuthenticationSASLContinue: + return m, nil + case *pgproto3.ErrorResponse: + return nil, ErrorResponseToPgError(m) + } + + return nil, fmt.Errorf("expected AuthenticationSASLContinue message but received unexpected message %T", msg) +} + +func (c *PgConn) rxSASLFinal() (*pgproto3.AuthenticationSASLFinal, error) { + msg, err := c.receiveMessage() + if err != nil { + return nil, err + } + switch m := msg.(type) { + case *pgproto3.AuthenticationSASLFinal: + return m, nil + case *pgproto3.ErrorResponse: + return nil, ErrorResponseToPgError(m) + } + + return nil, fmt.Errorf("expected AuthenticationSASLFinal message but received unexpected message %T", msg) +} + +type scramClient struct { + serverAuthMechanisms []string + password string + clientNonce []byte + + // authMechanism is the selected SASL mechanism for the client. Must be + // either SCRAM-SHA-256 (default) or SCRAM-SHA-256-PLUS. + // + // Upgraded to SCRAM-SHA-256-PLUS during authentication when channel binding + // is not disabled, channel binding data is available (TLS connection with + // an obtainable server certificate hash) and the server advertises + // SCRAM-SHA-256-PLUS. + authMechanism string + + // hasTLS indicates whether the connection is using TLS. This is + // needed because the GS2 header must distinguish between a client that + // supports channel binding but the server does not ("y,,") versus one + // that does not support it at all ("n,,"). + hasTLS bool + + // channelBindingData is the hash of the server's TLS certificate, computed + // per the tls-server-end-point channel binding type (RFC 5929). Used as + // the binding input in SCRAM-SHA-256-PLUS. nil when not in use. + channelBindingData []byte + + clientFirstMessageBare []byte + clientGS2Header []byte + + serverFirstMessage []byte + clientAndServerNonce []byte + salt []byte + iterations int + + saltedPassword []byte + authMessage []byte +} + +func newScramClient(serverAuthMechanisms []string, password string) (*scramClient, error) { + sc := &scramClient{ + serverAuthMechanisms: serverAuthMechanisms, + authMechanism: scramSHA256Name, + } + + // Ensure the server supports SCRAM-SHA-256. SCRAM-SHA-256-PLUS is the + // channel binding variant and is only advertised when the server supports + // SSL. PostgreSQL always advertises the base SCRAM-SHA-256 mechanism + // regardless of SSL. + if !slices.Contains(sc.serverAuthMechanisms, scramSHA256Name) { + return nil, errors.New("server does not support SCRAM-SHA-256") + } + + // precis.OpaqueString is equivalent to SASLprep for password. + var err error + sc.password, err = precis.OpaqueString.String(password) + if err != nil { + // PostgreSQL allows passwords invalid according to SCRAM / SASLprep. + sc.password = password + } + + buf := make([]byte, clientNonceLen) + _, err = rand.Read(buf) + if err != nil { + return nil, err + } + sc.clientNonce = make([]byte, base64.RawStdEncoding.EncodedLen(len(buf))) + base64.RawStdEncoding.Encode(sc.clientNonce, buf) + + return sc, nil +} + +func (sc *scramClient) clientFirstMessage() []byte { + // The client-first-message is the GS2 header concatenated with the bare + // message (username + client nonce). The GS2 header communicates the + // client's channel binding capability to the server: + // + // "n,," - client is not using TLS (channel binding not possible) + // "y,," - client is using TLS but channel binding is not + // in use (e.g., server did not advertise SCRAM-SHA-256-PLUS + // or the server certificate hash was not obtainable) + // "p=tls-server-end-point,," - channel binding is active via SCRAM-SHA-256-PLUS + // + // See: + // https://www.rfc-editor.org/rfc/rfc5802#section-6 + // https://www.rfc-editor.org/rfc/rfc5929#section-4 + // https://www.postgresql.org/docs/current/sasl-authentication.html#SASL-SCRAM-SHA-256 + + sc.clientFirstMessageBare = fmt.Appendf(nil, "n=,r=%s", sc.clientNonce) + + switch { + case sc.authMechanism == scramSHA256PlusName: + sc.clientGS2Header = []byte("p=tls-server-end-point,,") + case sc.hasTLS: + sc.clientGS2Header = []byte("y,,") + default: + sc.clientGS2Header = []byte("n,,") + } + + return append(sc.clientGS2Header, sc.clientFirstMessageBare...) +} + +func (sc *scramClient) recvServerFirstMessage(serverFirstMessage []byte) error { + sc.serverFirstMessage = serverFirstMessage + buf := serverFirstMessage + if !bytes.HasPrefix(buf, []byte("r=")) { + return errors.New("invalid SCRAM server-first-message received from server: did not include r=") + } + buf = buf[2:] + + idx := bytes.IndexByte(buf, ',') + if idx == -1 { + return errors.New("invalid SCRAM server-first-message received from server: did not include s=") + } + sc.clientAndServerNonce = buf[:idx] + buf = buf[idx+1:] + + if !bytes.HasPrefix(buf, []byte("s=")) { + return errors.New("invalid SCRAM server-first-message received from server: did not include s=") + } + buf = buf[2:] + + idx = bytes.IndexByte(buf, ',') + if idx == -1 { + return errors.New("invalid SCRAM server-first-message received from server: did not include i=") + } + saltStr := buf[:idx] + buf = buf[idx+1:] + + if !bytes.HasPrefix(buf, []byte("i=")) { + return errors.New("invalid SCRAM server-first-message received from server: did not include i=") + } + buf = buf[2:] + iterationsStr := buf + + var err error + sc.salt, err = base64.StdEncoding.DecodeString(string(saltStr)) + if err != nil { + return fmt.Errorf("invalid SCRAM salt received from server: %w", err) + } + + sc.iterations, err = strconv.Atoi(string(iterationsStr)) + if err != nil || sc.iterations <= 0 { + return fmt.Errorf("invalid SCRAM iteration count received from server: %w", err) + } + // Bound server-supplied iteration count to prevent a malicious server from forcing the client + // to spend unbounded CPU in PBKDF2. PostgreSQL's scram_iterations defaults to 4096; this ceiling + // is ~2500x that. + const maxScramIterations = 10_000_000 + if sc.iterations > maxScramIterations { + return fmt.Errorf("SCRAM iteration count from server too high: %d (max %d)", sc.iterations, maxScramIterations) + } + + if !bytes.HasPrefix(sc.clientAndServerNonce, sc.clientNonce) { + return errors.New("invalid SCRAM nonce: did not start with client nonce") + } + + if len(sc.clientAndServerNonce) <= len(sc.clientNonce) { + return errors.New("invalid SCRAM nonce: did not include server nonce") + } + + return nil +} + +func (sc *scramClient) clientFinalMessage() string { + // The c= attribute carries the base64-encoded channel binding input. + // + // Without channel binding this is just the GS2 header alone ("biws" for + // "n,," or "eSws" for "y,,"). + // + // With channel binding, this is the GS2 header with the channel binding data + // (certificate hash) appended. + channelBindInput := sc.clientGS2Header + if sc.authMechanism == scramSHA256PlusName { + channelBindInput = slices.Concat(sc.clientGS2Header, sc.channelBindingData) + } + channelBindingEncoded := base64.StdEncoding.EncodeToString(channelBindInput) + clientFinalMessageWithoutProof := fmt.Appendf(nil, "c=%s,r=%s", channelBindingEncoded, sc.clientAndServerNonce) + + var err error + sc.saltedPassword, err = pbkdf2.Key(sha256.New, sc.password, sc.salt, sc.iterations, 32) + if err != nil { + panic(err) // This should never happen. + } + sc.authMessage = bytes.Join([][]byte{sc.clientFirstMessageBare, sc.serverFirstMessage, clientFinalMessageWithoutProof}, []byte(",")) + + clientProof := computeClientProof(sc.saltedPassword, sc.authMessage) + + return fmt.Sprintf("%s,p=%s", clientFinalMessageWithoutProof, clientProof) +} + +func (sc *scramClient) recvServerFinalMessage(serverFinalMessage []byte) error { + if !bytes.HasPrefix(serverFinalMessage, []byte("v=")) { + return errors.New("invalid SCRAM server-final-message received from server") + } + + serverSignature := serverFinalMessage[2:] + + if !hmac.Equal(serverSignature, computeServerSignature(sc.saltedPassword, sc.authMessage)) { + return errors.New("invalid SCRAM ServerSignature received from server") + } + + return nil +} + +func computeHMAC(key, msg []byte) []byte { + mac := hmac.New(sha256.New, key) + mac.Write(msg) + return mac.Sum(nil) +} + +func computeClientProof(saltedPassword, authMessage []byte) []byte { + clientKey := computeHMAC(saltedPassword, []byte("Client Key")) + storedKey := sha256.Sum256(clientKey) + clientSignature := computeHMAC(storedKey[:], authMessage) + + clientProof := make([]byte, len(clientSignature)) + for i := range clientSignature { + clientProof[i] = clientKey[i] ^ clientSignature[i] + } + + buf := make([]byte, base64.StdEncoding.EncodedLen(len(clientProof))) + base64.StdEncoding.Encode(buf, clientProof) + return buf +} + +func computeServerSignature(saltedPassword, authMessage []byte) []byte { + serverKey := computeHMAC(saltedPassword, []byte("Server Key")) + serverSignature := computeHMAC(serverKey, authMessage) + buf := make([]byte, base64.StdEncoding.EncodedLen(len(serverSignature))) + base64.StdEncoding.Encode(buf, serverSignature) + return buf +} + +// Get the server certificate hash for SCRAM channel binding type +// tls-server-end-point. +func getTLSCertificateHash(conn *tls.Conn) ([]byte, error) { + state := conn.ConnectionState() + if len(state.PeerCertificates) == 0 { + return nil, errors.New("no peer certificates for channel binding") + } + + cert := state.PeerCertificates[0] + + // Per RFC 5929 section 4.1: If the certificate's signatureAlgorithm uses + // MD5 or SHA-1, use SHA-256. Otherwise use the hash from the signature + // algorithm. + // + // See: https://www.rfc-editor.org/rfc/rfc5929.html#section-4.1 + var h hash.Hash + switch cert.SignatureAlgorithm { + case x509.MD5WithRSA, x509.SHA1WithRSA, x509.ECDSAWithSHA1: + h = sha256.New() + case x509.SHA256WithRSA, x509.SHA256WithRSAPSS, x509.ECDSAWithSHA256: + h = sha256.New() + case x509.SHA384WithRSA, x509.SHA384WithRSAPSS, x509.ECDSAWithSHA384: + h = sha512.New384() + case x509.SHA512WithRSA, x509.SHA512WithRSAPSS, x509.ECDSAWithSHA512: + h = sha512.New() + default: + return nil, fmt.Errorf("tls-server-end-point channel binding is undefined for certificate signature algorithm %v", cert.SignatureAlgorithm) + } + + h.Write(cert.Raw) + return h.Sum(nil), nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/config.go b/vendor/github.com/jackc/pgx/v5/pgconn/config.go new file mode 100644 index 0000000..eec7de6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/config.go @@ -0,0 +1,1088 @@ +package pgconn + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "maps" + "math" + "net" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/jackc/pgpassfile" + "github.com/jackc/pgservicefile" + "github.com/jackc/pgx/v5/pgconn/ctxwatch" + "github.com/jackc/pgx/v5/pgproto3" +) + +type ( + AfterConnectFunc func(ctx context.Context, pgconn *PgConn) error + ValidateConnectFunc func(ctx context.Context, pgconn *PgConn) error + GetSSLPasswordFunc func(ctx context.Context) string +) + +// Config is the settings used to establish a connection to a PostgreSQL server. It must be created by [ParseConfig]. A +// manually initialized Config will cause ConnectConfig to panic. +type Config struct { + Host string // host (e.g. localhost) or absolute path to unix domain socket directory (e.g. /private/tmp) + Port uint16 + Database string + User string + Password string + TLSConfig *tls.Config // nil disables TLS + ConnectTimeout time.Duration + DialFunc DialFunc // e.g. net.Dialer.DialContext + LookupFunc LookupFunc // e.g. net.Resolver.LookupHost + BuildFrontend BuildFrontendFunc + + // BuildContextWatcherHandler is called to create a ContextWatcherHandler for a connection. The handler is called + // when a context passed to a PgConn method is canceled. + BuildContextWatcherHandler func(*PgConn) ctxwatch.Handler + + RuntimeParams map[string]string // Run-time parameters to set on connection as session default values (e.g. search_path or application_name) + + KerberosSrvName string + KerberosSpn string + Fallbacks []*FallbackConfig + + SSLNegotiation string // sslnegotiation=postgres or sslnegotiation=direct + + // AfterNetConnect is called after the network connection, including TLS if applicable, is established but before any + // PostgreSQL protocol communication. It takes the established net.Conn and returns a net.Conn that will be used in + // its place. It can be used to wrap the net.Conn (e.g. for logging, diagnostics, or testing). Its functionality has + // some overlap with DialFunc. However, DialFunc takes place before TLS is established and cannot be used to control + // the final net.Conn used for PostgreSQL protocol communication while AfterNetConnect can. + AfterNetConnect func(ctx context.Context, config *Config, conn net.Conn) (net.Conn, error) + + // ValidateConnect is called during a connection attempt after a successful authentication with the PostgreSQL server. + // It can be used to validate that the server is acceptable. If this returns an error the connection is closed and the next + // fallback config is tried. This allows implementing high availability behavior such as libpq does with target_session_attrs. + ValidateConnect ValidateConnectFunc + + // AfterConnect is called after ValidateConnect. It can be used to set up the connection (e.g. Set session variables + // or prepare statements). If this returns an error the connection attempt fails. + AfterConnect AfterConnectFunc + + // OnNotice is a callback function called when a notice response is received. + OnNotice NoticeHandler + + // OnNotification is a callback function called when a notification from the LISTEN/NOTIFY system is received. + OnNotification NotificationHandler + + // OnPgError is a callback function called when a Postgres error is received by the server. The default handler will close + // the connection on any FATAL errors. If you override this handler you should call the previously set handler or ensure + // that you close on FATAL errors by returning false. + OnPgError PgErrorHandler + + // OAuthTokenProvider is a function that returns an OAuth token for authentication. If set, it will be used for + // OAUTHBEARER SASL authentication when the server requests it. + OAuthTokenProvider func(context.Context) (string, error) + + // MinProtocolVersion is the minimum acceptable PostgreSQL protocol version. + // If the server does not support at least this version, the connection will fail. + // Valid values: "3.0", "3.2", "latest". Defaults to "3.0". + MinProtocolVersion string + + // MaxProtocolVersion is the maximum PostgreSQL protocol version to request from the server. + // Valid values: "3.0", "3.2", "latest". Defaults to "3.0" for compatibility. + MaxProtocolVersion string + + // ChannelBinding is the channel_binding parameter for SCRAM-SHA-256-PLUS authentication. + // Valid values: "disable", "prefer", "require". Defaults to "prefer". + ChannelBinding string + + // RequireAuth restricts which authentication methods the client will accept from the server, + // matching libpq's require_auth parameter. It is a comma-separated list of method names + // (password, md5, gss, sspi, scram-sha-256, oauth, none). A leading "!" on every entry negates + // the list (forbid these methods, allow all others). Empty (the default) means all methods are + // accepted. + RequireAuth string + + createdByParseConfig bool // Used to enforce created by ParseConfig rule. +} + +// connStringKeyAliases maps libpq parameter keywords to the canonical key names this package +// uses internally in the parsed-settings map. Most keywords are already canonical; this map +// holds only those whose pgx-internal name differs from the libpq spelling. +var connStringKeyAliases = map[string]string{ + "dbname": "database", +} + +// canonicalConnStringKey returns the canonical settings-map key for a libpq parameter keyword. +func canonicalConnStringKey(k string) string { + if c, ok := connStringKeyAliases[k]; ok { + return c + } + return k +} + +// ParseConfigOptions contains options that control how a config is built such as GetSSLPassword. +type ParseConfigOptions struct { + // GetSSLPassword gets the password to decrypt a SSL client certificate. This is analogous to the libpq function + // PQsetSSLKeyPassHook_OpenSSL. + GetSSLPassword GetSSLPasswordFunc + + // ConnStringAllowedKeys, if non-nil, restricts which parameter keys may appear in connString + // itself. Any other key (whether connString is in keyword/value or URL form) causes + // ParseConfigWithOptions to return an error before any filesystem access or network + // resolution is attempted. Environment variables (PGHOST, PGSERVICEFILE, ...) and built-in + // defaults are not checked: only keys that originate from the connString argument. + // + // Keys may be given in either their libpq spelling ("dbname") or pgx-internal spelling + // ("database"); both are accepted. + // + // A nil slice (the default) applies no restriction and matches libpq behaviour. An empty + // non-nil slice rejects every key, i.e. connString must be empty. + // + // Use this when any part of connString is built from input the application does not fully + // control (tenant configuration, RPC parameters, admin UI fields). List only the keys that + // input is expected to supply. This fails closed: a future libpq parameter that pgconn learns + // to parse will be rejected unless the application has explicitly allowed it, rather than + // silently passing through. + ConnStringAllowedKeys []string +} + +// Copy returns a deep copy of the config that is safe to use and modify. +// The only exception is the TLSConfig field: +// according to the tls.Config docs it must not be modified after creation. +func (c *Config) Copy() *Config { + newConf := new(Config) + *newConf = *c + if newConf.TLSConfig != nil { + newConf.TLSConfig = c.TLSConfig.Clone() + } + if newConf.RuntimeParams != nil { + newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams)) + maps.Copy(newConf.RuntimeParams, c.RuntimeParams) + } + if newConf.Fallbacks != nil { + newConf.Fallbacks = make([]*FallbackConfig, len(c.Fallbacks)) + for i, fallback := range c.Fallbacks { + newFallback := new(FallbackConfig) + *newFallback = *fallback + if newFallback.TLSConfig != nil { + newFallback.TLSConfig = fallback.TLSConfig.Clone() + } + newConf.Fallbacks[i] = newFallback + } + } + return newConf +} + +// FallbackConfig is additional settings to attempt a connection with when the primary Config fails to establish a +// network connection. It is used for TLS fallback such as sslmode=prefer and high availability (HA) connections. +type FallbackConfig struct { + Host string // host (e.g. localhost) or path to unix domain socket directory (e.g. /private/tmp) + Port uint16 + TLSConfig *tls.Config // nil disables TLS +} + +// connectOneConfig is the configuration for a single attempt to connect to a single host. +type connectOneConfig struct { + network string + address string + originalHostname string // original hostname before resolving + tlsConfig *tls.Config // nil disables TLS +} + +// isAbsolutePath checks if the provided value is an absolute path either +// beginning with a forward slash (as on Linux-based systems) or with a capital +// letter A-Z followed by a colon and a backslash, e.g., "C:\", (as on Windows). +func isAbsolutePath(path string) bool { + isWindowsPath := func(p string) bool { + if len(p) < 3 { + return false + } + drive := p[0] + colon := p[1] + backslash := p[2] + if drive >= 'A' && drive <= 'Z' && colon == ':' && backslash == '\\' { + return true + } + return false + } + return strings.HasPrefix(path, "/") || isWindowsPath(path) +} + +// NetworkAddress converts a PostgreSQL host and port into network and address suitable for use with +// net.Dial. +func NetworkAddress(host string, port uint16) (network, address string) { + if isAbsolutePath(host) { + network = "unix" + address = filepath.Join(host, ".s.PGSQL.") + strconv.FormatInt(int64(port), 10) + } else { + network = "tcp" + address = net.JoinHostPort(host, strconv.Itoa(int(port))) + } + return network, address +} + +// ParseConfig builds a *Config from connString with similar behavior to the PostgreSQL standard C library libpq. It +// uses the same defaults as libpq (e.g. port=5432) and understands most PG* environment variables. ParseConfig closely +// matches the parsing behavior of libpq. connString may either be in URL format or keyword = value format. See +// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING for details. connString also may be empty +// to only read from the environment. If a password is not supplied it will attempt to read the .pgpass file. +// +// # Example Keyword/Value +// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca +// +// # Example URL +// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca +// +// The returned *Config may be modified. However, it is strongly recommended that any configuration that can be done +// through the connection string be done there. In particular the fields Host, Port, TLSConfig, and Fallbacks can be +// interdependent (e.g. TLSConfig needs knowledge of the host to validate the server certificate). These fields should +// not be modified individually. They should all be modified or all left unchanged. +// +// ParseConfig supports specifying multiple hosts in similar manner to libpq. Host and port may include comma separated +// values that will be tried in order. This can be used as part of a high availability system. See +// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS for more information. +// +// # Example URL +// postgres://jack:secret@foo.example.com:5432,bar.example.com:5432/mydb +// +// ParseConfig currently recognizes the following environment variable and their parameter key word equivalents passed +// via database URL or keyword/value: +// +// PGHOST +// PGPORT +// PGDATABASE +// PGUSER +// PGPASSWORD +// PGPASSFILE +// PGSERVICE +// PGSERVICEFILE +// PGSSLMODE +// PGSSLCERT +// PGSSLKEY +// PGSSLROOTCERT +// PGSSLPASSWORD +// PGOPTIONS +// PGAPPNAME +// PGCONNECT_TIMEOUT +// PGTARGETSESSIONATTRS +// PGTZ +// PGMINPROTOCOLVERSION +// PGMAXPROTOCOLVERSION +// +// See http://www.postgresql.org/docs/current/static/libpq-envars.html for details on the meaning of environment variables. +// +// See https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-PARAMKEYWORDS for parameter key word names. They are +// usually but not always the environment variable name downcased and without the "PG" prefix. +// +// Important Security Notes: +// +// ParseConfig tries to match libpq behavior with regard to PGSSLMODE. This includes defaulting to "prefer" behavior if +// not set. +// +// See http://www.postgresql.org/docs/current/static/libpq-ssl.html#LIBPQ-SSL-PROTECTION for details on what level of +// security each sslmode provides. +// +// The sslmode "prefer" (the default), sslmode "allow", and multiple hosts are implemented via the Fallbacks field of +// the Config struct. If TLSConfig is manually changed it will not affect the fallbacks. For example, in the case of +// sslmode "prefer" this means it will first try the main Config settings which use TLS, then it will try the fallback +// which does not use TLS. This can lead to an unexpected unencrypted connection if the main TLS config is manually +// changed later but the unencrypted fallback is present. Ensure there are no stale fallbacks when manually setting +// TLSConfig. +// +// Several connection parameters cause ParseConfig to read files from the local filesystem: servicefile, passfile, +// sslkey, sslcert, and sslrootcert. Applications that build connection strings from untrusted input must not allow +// these keys to be set by that input. In particular, servicefile (which pgconn accepts in the connection string; +// libpq does not) is read as an INI file whose entries override other connection settings including host, port, and +// sslmode, so an attacker who controls servicefile and service can redirect the connection. If any portion of the +// connection string is externally supplied, use ParseConfigWithOptions and set ParseConfigOptions.ConnStringAllowedKeys +// to an allow-list of the keys that input is expected to supply; any other key in the connection string is then +// rejected before any filesystem access occurs. +// +// Other known differences with libpq: +// +// When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn +// does not. +// +// In addition, ParseConfig accepts the following options: +// +// - servicefile. +// libpq only reads servicefile from the PGSERVICEFILE environment variable. ParseConfig accepts servicefile as a +// part of the connection string. +func ParseConfig(connString string) (*Config, error) { + var parseConfigOptions ParseConfigOptions + return ParseConfigWithOptions(connString, parseConfigOptions) +} + +// ParseConfigWithOptions builds a *Config from connString and options with similar behavior to the PostgreSQL standard +// C library libpq. options contains settings that cannot be specified in a connString such as providing a function to +// get the SSL password. +func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Config, error) { + defaultSettings := defaultSettings() + envSettings := parseEnvSettings() + + connStringSettings := make(map[string]string) + if connString != "" { + var err error + // connString may be a database URL or in PostgreSQL keyword/value format + if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { + connStringSettings, err = parseURLSettings(connString) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err} + } + } else { + connStringSettings, err = parseKeywordValueSettings(connString) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as keyword/value", err: err} + } + } + } + + if options.ConnStringAllowedKeys != nil { + allowed := make(map[string]struct{}, len(options.ConnStringAllowedKeys)) + for _, k := range options.ConnStringAllowedKeys { + allowed[canonicalConnStringKey(k)] = struct{}{} + } + for k := range connStringSettings { + if _, ok := allowed[k]; !ok { + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)} + } + } + } + + settings := mergeSettings(defaultSettings, envSettings, connStringSettings) + if service, present := settings["service"]; present { + serviceSettings, err := parseServiceSettings(settings["servicefile"], service) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "failed to read service", err: err} + } + + settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings) + } + + config := &Config{ + createdByParseConfig: true, + Database: settings["database"], + User: settings["user"], + Password: settings["password"], + RuntimeParams: make(map[string]string), + BuildFrontend: pgproto3.NewFrontend, + BuildContextWatcherHandler: func(pgConn *PgConn) ctxwatch.Handler { + return &DeadlineContextWatcherHandler{Conn: pgConn.conn} + }, + OnPgError: func(_ *PgConn, pgErr *PgError) bool { + // we want to automatically close any fatal errors + if strings.EqualFold(pgErr.Severity, "FATAL") { + return false + } + return true + }, + } + + if connectTimeoutSetting, present := settings["connect_timeout"]; present { + connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "invalid connect_timeout", err: err} + } + config.ConnectTimeout = connectTimeout + config.DialFunc = makeConnectTimeoutDialFunc(connectTimeout) + } else { + defaultDialer := makeDefaultDialer() + config.DialFunc = defaultDialer.DialContext + } + + config.LookupFunc = makeDefaultResolver().LookupHost + + notRuntimeParams := map[string]struct{}{ + "host": {}, + "port": {}, + "database": {}, + "user": {}, + "password": {}, + "passfile": {}, + "connect_timeout": {}, + "sslmode": {}, + "sslkey": {}, + "sslcert": {}, + "sslrootcert": {}, + "sslnegotiation": {}, + "sslpassword": {}, + "sslsni": {}, + "krbspn": {}, + "krbsrvname": {}, + "target_session_attrs": {}, + "service": {}, + "servicefile": {}, + "min_protocol_version": {}, + "max_protocol_version": {}, + "channel_binding": {}, + "require_auth": {}, + } + + // Adding kerberos configuration + if _, present := settings["krbsrvname"]; present { + config.KerberosSrvName = settings["krbsrvname"] + } + if _, present := settings["krbspn"]; present { + config.KerberosSpn = settings["krbspn"] + } + + for k, v := range settings { + if _, present := notRuntimeParams[k]; present { + continue + } + config.RuntimeParams[k] = v + } + + fallbacks := []*FallbackConfig{} + + hosts := strings.Split(settings["host"], ",") + ports := strings.Split(settings["port"], ",") + + for i, host := range hosts { + var portStr string + if i < len(ports) { + portStr = ports[i] + } else { + portStr = ports[0] + } + + port, err := parsePort(portStr) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err} + } + + var tlsConfigs []*tls.Config + + // Ignore TLS settings if Unix domain socket like libpq + if network, _ := NetworkAddress(host, port); network == "unix" { + tlsConfigs = append(tlsConfigs, nil) + } else { + var err error + tlsConfigs, err = configTLS(settings, host, options) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err} + } + } + + for _, tlsConfig := range tlsConfigs { + fallbacks = append(fallbacks, &FallbackConfig{ + Host: host, + Port: port, + TLSConfig: tlsConfig, + }) + } + } + + config.Host = fallbacks[0].Host + config.Port = fallbacks[0].Port + config.TLSConfig = fallbacks[0].TLSConfig + config.Fallbacks = fallbacks[1:] + config.SSLNegotiation = settings["sslnegotiation"] + + passfile, err := pgpassfile.ReadPassfile(settings["passfile"]) + if err == nil { + if config.Password == "" { + host := config.Host + if network, _ := NetworkAddress(config.Host, config.Port); network == "unix" { + host = "localhost" + } + + config.Password = passfile.FindPassword(host, strconv.Itoa(int(config.Port)), config.Database, config.User) + } + } + + switch tsa := settings["target_session_attrs"]; tsa { + case "read-write": + config.ValidateConnect = ValidateConnectTargetSessionAttrsReadWrite + case "read-only": + config.ValidateConnect = ValidateConnectTargetSessionAttrsReadOnly + case "primary": + config.ValidateConnect = ValidateConnectTargetSessionAttrsPrimary + case "standby": + config.ValidateConnect = ValidateConnectTargetSessionAttrsStandby + case "prefer-standby": + config.ValidateConnect = ValidateConnectTargetSessionAttrsPreferStandby + case "any": + // do nothing + default: + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown target_session_attrs value: %v", tsa)} + } + + minProto, err := parseProtocolVersion(settings["min_protocol_version"]) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("invalid min_protocol_version: %q", settings["min_protocol_version"]), err: err} + } + maxProto, err := parseProtocolVersion(settings["max_protocol_version"]) + if err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("invalid max_protocol_version: %q", settings["max_protocol_version"]), err: err} + } + + config.MinProtocolVersion = settings["min_protocol_version"] + config.MaxProtocolVersion = settings["max_protocol_version"] + + if config.MinProtocolVersion == "" { + config.MinProtocolVersion = "3.0" + } + + // When max_protocol_version is not explicitly set, default based on + // min_protocol_version. This matches libpq behavior: if min > 3.0, + // default max to latest; otherwise default to 3.0 for compatibility + // with older servers/poolers that don't support NegotiateProtocolVersion. + if config.MaxProtocolVersion == "" { + if minProto > pgproto3.ProtocolVersion30 { + config.MaxProtocolVersion = "latest" + } else { + config.MaxProtocolVersion = "3.0" + } + } + + // Only error when max_protocol_version was explicitly set and conflicts + // with min_protocol_version. When max_protocol_version is not explicitly + // set, the auto-raise logic above already ensures a valid default. + if minProto > maxProto && settings["max_protocol_version"] != "" { + return nil, &ParseConfigError{ConnString: connString, msg: "min_protocol_version cannot be greater than max_protocol_version"} + } + + switch channelBinding := settings["channel_binding"]; channelBinding { + case "", "prefer": + config.ChannelBinding = "prefer" + case "disable": + config.ChannelBinding = "disable" + case "require": + config.ChannelBinding = "require" + default: + return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("unknown channel_binding value: %v", channelBinding)} + } + + config.RequireAuth = settings["require_auth"] + if _, err := parseRequireAuth(config.RequireAuth); err != nil { + return nil, &ParseConfigError{ConnString: connString, msg: "invalid require_auth", err: err} + } + + return config, nil +} + +func mergeSettings(settingSets ...map[string]string) map[string]string { + settings := make(map[string]string) + + for _, s2 := range settingSets { + maps.Copy(settings, s2) + } + + return settings +} + +func parseEnvSettings() map[string]string { + settings := make(map[string]string) + + nameMap := map[string]string{ + "PGHOST": "host", + "PGPORT": "port", + "PGDATABASE": "database", + "PGUSER": "user", + "PGPASSWORD": "password", + "PGPASSFILE": "passfile", + "PGAPPNAME": "application_name", + "PGCONNECT_TIMEOUT": "connect_timeout", + "PGSSLMODE": "sslmode", + "PGSSLKEY": "sslkey", + "PGSSLCERT": "sslcert", + "PGSSLSNI": "sslsni", + "PGSSLROOTCERT": "sslrootcert", + "PGSSLPASSWORD": "sslpassword", + "PGSSLNEGOTIATION": "sslnegotiation", + "PGTARGETSESSIONATTRS": "target_session_attrs", + "PGSERVICE": "service", + "PGSERVICEFILE": "servicefile", + "PGTZ": "timezone", + "PGOPTIONS": "options", + "PGMINPROTOCOLVERSION": "min_protocol_version", + "PGMAXPROTOCOLVERSION": "max_protocol_version", + "PGCHANNELBINDING": "channel_binding", + "PGREQUIREAUTH": "require_auth", + } + + for envname, realname := range nameMap { + value := os.Getenv(envname) + if value != "" { + settings[realname] = value + } + } + + return settings +} + +func parseURLSettings(connString string) (map[string]string, error) { + settings := make(map[string]string) + + parsedURL, err := url.Parse(connString) + if err != nil { + if urlErr := new(url.Error); errors.As(err, &urlErr) { + return nil, urlErr.Err + } + return nil, err + } + + if parsedURL.User != nil { + if u := parsedURL.User.Username(); u != "" { + settings["user"] = u + } + if password, present := parsedURL.User.Password(); present { + settings["password"] = password + } + } + + // Handle multiple host:port's in url.Host by splitting them into host,host,host and port,port,port. + var hosts []string + var ports []string + for host := range strings.SplitSeq(parsedURL.Host, ",") { + if host == "" { + continue + } + if isIPOnly(host) { + hosts = append(hosts, strings.Trim(host, "[]")) + continue + } + h, p, err := net.SplitHostPort(host) + if err != nil { + return nil, fmt.Errorf("failed to split host:port in '%s', err: %w", host, err) + } + if h != "" { + hosts = append(hosts, h) + } + if p != "" { + ports = append(ports, p) + } + } + if len(hosts) > 0 { + settings["host"] = strings.Join(hosts, ",") + } + if len(ports) > 0 { + settings["port"] = strings.Join(ports, ",") + } + + database := strings.TrimLeft(parsedURL.Path, "/") + if database != "" { + settings["database"] = database + } + + for k, v := range parsedURL.Query() { + settings[canonicalConnStringKey(k)] = v[0] + } + + return settings, nil +} + +func isIPOnly(host string) bool { + return net.ParseIP(strings.Trim(host, "[]")) != nil || !strings.Contains(host, ":") +} + +var asciiSpace = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1} + +func parseKeywordValueSettings(s string) (map[string]string, error) { + settings := make(map[string]string) + + // Trim any leading whitespace so that the loop exits cleanly when only + // spaces remain (e.g. trailing spaces after the last value). + s = strings.TrimLeft(s, " \t\n\r\v\f") + for len(s) > 0 { + var key, val string + eqIdx := strings.IndexRune(s, '=') + if eqIdx < 0 { + return nil, errors.New("invalid keyword/value") + } + + key = strings.Trim(s[:eqIdx], " \t\n\r\v\f") + s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f") + switch { + case len(s) == 0: + case s[0] != '\'': + end := 0 + for ; end < len(s); end++ { + if asciiSpace[s[end]] == 1 { + break + } + if s[end] == '\\' { + end++ + if end == len(s) { + return nil, errors.New("invalid backslash") + } + } + } + val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'") + // Consume the value and trim any subsequent whitespace so that + // multiple trailing spaces don't cause a spurious parse failure. + s = strings.TrimLeft(s[end:], " \t\n\r\v\f") + default: // quoted string + s = s[1:] + end := 0 + for ; end < len(s); end++ { + if s[end] == '\'' { + break + } + if s[end] == '\\' { + end++ + } + } + if end == len(s) { + return nil, errors.New("unterminated quoted string in connection info string") + } + val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'") + // Consume the closing quote and any subsequent whitespace. + s = strings.TrimLeft(s[end+1:], " \t\n\r\v\f") + } + + key = canonicalConnStringKey(key) + + if key == "" { + return nil, errors.New("invalid keyword/value") + } + + if key == "user" && val == "" { + continue + } + settings[key] = val + } + + return settings, nil +} + +func parseServiceSettings(servicefilePath, serviceName string) (map[string]string, error) { + servicefile, err := pgservicefile.ReadServicefile(servicefilePath) + if err != nil { + return nil, fmt.Errorf("failed to read service file: %v", servicefilePath) + } + + service, err := servicefile.GetService(serviceName) + if err != nil { + return nil, fmt.Errorf("unable to find service: %v", serviceName) + } + + settings := make(map[string]string, len(service.Settings)) + for k, v := range service.Settings { + settings[canonicalConnStringKey(k)] = v + } + + return settings, nil +} + +// configTLS uses libpq's TLS parameters to construct []*tls.Config. It is +// necessary to allow returning multiple TLS configs as sslmode "allow" and +// "prefer" allow fallback. +func configTLS(settings map[string]string, thisHost string, parseConfigOptions ParseConfigOptions) ([]*tls.Config, error) { + host := thisHost + sslmode := settings["sslmode"] + sslrootcert := settings["sslrootcert"] + sslcert := settings["sslcert"] + sslkey := settings["sslkey"] + sslpassword := settings["sslpassword"] + sslsni := settings["sslsni"] + sslnegotiation := settings["sslnegotiation"] + + // Match libpq default behavior + if sslmode == "" { + sslmode = "prefer" + } + if sslsni == "" { + sslsni = "1" + } + + tlsConfig := &tls.Config{} + + if sslnegotiation == "direct" { + tlsConfig.NextProtos = []string{"postgresql"} + if sslmode == "prefer" { + sslmode = "require" + } + } + + if sslrootcert != "" { + var caCertPool *x509.CertPool + + if sslrootcert == "system" { + var err error + + caCertPool, err = x509.SystemCertPool() + if err != nil { + return nil, fmt.Errorf("unable to load system certificate pool: %w", err) + } + + sslmode = "verify-full" + } else { + caCertPool = x509.NewCertPool() + + caPath := sslrootcert + caCert, err := os.ReadFile(caPath) + if err != nil { + return nil, fmt.Errorf("unable to read CA file: %w", err) + } + + if !caCertPool.AppendCertsFromPEM(caCert) { + return nil, errors.New("unable to add CA to cert pool") + } + } + + tlsConfig.RootCAs = caCertPool + tlsConfig.ClientCAs = caCertPool + } + + switch sslmode { + case "disable": + return []*tls.Config{nil}, nil + case "allow", "prefer": + tlsConfig.InsecureSkipVerify = true + case "require": + // According to PostgreSQL documentation, if a root CA file exists, + // the behavior of sslmode=require should be the same as that of verify-ca + // + // See https://www.postgresql.org/docs/current/libpq-ssl.html + if sslrootcert != "" { + goto nextCase + } + tlsConfig.InsecureSkipVerify = true + break + nextCase: + fallthrough + case "verify-ca": + // Don't perform the default certificate verification because it + // will verify the hostname. Instead, verify the server's + // certificate chain ourselves in VerifyPeerCertificate and + // ignore the server name. This emulates libpq's verify-ca + // behavior. + // + // See https://github.com/golang/go/issues/21971#issuecomment-332693931 + // and https://pkg.go.dev/crypto/tls?tab=doc#example-Config-VerifyPeerCertificate + // for more info. + tlsConfig.InsecureSkipVerify = true + tlsConfig.VerifyPeerCertificate = func(certificates [][]byte, _ [][]*x509.Certificate) error { + certs := make([]*x509.Certificate, len(certificates)) + for i, asn1Data := range certificates { + cert, err := x509.ParseCertificate(asn1Data) + if err != nil { + return errors.New("failed to parse certificate from server: " + err.Error()) + } + certs[i] = cert + } + + // Leave DNSName empty to skip hostname verification. + opts := x509.VerifyOptions{ + Roots: tlsConfig.RootCAs, + Intermediates: x509.NewCertPool(), + } + // Skip the first cert because it's the leaf. All others + // are intermediates. + for _, cert := range certs[1:] { + opts.Intermediates.AddCert(cert) + } + _, err := certs[0].Verify(opts) + return err + } + case "verify-full": + tlsConfig.ServerName = host + default: + return nil, errors.New("sslmode is invalid") + } + + if (sslcert != "" && sslkey == "") || (sslcert == "" && sslkey != "") { + return nil, errors.New(`both "sslcert" and "sslkey" are required`) + } + + if sslcert != "" && sslkey != "" { + buf, err := os.ReadFile(sslkey) + if err != nil { + return nil, fmt.Errorf("unable to read sslkey: %w", err) + } + block, _ := pem.Decode(buf) + if block == nil { + return nil, errors.New("failed to decode sslkey") + } + var pemKey []byte + var decryptedKey []byte + var decryptedError error + // If PEM is encrypted, attempt to decrypt using pass phrase + if x509.IsEncryptedPEMBlock(block) { + // Attempt decryption with pass phrase + // NOTE: only supports RSA (PKCS#1) + if sslpassword != "" { + decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) //nolint:ineffassign + } + // if sslpassword not provided or has decryption error when use it + // try to find sslpassword with callback function + if sslpassword == "" || decryptedError != nil { + if parseConfigOptions.GetSSLPassword != nil { + sslpassword = parseConfigOptions.GetSSLPassword(context.Background()) + } + if sslpassword == "" { + return nil, fmt.Errorf("unable to find sslpassword") + } + } + decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword)) + // Should we also provide warning for PKCS#1 needed? + if decryptedError != nil { + return nil, fmt.Errorf("unable to decrypt key: %w", decryptedError) + } + + pemBytes := pem.Block{ + Type: "RSA PRIVATE KEY", + Bytes: decryptedKey, + } + pemKey = pem.EncodeToMemory(&pemBytes) + } else { + pemKey = pem.EncodeToMemory(block) + } + certfile, err := os.ReadFile(sslcert) + if err != nil { + return nil, fmt.Errorf("unable to read cert: %w", err) + } + cert, err := tls.X509KeyPair(certfile, pemKey) + if err != nil { + return nil, fmt.Errorf("unable to load cert: %w", err) + } + tlsConfig.Certificates = []tls.Certificate{cert} + } + + // Set Server Name Indication (SNI), if enabled by connection parameters. + // Per RFC 6066, do not set it if the host is a literal IP address (IPv4 + // or IPv6). + if sslsni == "1" && net.ParseIP(host) == nil { + tlsConfig.ServerName = host + } + + switch sslmode { + case "allow": + return []*tls.Config{nil, tlsConfig}, nil + case "prefer": + return []*tls.Config{tlsConfig, nil}, nil + case "require", "verify-ca", "verify-full": + return []*tls.Config{tlsConfig}, nil + default: + panic("BUG: bad sslmode should already have been caught") + } +} + +func parsePort(s string) (uint16, error) { + port, err := strconv.ParseUint(s, 10, 16) + if err != nil { + return 0, err + } + if port < 1 || port > math.MaxUint16 { + return 0, errors.New("outside range") + } + return uint16(port), nil +} + +func makeDefaultDialer() *net.Dialer { + // rely on GOLANG KeepAlive settings + return &net.Dialer{} +} + +func makeDefaultResolver() *net.Resolver { + return net.DefaultResolver +} + +func parseConnectTimeoutSetting(s string) (time.Duration, error) { + timeout, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return 0, err + } + if timeout < 0 { + return 0, errors.New("negative timeout") + } + return time.Duration(timeout) * time.Second, nil +} + +func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc { + d := makeDefaultDialer() + d.Timeout = timeout + return d.DialContext +} + +// ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible +// target_session_attrs=read-write. +func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error { + result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll() + if err != nil { + return err + } + + if string(result[0].Rows[0][0]) == "on" { + return errors.New("read only connection") + } + + return nil +} + +// ValidateConnectTargetSessionAttrsReadOnly is a ValidateConnectFunc that implements libpq compatible +// target_session_attrs=read-only. +func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgConn) error { + result, err := pgConn.Exec(ctx, "show transaction_read_only").ReadAll() + if err != nil { + return err + } + + if string(result[0].Rows[0][0]) != "on" { + return errors.New("connection is not read only") + } + + return nil +} + +// ValidateConnectTargetSessionAttrsStandby is a ValidateConnectFunc that implements libpq compatible +// target_session_attrs=standby. +func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgConn) error { + result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll() + if err != nil { + return err + } + + if string(result[0].Rows[0][0]) != "t" { + return errors.New("server is not in hot standby mode") + } + + return nil +} + +// ValidateConnectTargetSessionAttrsPrimary is a ValidateConnectFunc that implements libpq compatible +// target_session_attrs=primary. +func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgConn) error { + result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll() + if err != nil { + return err + } + + if string(result[0].Rows[0][0]) == "t" { + return errors.New("server is in standby mode") + } + + return nil +} + +// ValidateConnectTargetSessionAttrsPreferStandby is a ValidateConnectFunc that implements libpq compatible +// target_session_attrs=prefer-standby. +func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn *PgConn) error { + result, err := pgConn.Exec(ctx, "select pg_is_in_recovery()").ReadAll() + if err != nil { + return err + } + + if string(result[0].Rows[0][0]) != "t" { + return &NotPreferredError{err: errors.New("server is not in hot standby mode")} + } + + return nil +} + +func parseProtocolVersion(s string) (uint32, error) { + switch s { + case "", "3.0": + return pgproto3.ProtocolVersion30, nil + case "3.2", "latest": + return pgproto3.ProtocolVersion32, nil + default: + return 0, fmt.Errorf("invalid protocol version: %q", s) + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go b/vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go new file mode 100644 index 0000000..b8892e6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/ctxwatch/context_watcher.go @@ -0,0 +1,72 @@ +package ctxwatch + +import ( + "context" + "sync" +) + +// ContextWatcher watches a context and performs an action when the context is canceled. It can watch one context at a +// time. +type ContextWatcher struct { + handler Handler + + // Lock protects the members below. + lock sync.Mutex + // Stop is the handle for an "after func". See [context.AfterFunc]. + stop func() bool + done chan struct{} +} + +// NewContextWatcher returns a ContextWatcher. onCancel will be called when a watched context is canceled. +// OnUnwatchAfterCancel will be called when Unwatch is called and the watched context had already been canceled and +// onCancel called. +func NewContextWatcher(handler Handler) *ContextWatcher { + cw := &ContextWatcher{ + handler: handler, + } + + return cw +} + +// Watch starts watching ctx. If ctx is canceled then the onCancel function passed to NewContextWatcher will be called. +func (cw *ContextWatcher) Watch(ctx context.Context) { + cw.lock.Lock() + defer cw.lock.Unlock() + + if cw.stop != nil { + panic("watch already in progress") + } + + if ctx.Done() != nil { + cw.done = make(chan struct{}) + cw.stop = context.AfterFunc(ctx, func() { + cw.handler.HandleCancel(ctx) + close(cw.done) + }) + } +} + +// Unwatch stops watching the previously watched context. If the onCancel function passed to NewContextWatcher was +// called then onUnwatchAfterCancel will also be called. +func (cw *ContextWatcher) Unwatch() { + cw.lock.Lock() + defer cw.lock.Unlock() + + if cw.stop != nil { + if !cw.stop() { + <-cw.done + cw.handler.HandleUnwatchAfterCancel() + } + cw.stop = nil + cw.done = nil + } +} + +type Handler interface { + // HandleCancel is called when the context that a ContextWatcher is currently watching is canceled. canceledCtx is the + // context that was canceled. + HandleCancel(canceledCtx context.Context) + + // HandleUnwatchAfterCancel is called when a ContextWatcher that called HandleCancel on this Handler is unwatched. + HandleUnwatchAfterCancel() +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go new file mode 100644 index 0000000..1dd514f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/defaults.go @@ -0,0 +1,63 @@ +//go:build !windows +// +build !windows + +package pgconn + +import ( + "os" + "os/user" + "path/filepath" +) + +func defaultSettings() map[string]string { + settings := make(map[string]string) + + settings["host"] = defaultHost() + settings["port"] = "5432" + + // Default to the OS user name. Purposely ignoring err getting user name from + // OS. The client application will simply have to specify the user in that + // case (which they typically will be doing anyway). + user, err := user.Current() + if err == nil { + settings["user"] = user.Username + settings["passfile"] = filepath.Join(user.HomeDir, ".pgpass") + settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") + sslcert := filepath.Join(user.HomeDir, ".postgresql", "postgresql.crt") + sslkey := filepath.Join(user.HomeDir, ".postgresql", "postgresql.key") + if _, err := os.Stat(sslcert); err == nil { + if _, err := os.Stat(sslkey); err == nil { + // Both the cert and key must be present to use them, or do not use either + settings["sslcert"] = sslcert + settings["sslkey"] = sslkey + } + } + sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt") + if _, err := os.Stat(sslrootcert); err == nil { + settings["sslrootcert"] = sslrootcert + } + } + + settings["target_session_attrs"] = "any" + + return settings +} + +// defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost +// on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it +// checks the existence of common locations. +func defaultHost() string { + candidatePaths := []string{ + "/var/run/postgresql", // Debian + "/private/tmp", // OSX - homebrew + "/tmp", // standard PostgreSQL + } + + for _, path := range candidatePaths { + if _, err := os.Stat(path); err == nil { + return path + } + } + + return "localhost" +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go new file mode 100644 index 0000000..33b4a1f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/defaults_windows.go @@ -0,0 +1,57 @@ +package pgconn + +import ( + "os" + "os/user" + "path/filepath" + "strings" +) + +func defaultSettings() map[string]string { + settings := make(map[string]string) + + settings["host"] = defaultHost() + settings["port"] = "5432" + + // Default to the OS user name. Purposely ignoring err getting user name from + // OS. The client application will simply have to specify the user in that + // case (which they typically will be doing anyway). + user, err := user.Current() + appData := os.Getenv("APPDATA") + if err == nil { + // Windows gives us the username here as `DOMAIN\user` or `LOCALPCNAME\user`, + // but the libpq default is just the `user` portion, so we strip off the first part. + username := user.Username + if strings.Contains(username, "\\") { + username = username[strings.LastIndex(username, "\\")+1:] + } + + settings["user"] = username + settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf") + settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf") + sslcert := filepath.Join(appData, "postgresql", "postgresql.crt") + sslkey := filepath.Join(appData, "postgresql", "postgresql.key") + if _, err := os.Stat(sslcert); err == nil { + if _, err := os.Stat(sslkey); err == nil { + // Both the cert and key must be present to use them, or do not use either + settings["sslcert"] = sslcert + settings["sslkey"] = sslkey + } + } + sslrootcert := filepath.Join(appData, "postgresql", "root.crt") + if _, err := os.Stat(sslrootcert); err == nil { + settings["sslrootcert"] = sslrootcert + } + } + + settings["target_session_attrs"] = "any" + + return settings +} + +// defaultHost attempts to mimic libpq's default host. libpq uses the default unix socket location on *nix and localhost +// on Windows. The default socket location is compiled into libpq. Since pgx does not have access to that default it +// checks the existence of common locations. +func defaultHost() string { + return "localhost" +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/doc.go b/vendor/github.com/jackc/pgx/v5/pgconn/doc.go new file mode 100644 index 0000000..f970726 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/doc.go @@ -0,0 +1,64 @@ +// Package pgconn is a low-level PostgreSQL database driver. +/* +pgconn provides lower level access to a PostgreSQL connection than a database/sql or pgx connection. It operates at +nearly the same level is the C library libpq. + +Establishing a Connection + +Use Connect to establish a connection. It accepts a connection string in URL or keyword/value format and will read the +environment for libpq style environment variables. + +Connecting Securely + +By default ParseConfig matches libpq and uses sslmode=prefer, which silently falls back to an unencrypted connection +if the server does not offer TLS. For connections that traverse an untrusted network, set the following parameters +explicitly: + + # URL form + postgres://user@db.example.com/mydb?sslmode=verify-full&sslrootcert=/path/to/root.crt&channel_binding=require&require_auth=scram-sha-256 + + # keyword/value form + host=db.example.com user=user dbname=mydb sslmode=verify-full sslrootcert=/path/to/root.crt channel_binding=require require_auth=scram-sha-256 + + sslmode=verify-full Require TLS, verify the server certificate against sslrootcert, and verify that the + certificate's host name matches the host being connected to. Weaker modes (disable, + allow, prefer, require) either permit plaintext fallback or skip certificate + verification, allowing a network attacker to impersonate the server. + channel_binding=require Require SCRAM-SHA-256-PLUS, which binds the authentication exchange to the TLS channel + so that a TLS-terminating intermediary cannot relay credentials to the real server. + require_auth=scram-sha-256 + Refuse to respond to AuthenticationCleartextPassword or AuthenticationMD5Password + requests from the server. Without this, a server (or interceptor) can request the + password in cleartext and the client will send it. + +These parameters may also be set via the PGSSLMODE, PGSSLROOTCERT, PGCHANNELBINDING, and PGREQUIREAUTH environment +variables. + +Executing a Query + +ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method +reads all rows into memory. + +Executing Multiple Queries in a Single Round Trip + +Exec and ExecBatch can execute multiple queries in a single round trip. They return readers that iterate over each query +result. The ReadAll method reads all query results into memory. + +Pipeline Mode + +Pipeline mode allows sending queries without having read the results of previously sent queries. It allows control of +exactly how many and when network round trips occur. + +Context Support + +All potentially blocking operations take a context.Context. The default behavior when a context is canceled is for the +method to immediately return. In most circumstances, this will also close the underlying connection. This behavior can +be customized by using BuildContextWatcherHandler on the Config to create a ctxwatch.Handler with different behavior. +This can be especially useful when queries that are frequently canceled and the overhead of creating new connections is +a problem. DeadlineContextWatcherHandler and CancelRequestContextWatcherHandler can be used to introduce a delay before +interrupting the query in such a way as to close the connection. + +The CancelRequest method may be used to request the PostgreSQL server cancel an in-progress query without forcing the +client to abort. +*/ +package pgconn diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/errors.go b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go new file mode 100644 index 0000000..9fbe68c --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/errors.go @@ -0,0 +1,287 @@ +package pgconn + +import ( + "context" + "errors" + "fmt" + "net" + "net/url" + "regexp" + "strings" +) + +// SafeToRetry checks if the err is guaranteed to have occurred before sending any data to the server. +func SafeToRetry(err error) bool { + var retryableErr interface{ SafeToRetry() bool } + if errors.As(err, &retryableErr) { + return retryableErr.SafeToRetry() + } + return false +} + +// Timeout checks if err was caused by a timeout. To be specific, it is true if err was caused within pgconn by a +// context.DeadlineExceeded or an implementer of net.Error where Timeout() is true. +func Timeout(err error) bool { + var timeoutErr *errTimeout + return errors.As(err, &timeoutErr) +} + +// PgError represents an error reported by the PostgreSQL server. See +// http://www.postgresql.org/docs/current/static/protocol-error-fields.html for +// detailed field description. +type PgError struct { + Severity string + SeverityUnlocalized string + Code string + Message string + Detail string + Hint string + Position int32 + InternalPosition int32 + InternalQuery string + Where string + SchemaName string + TableName string + ColumnName string + DataTypeName string + ConstraintName string + File string + Line int32 + Routine string +} + +func (pe *PgError) Error() string { + return pe.Severity + ": " + pe.Message + " (SQLSTATE " + pe.Code + ")" +} + +// SQLState returns the SQLState of the error. +func (pe *PgError) SQLState() string { + return pe.Code +} + +// ConnectError is the error returned when a connection attempt fails. +type ConnectError struct { + Config *Config // The configuration that was used in the connection attempt. + err error +} + +func (e *ConnectError) Error() string { + prefix := fmt.Sprintf("failed to connect to `user=%s database=%s`:", e.Config.User, e.Config.Database) + details := e.err.Error() + if strings.Contains(details, "\n") { + return prefix + "\n\t" + strings.ReplaceAll(details, "\n", "\n\t") + } else { + return prefix + " " + details + } +} + +func (e *ConnectError) Unwrap() error { + return e.err +} + +type perDialConnectError struct { + address string + originalHostname string + err error +} + +func (e *perDialConnectError) Error() string { + return fmt.Sprintf("%s (%s): %s", e.address, e.originalHostname, e.err.Error()) +} + +func (e *perDialConnectError) Unwrap() error { + return e.err +} + +// ErrConnClosed is returned (possibly wrapped) when an operation is attempted +// on a connection that the driver has already closed, e.g. because a prior +// query was cancelled mid-flight or the underlying socket went away. Use +// errors.Is to test for it, since it shows up wrapped inside connLockError. +var ErrConnClosed = errors.New("conn closed") + +type connLockError struct { + status string +} + +func (e *connLockError) SafeToRetry() bool { + return true // a lock failure by definition happens before the connection is used. +} + +func (e *connLockError) Error() string { + return e.status +} + +func (e *connLockError) Unwrap() error { + if e.status == "conn closed" { + return ErrConnClosed + } + return nil +} + +// ParseConfigError is the error returned when a connection string cannot be parsed. +type ParseConfigError struct { + ConnString string // The connection string that could not be parsed. + msg string + err error +} + +func NewParseConfigError(conn, msg string, err error) error { + return &ParseConfigError{ + ConnString: conn, + msg: msg, + err: err, + } +} + +func (e *ParseConfigError) Error() string { + // Now that ParseConfigError is public and ConnString is available to the developer, perhaps it would be better only + // return a static string. That would ensure that the error message cannot leak a password. The ConnString field would + // allow access to the original string if desired and Unwrap would allow access to the underlying error. + connString := redactPW(e.ConnString) + if e.err == nil { + return fmt.Sprintf("cannot parse `%s`: %s", connString, e.msg) + } + return fmt.Sprintf("cannot parse `%s`: %s (%s)", connString, e.msg, e.err.Error()) +} + +func (e *ParseConfigError) Unwrap() error { + return e.err +} + +func normalizeTimeoutError(ctx context.Context, err error) error { + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + switch ctx.Err() { + case context.Canceled: + // Since the timeout was caused by a context cancellation, the actual error is context.Canceled not the timeout error. + return context.Canceled + case context.DeadlineExceeded: + return &errTimeout{err: ctx.Err()} + default: + return &errTimeout{err: err} + } + } + return err +} + +type pgconnError struct { + msg string + err error + safeToRetry bool +} + +func (e *pgconnError) Error() string { + if e.msg == "" { + return e.err.Error() + } + if e.err == nil { + return e.msg + } + return fmt.Sprintf("%s: %s", e.msg, e.err.Error()) +} + +func (e *pgconnError) SafeToRetry() bool { + return e.safeToRetry +} + +func (e *pgconnError) Unwrap() error { + return e.err +} + +// errTimeout occurs when an error was caused by a timeout. Specifically, it wraps an error which is +// context.Canceled, context.DeadlineExceeded, or an implementer of net.Error where Timeout() is true. +type errTimeout struct { + err error +} + +func (e *errTimeout) Error() string { + return fmt.Sprintf("timeout: %s", e.err.Error()) +} + +func (e *errTimeout) SafeToRetry() bool { + return SafeToRetry(e.err) +} + +func (e *errTimeout) Unwrap() error { + return e.err +} + +type contextAlreadyDoneError struct { + err error +} + +func (e *contextAlreadyDoneError) Error() string { + return fmt.Sprintf("context already done: %s", e.err.Error()) +} + +func (e *contextAlreadyDoneError) SafeToRetry() bool { + return true +} + +func (e *contextAlreadyDoneError) Unwrap() error { + return e.err +} + +// newContextAlreadyDoneError double-wraps a context error in `contextAlreadyDoneError` and `errTimeout`. +func newContextAlreadyDoneError(ctx context.Context) (err error) { + return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}} +} + +func redactPW(connString string) string { + if strings.HasPrefix(connString, "postgres://") || strings.HasPrefix(connString, "postgresql://") { + if u, err := url.Parse(connString); err == nil { + return redactURL(u) + } + } + quotedKV := regexp.MustCompile(`password='[^']*'`) + connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx") + plainKV := regexp.MustCompile(`password=[^ ]*`) + connString = plainKV.ReplaceAllLiteralString(connString, "password=xxxxx") + brokenURL := regexp.MustCompile(`:[^:@]+?@`) + connString = brokenURL.ReplaceAllLiteralString(connString, ":xxxxxx@") + return connString +} + +func redactURL(u *url.URL) string { + if u == nil { + return "" + } + if _, pwSet := u.User.Password(); pwSet { + u.User = url.UserPassword(u.User.Username(), "xxxxx") + } + return u.String() +} + +type NotPreferredError struct { + err error + safeToRetry bool +} + +func (e *NotPreferredError) Error() string { + return fmt.Sprintf("standby server not found: %s", e.err.Error()) +} + +func (e *NotPreferredError) SafeToRetry() bool { + return e.safeToRetry +} + +func (e *NotPreferredError) Unwrap() error { + return e.err +} + +type PrepareError struct { + err error + + ParseComplete bool // Indicates whether the error occurred after a ParseComplete message was received. +} + +func (e *PrepareError) Error() string { + if e.ParseComplete { + return fmt.Sprintf("prepare failed after ParseComplete: %s", e.err.Error()) + } + return e.err.Error() +} + +func (e *PrepareError) Unwrap() error { + return e.err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go b/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go new file mode 100644 index 0000000..e65c2c2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/internal/bgreader/bgreader.go @@ -0,0 +1,139 @@ +// Package bgreader provides a io.Reader that can optionally buffer reads in the background. +package bgreader + +import ( + "io" + "sync" + + "github.com/jackc/pgx/v5/internal/iobufpool" +) + +const ( + StatusStopped = iota + StatusRunning + StatusStopping +) + +// BGReader is an io.Reader that can optionally buffer reads in the background. It is safe for concurrent use. +type BGReader struct { + r io.Reader + + cond *sync.Cond + status int32 + readResults []readResult +} + +type readResult struct { + buf *[]byte + err error +} + +// Start starts the backgrounder reader. If the background reader is already running this is a no-op. The background +// reader will stop automatically when the underlying reader returns an error. +func (r *BGReader) Start() { + r.cond.L.Lock() + defer r.cond.L.Unlock() + + switch r.status { + case StatusStopped: + r.status = StatusRunning + go r.bgRead() + case StatusRunning: + // no-op + case StatusStopping: + r.status = StatusRunning + } +} + +// Stop tells the background reader to stop after the in progress Read returns. It is safe to call Stop when the +// background reader is not running. +func (r *BGReader) Stop() { + r.cond.L.Lock() + defer r.cond.L.Unlock() + + switch r.status { + case StatusStopped: + // no-op + case StatusRunning: + r.status = StatusStopping + case StatusStopping: + // no-op + } +} + +// Status returns the current status of the background reader. +func (r *BGReader) Status() int32 { + r.cond.L.Lock() + defer r.cond.L.Unlock() + return r.status +} + +func (r *BGReader) bgRead() { + keepReading := true + for keepReading { + buf := iobufpool.Get(8192) + n, err := r.r.Read(*buf) + *buf = (*buf)[:n] + + r.cond.L.Lock() + r.readResults = append(r.readResults, readResult{buf: buf, err: err}) + if r.status == StatusStopping || err != nil { + r.status = StatusStopped + keepReading = false + } + r.cond.L.Unlock() + r.cond.Broadcast() + } +} + +// Read implements the io.Reader interface. +func (r *BGReader) Read(p []byte) (int, error) { + r.cond.L.Lock() + defer r.cond.L.Unlock() + + if len(r.readResults) > 0 { + return r.readFromReadResults(p) + } + + // There are no unread background read results and the background reader is stopped. + if r.status == StatusStopped { + return r.r.Read(p) + } + + // Wait for results from the background reader + for len(r.readResults) == 0 { + r.cond.Wait() + } + return r.readFromReadResults(p) +} + +// readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held. +func (r *BGReader) readFromReadResults(p []byte) (int, error) { + buf := r.readResults[0].buf + var err error + + n := copy(p, *buf) + if n == len(*buf) { + err = r.readResults[0].err + iobufpool.Put(buf) + if len(r.readResults) == 1 { + r.readResults = nil + } else { + r.readResults = r.readResults[1:] + } + } else { + *buf = (*buf)[n:] + r.readResults[0].buf = buf + } + + return n, err +} + +func New(r io.Reader) *BGReader { + return &BGReader{ + r: r, + cond: &sync.Cond{ + L: &sync.Mutex{}, + }, + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/krb5.go b/vendor/github.com/jackc/pgx/v5/pgconn/krb5.go new file mode 100644 index 0000000..efb0d61 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/krb5.go @@ -0,0 +1,100 @@ +package pgconn + +import ( + "errors" + "fmt" + + "github.com/jackc/pgx/v5/pgproto3" +) + +// NewGSSFunc creates a GSS authentication provider, for use with +// RegisterGSSProvider. +type NewGSSFunc func() (GSS, error) + +var newGSS NewGSSFunc + +// RegisterGSSProvider registers a GSS authentication provider. For example, if +// you need to use Kerberos to authenticate with your server, add this to your +// main package: +// +// import "github.com/otan/gopgkrb5" +// +// func init() { +// pgconn.RegisterGSSProvider(func() (pgconn.GSS, error) { return gopgkrb5.NewGSS() }) +// } +func RegisterGSSProvider(newGSSArg NewGSSFunc) { + newGSS = newGSSArg +} + +// GSS provides GSSAPI authentication (e.g., Kerberos). +type GSS interface { + GetInitToken(host, service string) ([]byte, error) + GetInitTokenFromSPN(spn string) ([]byte, error) + Continue(inToken []byte) (done bool, outToken []byte, err error) +} + +func (c *PgConn) gssAuth() error { + if newGSS == nil { + return errors.New("kerberos error: no GSSAPI provider registered, see https://github.com/otan/gopgkrb5") + } + cli, err := newGSS() + if err != nil { + return err + } + + var nextData []byte + if c.config.KerberosSpn != "" { + // Use the supplied SPN if provided. + nextData, err = cli.GetInitTokenFromSPN(c.config.KerberosSpn) + } else { + // Allow the kerberos service name to be overridden + service := "postgres" + if c.config.KerberosSrvName != "" { + service = c.config.KerberosSrvName + } + nextData, err = cli.GetInitToken(c.config.Host, service) + } + if err != nil { + return err + } + + for { + gssResponse := &pgproto3.GSSResponse{ + Data: nextData, + } + c.frontend.Send(gssResponse) + err = c.flushWithPotentialWriteReadDeadlock() + if err != nil { + return err + } + resp, err := c.rxGSSContinue() + if err != nil { + return err + } + var done bool + done, nextData, err = cli.Continue(resp.Data) + if err != nil { + return err + } + if done { + break + } + } + return nil +} + +func (c *PgConn) rxGSSContinue() (*pgproto3.AuthenticationGSSContinue, error) { + msg, err := c.receiveMessage() + if err != nil { + return nil, err + } + + switch m := msg.(type) { + case *pgproto3.AuthenticationGSSContinue: + return m, nil + case *pgproto3.ErrorResponse: + return nil, ErrorResponseToPgError(m) + } + + return nil, fmt.Errorf("expected AuthenticationGSSContinue message but received unexpected message %T", msg) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go new file mode 100644 index 0000000..d181f7f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/pgconn.go @@ -0,0 +1,3042 @@ +package pgconn + +import ( + "container/list" + "context" + "crypto/md5" + "crypto/tls" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "maps" + "math" + "net" + "strconv" + "strings" + "sync" + "time" + + "github.com/jackc/pgx/v5/internal/iobufpool" + "github.com/jackc/pgx/v5/internal/pgio" + "github.com/jackc/pgx/v5/pgconn/ctxwatch" + "github.com/jackc/pgx/v5/pgconn/internal/bgreader" + "github.com/jackc/pgx/v5/pgproto3" + "github.com/jackc/pgx/v5/pgtype" +) + +const ( + connStatusUninitialized = iota + connStatusConnecting + connStatusClosed + connStatusIdle + connStatusBusy +) + +// Notice represents a notice response message reported by the PostgreSQL server. Be aware that this is distinct from +// LISTEN/NOTIFY notification. +type Notice PgError + +// Notification is a message received from the PostgreSQL LISTEN/NOTIFY system +type Notification struct { + PID uint32 // backend pid that sent the notification + Channel string // channel from which notification was received + Payload string +} + +// DialFunc is a function that can be used to connect to a PostgreSQL server. +type DialFunc func(ctx context.Context, network, addr string) (net.Conn, error) + +// LookupFunc is a function that can be used to lookup IPs addrs from host. Optionally an ip:port combination can be +// returned in order to override the connection string's port. +type LookupFunc func(ctx context.Context, host string) (addrs []string, err error) + +// BuildFrontendFunc is a function that can be used to create Frontend implementation for connection. +type BuildFrontendFunc func(r io.Reader, w io.Writer) *pgproto3.Frontend + +// PgErrorHandler is a function that handles errors returned from Postgres. This function must return true to keep +// the connection open. Returning false will cause the connection to be closed immediately. You should return +// false on any FATAL-severity errors. This will not receive network errors. The *PgConn is provided so the handler is +// aware of the origin of the error, but it must not invoke any query method. +type PgErrorHandler func(*PgConn, *PgError) bool + +// NoticeHandler is a function that can handle notices received from the PostgreSQL server. Notices can be received at +// any time, usually during handling of a query response. The *PgConn is provided so the handler is aware of the origin +// of the notice, but it must not invoke any query method. Be aware that this is distinct from LISTEN/NOTIFY +// notification. +type NoticeHandler func(*PgConn, *Notice) + +// NotificationHandler is a function that can handle notifications received from the PostgreSQL server. Notifications +// can be received at any time, usually during handling of a query response. The *PgConn is provided so the handler is +// aware of the origin of the notice, but it must not invoke any query method. Be aware that this is distinct from a +// notice event. +type NotificationHandler func(*PgConn, *Notification) + +// PgConn is a low-level PostgreSQL connection handle. It is not safe for concurrent usage. +type PgConn struct { + conn net.Conn + tlsConfig *tls.Config // tls.Config that conn was negotiated with; nil if conn is not TLS + pid uint32 // backend pid + secretKey []byte // key to use to send a cancel query message to the server + parameterStatuses map[string]string // parameters that have been reported by the server + txStatus byte + frontend *pgproto3.Frontend + bgReader *bgreader.BGReader + slowWriteTimer *time.Timer + bgReaderStarted chan struct{} + + customData map[string]any + + config *Config + + status byte // One of connStatus* constants + + bufferingReceive bool + bufferingReceiveMux sync.Mutex + bufferingReceiveMsg pgproto3.BackendMessage + bufferingReceiveErr error + + peekedMsg pgproto3.BackendMessage + + // Reusable / preallocated resources + resultReader ResultReader + multiResultReader MultiResultReader + pipeline Pipeline + contextWatcher *ctxwatch.ContextWatcher + fieldDescriptions [16]FieldDescription + + cleanupDone chan struct{} +} + +// Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value +// format) to provide configuration. See documentation for [ParseConfig] for details. ctx can be used to cancel a +// connect attempt. +func Connect(ctx context.Context, connString string) (*PgConn, error) { + config, err := ParseConfig(connString) + if err != nil { + return nil, err + } + + return ConnectConfig(ctx, config) +} + +// Connect establishes a connection to a PostgreSQL server using the environment and connString (in URL or keyword/value +// format) and ParseConfigOptions to provide additional configuration. See documentation for [ParseConfig] for details. +// ctx can be used to cancel a connect attempt. +func ConnectWithOptions(ctx context.Context, connString string, parseConfigOptions ParseConfigOptions) (*PgConn, error) { + config, err := ParseConfigWithOptions(connString, parseConfigOptions) + if err != nil { + return nil, err + } + + return ConnectConfig(ctx, config) +} + +// Connect establishes a connection to a PostgreSQL server using config. config must have been constructed with +// [ParseConfig]. ctx can be used to cancel a connect attempt. +// +// If config.Fallbacks are present they will sequentially be tried in case of error establishing network connection. An +// authentication error will terminate the chain of attempts (like libpq: +// https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS) and be returned as the error. +func ConnectConfig(ctx context.Context, config *Config) (*PgConn, error) { + // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from + // zero values. + if !config.createdByParseConfig { + panic("config must be created by ParseConfig") + } + + var allErrors []error + + connectConfigs, errs := buildConnectOneConfigs(ctx, config) + if len(errs) > 0 { + allErrors = append(allErrors, errs...) + } + + if len(connectConfigs) == 0 { + return nil, &ConnectError{Config: config, err: fmt.Errorf("hostname resolving error: %w", errors.Join(allErrors...))} + } + + pgConn, errs := connectPreferred(ctx, config, connectConfigs) + if len(errs) > 0 { + allErrors = append(allErrors, errs...) + return nil, &ConnectError{Config: config, err: errors.Join(allErrors...)} + } + + if config.AfterConnect != nil { + err := config.AfterConnect(ctx, pgConn) + if err != nil { + pgConn.conn.Close() + return nil, &ConnectError{Config: config, err: fmt.Errorf("AfterConnect error: %w", err)} + } + } + + return pgConn, nil +} + +// buildConnectOneConfigs resolves hostnames and builds a list of connectOneConfigs to try connecting to. It returns a +// slice of successfully resolved connectOneConfigs and a slice of errors. It is possible for both slices to contain +// values if some hosts were successfully resolved and others were not. +func buildConnectOneConfigs(ctx context.Context, config *Config) ([]*connectOneConfig, []error) { + // Simplify usage by treating primary config and fallbacks the same. + fallbackConfigs := []*FallbackConfig{ + { + Host: config.Host, + Port: config.Port, + TLSConfig: config.TLSConfig, + }, + } + fallbackConfigs = append(fallbackConfigs, config.Fallbacks...) + + var configs []*connectOneConfig + + var allErrors []error + + for _, fb := range fallbackConfigs { + // skip resolve for unix sockets + if isAbsolutePath(fb.Host) { + network, address := NetworkAddress(fb.Host, fb.Port) + configs = append(configs, &connectOneConfig{ + network: network, + address: address, + originalHostname: fb.Host, + tlsConfig: fb.TLSConfig, + }) + + continue + } + + ips, err := config.LookupFunc(ctx, fb.Host) + if err != nil { + allErrors = append(allErrors, err) + continue + } + + for _, ip := range ips { + splitIP, splitPort, err := net.SplitHostPort(ip) + if err == nil { + port, err := strconv.ParseUint(splitPort, 10, 16) + if err != nil { + return nil, []error{fmt.Errorf("error parsing port (%s) from lookup: %w", splitPort, err)} + } + network, address := NetworkAddress(splitIP, uint16(port)) + configs = append(configs, &connectOneConfig{ + network: network, + address: address, + originalHostname: fb.Host, + tlsConfig: fb.TLSConfig, + }) + } else { + network, address := NetworkAddress(ip, fb.Port) + configs = append(configs, &connectOneConfig{ + network: network, + address: address, + originalHostname: fb.Host, + tlsConfig: fb.TLSConfig, + }) + } + } + } + + return configs, allErrors +} + +// connectPreferred attempts to connect to the preferred host from connectOneConfigs. The connections are attempted in +// order. If a connection is successful it is returned. If no connection is successful then all errors are returned. If +// a connection attempt returns a [NotPreferredError], then that host will be used if no other hosts are successful. +func connectPreferred(ctx context.Context, config *Config, connectOneConfigs []*connectOneConfig) (*PgConn, []error) { + octx := ctx + var allErrors []error + + var fallbackConnectOneConfig *connectOneConfig + for i, c := range connectOneConfigs { + // ConnectTimeout restricts the whole connection process. + if config.ConnectTimeout != 0 { + // create new context first time or when previous host was different + if i == 0 || (connectOneConfigs[i].address != connectOneConfigs[i-1].address) { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(octx, config.ConnectTimeout) + defer cancel() + } + } else { + ctx = octx + } + + pgConn, err := connectOne(ctx, config, c, false) + if pgConn != nil { + return pgConn, nil + } + + allErrors = append(allErrors, err) + + var pgErr *PgError + if errors.As(err, &pgErr) { + // pgx will try next host even if libpq does not in certain cases (see #2246) + // consider change for the next major version + + const ERRCODE_INVALID_PASSWORD = "28P01" + const ERRCODE_INVALID_CATALOG_NAME = "3D000" // db does not exist + const ERRCODE_INSUFFICIENT_PRIVILEGE = "42501" // missing connect privilege + + // auth failed due to invalid password, db does not exist or user has no permission + if pgErr.Code == ERRCODE_INVALID_PASSWORD || + pgErr.Code == ERRCODE_INVALID_CATALOG_NAME || + pgErr.Code == ERRCODE_INSUFFICIENT_PRIVILEGE { + return nil, allErrors + } + } + + var npErr *NotPreferredError + if errors.As(err, &npErr) { + fallbackConnectOneConfig = c + } + } + + if fallbackConnectOneConfig != nil { + fallbackCtx := octx + if config.ConnectTimeout != 0 { + var cancel context.CancelFunc + fallbackCtx, cancel = context.WithTimeout(octx, config.ConnectTimeout) + defer cancel() + } + pgConn, err := connectOne(fallbackCtx, config, fallbackConnectOneConfig, true) + if err == nil { + return pgConn, nil + } + allErrors = append(allErrors, err) + } + + return nil, allErrors +} + +// connectOne makes one connection attempt to a single host. +func connectOne(ctx context.Context, config *Config, connectConfig *connectOneConfig, + ignoreNotPreferredErr bool, +) (*PgConn, error) { + pgConn := new(PgConn) + pgConn.config = config + pgConn.cleanupDone = make(chan struct{}) + pgConn.customData = make(map[string]any) + + var err error + + newPerDialConnectError := func(msg string, err error) *perDialConnectError { + err = normalizeTimeoutError(ctx, err) + e := &perDialConnectError{address: connectConfig.address, originalHostname: connectConfig.originalHostname, err: fmt.Errorf("%s: %w", msg, err)} + return e + } + + maxProtocolVersion, err := parseProtocolVersion(config.MaxProtocolVersion) + if err != nil { + return nil, newPerDialConnectError("invalid max_protocol_version", err) + } + minProtocolVersion, err := parseProtocolVersion(config.MinProtocolVersion) + if err != nil { + return nil, newPerDialConnectError("invalid min_protocol_version", err) + } + + pgConn.conn, err = config.DialFunc(ctx, connectConfig.network, connectConfig.address) + if err != nil { + return nil, newPerDialConnectError("dial error", err) + } + + if connectConfig.tlsConfig != nil { + pgConn.contextWatcher = ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: pgConn.conn}) + pgConn.contextWatcher.Watch(ctx) + var ( + tlsConn net.Conn + err error + ) + if config.SSLNegotiation == "direct" { + tlsConn = tls.Client(pgConn.conn, connectConfig.tlsConfig) + } else { + tlsConn, err = startTLS(pgConn.conn, connectConfig.tlsConfig) + } + pgConn.contextWatcher.Unwatch() // Always unwatch `netConn` after TLS. + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("tls error", err) + } + + pgConn.conn = tlsConn + pgConn.tlsConfig = connectConfig.tlsConfig + } + + if config.AfterNetConnect != nil { + pgConn.conn, err = config.AfterNetConnect(ctx, config, pgConn.conn) + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("AfterNetConnect failed", err) + } + } + + // Use a deadline-only watcher during connect. The application-supplied + // BuildContextWatcherHandler may read *PgConn fields (e.g. + // CancelRequestContextWatcherHandler reads pgConn.pid and + // pgConn.secretKey), which would race with this function's writes to + // those fields when handling BackendKeyData. The application handler is + // installed below, after the connection reaches connStatusIdle. + pgConn.contextWatcher = ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: pgConn.conn}) + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + + pgConn.parameterStatuses = make(map[string]string) + pgConn.status = connStatusConnecting + pgConn.bgReader = bgreader.New(pgConn.conn) + pgConn.slowWriteTimer = time.AfterFunc(time.Duration(math.MaxInt64), + func() { + pgConn.bgReader.Start() + pgConn.bgReaderStarted <- struct{}{} + }, + ) + pgConn.slowWriteTimer.Stop() + pgConn.bgReaderStarted = make(chan struct{}) + pgConn.frontend = config.BuildFrontend(pgConn.bgReader, pgConn.conn) + + startupMsg := pgproto3.StartupMessage{ + ProtocolVersion: maxProtocolVersion, + Parameters: make(map[string]string), + } + + // Copy default run-time params + maps.Copy(startupMsg.Parameters, config.RuntimeParams) + + startupMsg.Parameters["user"] = config.User + if config.Database != "" { + startupMsg.Parameters["database"] = config.Database + } + + pgConn.frontend.Send(&startupMsg) + if err := pgConn.flushWithPotentialWriteReadDeadlock(); err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("failed to write startup message", err) + } + + // Parse require_auth on each connect so that callers who mutate + // Config.RequireAuth after ParseConfig see their change take effect. + // The parser is pure and cheap; ParseConfigWithOptions validates the + // value up front so any parse error here indicates post-parse mutation. + requireAuthPolicy, err := parseRequireAuth(config.RequireAuth) + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("invalid require_auth", err) + } + requireAuthFail := func(err error) (*PgConn, error) { + pgConn.conn.Close() + return nil, newPerDialConnectError("require_auth check failed", err) + } + clientFinishedAuth := false + + for { + msg, err := pgConn.receiveMessage() + if err != nil { + pgConn.conn.Close() + if err, ok := err.(*PgError); ok { + return nil, newPerDialConnectError("server error", err) + } + return nil, newPerDialConnectError("failed to receive message", err) + } + + switch msg := msg.(type) { + case *pgproto3.BackendKeyData: + pgConn.pid = msg.ProcessID + pgConn.secretKey = msg.SecretKey + + case *pgproto3.AuthenticationOk: + if requireAuthPolicy.authRequired && !clientFinishedAuth { + return requireAuthFail(requireAuthPolicy.check(authMethodNone)) + } + case *pgproto3.AuthenticationCleartextPassword: + if err := requireAuthPolicy.check(authMethodPassword); err != nil { + return requireAuthFail(err) + } + err = pgConn.txPasswordMessage(pgConn.config.Password) + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("failed to write password message", err) + } + clientFinishedAuth = true + case *pgproto3.AuthenticationMD5Password: + if err := requireAuthPolicy.check(authMethodMD5); err != nil { + return requireAuthFail(err) + } + digestedPassword := "md5" + hexMD5(hexMD5(pgConn.config.Password+pgConn.config.User)+string(msg.Salt[:])) + err = pgConn.txPasswordMessage(digestedPassword) + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("failed to write password message", err) + } + clientFinishedAuth = true + case *pgproto3.AuthenticationSASL: + // Check if OAUTHBEARER is supported + serverSupportsOAuthBearer := false + for _, mech := range msg.AuthMechanisms { + if mech == "OAUTHBEARER" { + serverSupportsOAuthBearer = true + break + } + } + + if serverSupportsOAuthBearer && pgConn.config.OAuthTokenProvider != nil { + if err := requireAuthPolicy.check(authMethodOAuth); err != nil { + return requireAuthFail(err) + } + err = pgConn.oauthAuth(ctx) + } else { + if err := requireAuthPolicy.check(authMethodSCRAMSHA256); err != nil { + return requireAuthFail(err) + } + err = pgConn.scramAuth(msg.AuthMechanisms) + } + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("failed SASL auth", err) + } + clientFinishedAuth = true + case *pgproto3.AuthenticationGSS: + if err := requireAuthPolicy.check(authMethodGSS); err != nil { + return requireAuthFail(err) + } + err = pgConn.gssAuth() + if err != nil { + pgConn.conn.Close() + return nil, newPerDialConnectError("failed GSS auth", err) + } + clientFinishedAuth = true + case *pgproto3.ReadyForQuery: + pgConn.status = connStatusIdle + // The connect-phase deadline-only watcher is no longer needed; replace + // it with the application-supplied watcher so subsequent operations + // (including any queries run by ValidateConnect) use it. + pgConn.contextWatcher.Unwatch() + pgConn.contextWatcher = ctxwatch.NewContextWatcher(config.BuildContextWatcherHandler(pgConn)) + + if config.ValidateConnect != nil { + err := config.ValidateConnect(ctx, pgConn) + if err != nil { + if _, ok := err.(*NotPreferredError); ignoreNotPreferredErr && ok { + return pgConn, nil + } + pgConn.conn.Close() + return nil, newPerDialConnectError("ValidateConnect failed", err) + } + } + return pgConn, nil + case *pgproto3.ParameterStatus, *pgproto3.NoticeResponse: + // handled by ReceiveMessage + case *pgproto3.NegotiateProtocolVersion: + serverVersion := pgproto3.ProtocolVersion30&0xFFFF0000 | msg.NewestMinorProtocol + if serverVersion < minProtocolVersion { + pgConn.conn.Close() + return nil, newPerDialConnectError("server protocol version too low", nil) + } + case *pgproto3.ErrorResponse: + pgConn.conn.Close() + return nil, newPerDialConnectError("server error", ErrorResponseToPgError(msg)) + default: + pgConn.conn.Close() + return nil, newPerDialConnectError("received unexpected message", err) + } + } +} + +func startTLS(conn net.Conn, tlsConfig *tls.Config) (net.Conn, error) { + err := binary.Write(conn, binary.BigEndian, []int32{8, 80877103}) + if err != nil { + return nil, err + } + + response := make([]byte, 1) + if _, err = io.ReadFull(conn, response); err != nil { + return nil, err + } + + if response[0] != 'S' { + return nil, errors.New("server refused TLS connection") + } + + return tls.Client(conn, tlsConfig), nil +} + +func (pgConn *PgConn) txPasswordMessage(password string) (err error) { + pgConn.frontend.Send(&pgproto3.PasswordMessage{Password: password}) + return pgConn.flushWithPotentialWriteReadDeadlock() +} + +func hexMD5(s string) string { + hash := md5.New() + io.WriteString(hash, s) + return hex.EncodeToString(hash.Sum(nil)) +} + +func (pgConn *PgConn) signalMessage() chan struct{} { + if pgConn.bufferingReceive { + panic("BUG: signalMessage when already in progress") + } + + pgConn.bufferingReceive = true + pgConn.bufferingReceiveMux.Lock() + + ch := make(chan struct{}) + go func() { + pgConn.bufferingReceiveMsg, pgConn.bufferingReceiveErr = pgConn.frontend.Receive() + pgConn.bufferingReceiveMux.Unlock() + close(ch) + }() + + return ch +} + +// ReceiveMessage receives one wire protocol message from the PostgreSQL server. It must only be used when the +// connection is not busy. e.g. It is an error to call [PgConn.ReceiveMessage] while reading the result of a query. The messages +// are still handled by the core pgconn message handling system so receiving a NotificationResponse will still trigger +// the OnNotification callback. +// +// This is a very low level method that requires deep understanding of the PostgreSQL wire protocol to use correctly. +// See https://www.postgresql.org/docs/current/protocol.html. +func (pgConn *PgConn) ReceiveMessage(ctx context.Context) (pgproto3.BackendMessage, error) { + if err := pgConn.lock(); err != nil { + return nil, err + } + defer pgConn.unlock() + + if ctx != context.Background() { + select { + case <-ctx.Done(): + return nil, newContextAlreadyDoneError(ctx) + default: + } + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + msg, err := pgConn.receiveMessage() + if err != nil { + err = &pgconnError{ + msg: "receive message failed", + err: normalizeTimeoutError(ctx, err), + safeToRetry: true, + } + } + return msg, err +} + +// peekMessage peeks at the next message without setting up context cancellation. +func (pgConn *PgConn) peekMessage() (pgproto3.BackendMessage, error) { + if pgConn.peekedMsg != nil { + return pgConn.peekedMsg, nil + } + + var msg pgproto3.BackendMessage + var err error + if pgConn.bufferingReceive { + pgConn.bufferingReceiveMux.Lock() + msg = pgConn.bufferingReceiveMsg + err = pgConn.bufferingReceiveErr + pgConn.bufferingReceiveMux.Unlock() + pgConn.bufferingReceive = false + + // If a timeout error happened in the background try the read again. + var netErr net.Error + if errors.As(err, &netErr) && netErr.Timeout() { + msg, err = pgConn.frontend.Receive() + } + } else { + msg, err = pgConn.frontend.Receive() + } + + if err != nil { + // Close on anything other than timeout error - everything else is fatal + var netErr net.Error + isNetErr := errors.As(err, &netErr) + if !(isNetErr && netErr.Timeout()) { + pgConn.asyncClose() + } + + return nil, err + } + + pgConn.peekedMsg = msg + return msg, nil +} + +// receiveMessage receives a message without setting up context cancellation +func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) { + if pgConn.status == connStatusClosed { + return nil, &connLockError{status: "conn closed"} + } + + msg, err := pgConn.peekMessage() + if err != nil { + return nil, err + } + pgConn.peekedMsg = nil + + switch msg := msg.(type) { + case *pgproto3.ReadyForQuery: + pgConn.txStatus = msg.TxStatus + case *pgproto3.ParameterStatus: + pgConn.parameterStatuses[msg.Name] = msg.Value + case *pgproto3.ErrorResponse: + err := ErrorResponseToPgError(msg) + if pgConn.config.OnPgError != nil && !pgConn.config.OnPgError(pgConn, err) { + pgConn.status = connStatusClosed + pgConn.conn.Close() // Ignore error as the connection is already broken and there is already an error to return. + close(pgConn.cleanupDone) + return nil, err + } + case *pgproto3.NoticeResponse: + if pgConn.config.OnNotice != nil { + pgConn.config.OnNotice(pgConn, noticeResponseToNotice(msg)) + } + case *pgproto3.NotificationResponse: + if pgConn.config.OnNotification != nil { + pgConn.config.OnNotification(pgConn, &Notification{PID: msg.PID, Channel: msg.Channel, Payload: msg.Payload}) + } + } + + return msg, nil +} + +// Conn returns the underlying net.Conn. This rarely necessary. If the connection will be directly used for reading or +// writing then SyncConn should usually be called before Conn. +func (pgConn *PgConn) Conn() net.Conn { + return pgConn.conn +} + +// PID returns the backend PID. +func (pgConn *PgConn) PID() uint32 { + return pgConn.pid +} + +// TxStatus returns the current TxStatus as reported by the server in the ReadyForQuery message. +// +// Possible return values: +// +// 'I' - idle / not in transaction +// 'T' - in a transaction +// 'E' - in a failed transaction +// +// See https://www.postgresql.org/docs/current/protocol-message-formats.html. +func (pgConn *PgConn) TxStatus() byte { + return pgConn.txStatus +} + +// SecretKey returns the backend secret key used to send a cancel query message to the server. +func (pgConn *PgConn) SecretKey() []byte { + return pgConn.secretKey +} + +// Frontend returns the underlying *pgproto3.Frontend. This rarely necessary. +func (pgConn *PgConn) Frontend() *pgproto3.Frontend { + return pgConn.frontend +} + +// Close closes a connection. It is safe to call Close on an already closed connection. Close attempts a clean close by +// sending the exit message to PostgreSQL. However, this could block so ctx is available to limit the time to wait. The +// underlying net.Conn.Close() will always be called regardless of any other errors. +func (pgConn *PgConn) Close(ctx context.Context) error { + if pgConn.status == connStatusClosed { + return nil + } + pgConn.status = connStatusClosed + + defer close(pgConn.cleanupDone) + defer pgConn.conn.Close() + + if ctx != context.Background() { + // Close may be called while a cancellable query is in progress. This will most often be triggered by panic when + // a defer closes the connection (possibly indirectly via a transaction or a connection pool). Unwatch to end any + // previous watch. It is safe to Unwatch regardless of whether a watch is already is progress. + // + // See https://github.com/jackc/pgconn/issues/29 + pgConn.contextWatcher.Unwatch() + + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + // Ignore any errors sending Terminate message and waiting for server to close connection. + // This mimics the behavior of libpq PQfinish. It calls closePGconn which calls sendTerminateConn which purposefully + // ignores errors. + // + // See https://github.com/jackc/pgx/issues/637 + pgConn.frontend.Send(&pgproto3.Terminate{}) + pgConn.flushWithPotentialWriteReadDeadlock() + + return pgConn.conn.Close() +} + +// asyncClose marks the connection as closed and asynchronously sends a cancel query message and closes the underlying +// connection. +func (pgConn *PgConn) asyncClose() { + if pgConn.status == connStatusClosed { + return + } + pgConn.status = connStatusClosed + + go func() { + defer close(pgConn.cleanupDone) + defer pgConn.conn.Close() + + deadline := time.Now().Add(time.Second * 15) + + ctx, cancel := context.WithDeadline(context.Background(), deadline) + defer cancel() + + pgConn.CancelRequest(ctx) + + pgConn.conn.SetDeadline(deadline) + + pgConn.frontend.Send(&pgproto3.Terminate{}) + pgConn.flushWithPotentialWriteReadDeadlock() + }() +} + +// CleanupDone returns a channel that will be closed after all underlying resources have been cleaned up. A closed +// connection is no longer usable, but underlying resources, in particular the net.Conn, may not have finished closing +// yet. This is because certain errors such as a context cancellation require that the interrupted function call return +// immediately, but the error may also cause the connection to be closed. In these cases the underlying resources are +// closed asynchronously. +// +// This is only likely to be useful to connection pools. It gives them a way avoid establishing a new connection while +// an old connection is still being cleaned up and thereby exceeding the maximum pool size. +func (pgConn *PgConn) CleanupDone() chan (struct{}) { + return pgConn.cleanupDone +} + +// IsClosed reports if the connection has been closed. +// +// CleanupDone() can be used to determine if all cleanup has been completed. +func (pgConn *PgConn) IsClosed() bool { + return pgConn.status < connStatusIdle +} + +// IsBusy reports if the connection is busy. +func (pgConn *PgConn) IsBusy() bool { + return pgConn.status == connStatusBusy +} + +// lock locks the connection. +func (pgConn *PgConn) lock() error { + switch pgConn.status { + case connStatusBusy: + return &connLockError{status: "conn busy"} // This only should be possible in case of an application bug. + case connStatusClosed: + return &connLockError{status: "conn closed"} + case connStatusUninitialized: + return &connLockError{status: "conn uninitialized"} + } + pgConn.status = connStatusBusy + return nil +} + +func (pgConn *PgConn) unlock() { + switch pgConn.status { + case connStatusBusy: + pgConn.status = connStatusIdle + case connStatusClosed: + default: + panic("BUG: cannot unlock unlocked connection") // This should only be possible if there is a bug in this package. + } +} + +// ParameterStatus returns the value of a parameter reported by the server (e.g. +// server_version). Returns an empty string for unknown parameters. +func (pgConn *PgConn) ParameterStatus(key string) string { + return pgConn.parameterStatuses[key] +} + +// CommandTag is the status text returned by PostgreSQL for a query. +type CommandTag struct { + s string +} + +// NewCommandTag makes a CommandTag from s. +func NewCommandTag(s string) CommandTag { + return CommandTag{s: s} +} + +// RowsAffected returns the number of rows affected. If the CommandTag was not +// for a row affecting command (e.g. "CREATE TABLE") then it returns 0. +func (ct CommandTag) RowsAffected() int64 { + // Parse the number from the end in a single pass. + var n int64 + var mult int64 = 1 + + for i := len(ct.s) - 1; i >= 0; i-- { + c := ct.s[i] + if c >= '0' && c <= '9' { + n += int64(c-'0') * mult + mult *= 10 + } else { + break + } + } + + return n +} + +func (ct CommandTag) String() string { + return ct.s +} + +// Insert is true if the command tag starts with "INSERT". +func (ct CommandTag) Insert() bool { + return strings.HasPrefix(ct.s, "INSERT") +} + +// Update is true if the command tag starts with "UPDATE". +func (ct CommandTag) Update() bool { + return strings.HasPrefix(ct.s, "UPDATE") +} + +// Delete is true if the command tag starts with "DELETE". +func (ct CommandTag) Delete() bool { + return strings.HasPrefix(ct.s, "DELETE") +} + +// Select is true if the command tag starts with "SELECT". +func (ct CommandTag) Select() bool { + return strings.HasPrefix(ct.s, "SELECT") +} + +type FieldDescription struct { + Name string + TableOID uint32 + TableAttributeNumber uint16 + DataTypeOID uint32 + DataTypeSize int16 + TypeModifier int32 + Format int16 +} + +func (pgConn *PgConn) getFieldDescriptionSlice(n int) []FieldDescription { + if cap(pgConn.fieldDescriptions) >= n { + return pgConn.fieldDescriptions[:n:n] + } else { + return make([]FieldDescription, n) + } +} + +func convertRowDescription(dst []FieldDescription, rd *pgproto3.RowDescription) { + for i := range rd.Fields { + dst[i].Name = string(rd.Fields[i].Name) + dst[i].TableOID = rd.Fields[i].TableOID + dst[i].TableAttributeNumber = rd.Fields[i].TableAttributeNumber + dst[i].DataTypeOID = rd.Fields[i].DataTypeOID + dst[i].DataTypeSize = rd.Fields[i].DataTypeSize + dst[i].TypeModifier = rd.Fields[i].TypeModifier + dst[i].Format = rd.Fields[i].Format + } +} + +type StatementDescription struct { + Name string + SQL string + ParamOIDs []uint32 + Fields []FieldDescription +} + +// Prepare creates a prepared statement. If the name is empty, the anonymous prepared statement will be used. This +// allows Prepare to also to describe statements without creating a server-side prepared statement. +// +// Prepare does not send a PREPARE statement to the server. It uses the PostgreSQL Parse and Describe protocol messages +// directly. +// +// In extremely rare cases, Prepare may fail after the Parse is successful, but before the Describe is complete. In this +// case, the returned error will be an error where errors.As with a *PrepareError succeeds and the *PrepareError has +// ParseComplete set to true. +func (pgConn *PgConn) Prepare(ctx context.Context, name, sql string, paramOIDs []uint32) (*StatementDescription, error) { + if err := pgConn.lock(); err != nil { + return nil, err + } + defer pgConn.unlock() + + if ctx != context.Background() { + select { + case <-ctx.Done(): + return nil, newContextAlreadyDoneError(ctx) + default: + } + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + pgConn.frontend.SendParse(&pgproto3.Parse{Name: name, Query: sql, ParameterOIDs: paramOIDs}) + pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'S', Name: name}) + pgConn.frontend.SendSync(&pgproto3.Sync{}) + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + return nil, err + } + + psd := &StatementDescription{Name: name, SQL: sql} + + var ParseComplete bool + var pgErr *PgError + +readloop: + for { + msg, err := pgConn.receiveMessage() + if err != nil { + pgConn.asyncClose() + return nil, normalizeTimeoutError(ctx, err) + } + + switch msg := msg.(type) { + case *pgproto3.ParseComplete: + ParseComplete = true + case *pgproto3.ParameterDescription: + psd.ParamOIDs = make([]uint32, len(msg.ParameterOIDs)) + copy(psd.ParamOIDs, msg.ParameterOIDs) + case *pgproto3.RowDescription: + psd.Fields = make([]FieldDescription, len(msg.Fields)) + convertRowDescription(psd.Fields, msg) + case *pgproto3.ErrorResponse: + pgErr = ErrorResponseToPgError(msg) + case *pgproto3.ReadyForQuery: + break readloop + } + } + + if pgErr != nil { + return nil, &PrepareError{err: pgErr, ParseComplete: ParseComplete} + } + return psd, nil +} + +// Deallocate deallocates a prepared statement. +// +// Deallocate does not send a DEALLOCATE statement to the server. It uses the PostgreSQL Close protocol message +// directly. This has slightly different behavior than executing DEALLOCATE statement. +// - Deallocate can succeed in an aborted transaction. +// - Deallocating a non-existent prepared statement is not an error. +func (pgConn *PgConn) Deallocate(ctx context.Context, name string) error { + if err := pgConn.lock(); err != nil { + return err + } + defer pgConn.unlock() + + if ctx != context.Background() { + select { + case <-ctx.Done(): + return newContextAlreadyDoneError(ctx) + default: + } + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + pgConn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name}) + pgConn.frontend.SendSync(&pgproto3.Sync{}) + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + return err + } + + for { + msg, err := pgConn.receiveMessage() + if err != nil { + pgConn.asyncClose() + return normalizeTimeoutError(ctx, err) + } + + switch msg := msg.(type) { + case *pgproto3.ErrorResponse: + return ErrorResponseToPgError(msg) + case *pgproto3.ReadyForQuery: + return nil + } + } +} + +// ErrorResponseToPgError converts a wire protocol error message to a *PgError. +func ErrorResponseToPgError(msg *pgproto3.ErrorResponse) *PgError { + return &PgError{ + Severity: msg.Severity, + SeverityUnlocalized: msg.SeverityUnlocalized, + Code: msg.Code, + Message: msg.Message, + Detail: msg.Detail, + Hint: msg.Hint, + Position: msg.Position, + InternalPosition: msg.InternalPosition, + InternalQuery: msg.InternalQuery, + Where: msg.Where, + SchemaName: msg.SchemaName, + TableName: msg.TableName, + ColumnName: msg.ColumnName, + DataTypeName: msg.DataTypeName, + ConstraintName: msg.ConstraintName, + File: msg.File, + Line: msg.Line, + Routine: msg.Routine, + } +} + +func noticeResponseToNotice(msg *pgproto3.NoticeResponse) *Notice { + pgerr := ErrorResponseToPgError((*pgproto3.ErrorResponse)(msg)) + return (*Notice)(pgerr) +} + +// CancelRequest sends a cancel request to the PostgreSQL server. It returns an error if unable to deliver the cancel +// request, but lack of an error does not ensure that the query was canceled. As specified in the documentation, there +// is no way to be sure a query was canceled. +// See https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-CANCELING-REQUESTS +func (pgConn *PgConn) CancelRequest(ctx context.Context) error { + // Open a cancellation request to the same server. The address is taken from the net.Conn directly instead of reusing + // the connection config. This is important in high availability configurations where fallback connections may be + // specified or DNS may be used to load balance. + serverAddr := pgConn.conn.RemoteAddr() + var serverNetwork string + var serverAddress string + if serverAddr.Network() == "unix" { + // for unix sockets, RemoteAddr() calls getpeername() which returns the name the + // server passed to bind(). For Postgres, this is always a relative path "./.s.PGSQL.5432" + // so connecting to it will fail. Fall back to the config's value + serverNetwork, serverAddress = NetworkAddress(pgConn.config.Host, pgConn.config.Port) + } else { + serverNetwork, serverAddress = serverAddr.Network(), serverAddr.String() + } + cancelConn, err := pgConn.config.DialFunc(ctx, serverNetwork, serverAddress) + if err != nil { + // In case of unix sockets, RemoteAddr() returns only the file part of the path. If the + // first connect failed, try the config. + if serverAddr.Network() != "unix" { + return err + } + serverNetwork, serverAddr := NetworkAddress(pgConn.config.Host, pgConn.config.Port) + cancelConn, err = pgConn.config.DialFunc(ctx, serverNetwork, serverAddr) + if err != nil { + return err + } + } + defer cancelConn.Close() + + if ctx != context.Background() { + contextWatcher := ctxwatch.NewContextWatcher(&DeadlineContextWatcherHandler{Conn: cancelConn}) + contextWatcher.Watch(ctx) + defer contextWatcher.Unwatch() + } + + // If the primary connection is encrypted, encrypt the cancel connection the same way so the + // backend pid and secret key are not exposed to a passive network observer. This mirrors libpq's + // PQcancelCreate (PG17+), which reuses the original connection's sslmode/gssencmode for the + // cancel connection. The legacy unencrypted path is still used when the primary connection is + // plaintext (e.g. unix sockets or sslmode=disable). + if pgConn.tlsConfig != nil { + var tlsCancelConn net.Conn + if pgConn.config.SSLNegotiation == "direct" { + tlsCancelConn = tls.Client(cancelConn, pgConn.tlsConfig) + } else { + tlsCancelConn, err = startTLS(cancelConn, pgConn.tlsConfig) + if err != nil { + return fmt.Errorf("tls error on cancel connection: %w", err) + } + } + cancelConn = tlsCancelConn + defer cancelConn.Close() + } + + buf := make([]byte, 12+len(pgConn.secretKey)) + binary.BigEndian.PutUint32(buf[0:4], uint32(len(buf))) + binary.BigEndian.PutUint32(buf[4:8], 80877102) + binary.BigEndian.PutUint32(buf[8:12], pgConn.pid) + copy(buf[12:], pgConn.secretKey) + + if _, err := cancelConn.Write(buf); err != nil { + return fmt.Errorf("write to connection for cancellation: %w", err) + } + + // Wait for the cancel request to be acknowledged by the server. + // It copies the behavior of the libpq: https://github.com/postgres/postgres/blob/REL_16_0/src/interfaces/libpq/fe-connect.c#L4946-L4960 + _, _ = cancelConn.Read(buf) + + return nil +} + +// WaitForNotification waits for a LISTEN/NOTIFY message to be received. It returns an error if a notification was not +// received. +func (pgConn *PgConn) WaitForNotification(ctx context.Context) error { + if err := pgConn.lock(); err != nil { + return err + } + defer pgConn.unlock() + + if ctx != context.Background() { + select { + case <-ctx.Done(): + return newContextAlreadyDoneError(ctx) + default: + } + + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + for { + msg, err := pgConn.receiveMessage() + if err != nil { + return normalizeTimeoutError(ctx, err) + } + + if _, ok := msg.(*pgproto3.NotificationResponse); ok { + return nil + } + } +} + +// Exec executes SQL via the PostgreSQL simple query protocol. SQL may contain multiple queries. Execution is +// implicitly wrapped in a transaction unless a transaction is already in progress or SQL contains transaction control +// statements. +// +// Prefer [PgConn.ExecParams] unless executing arbitrary SQL that may contain multiple queries. +func (pgConn *PgConn) Exec(ctx context.Context, sql string) *MultiResultReader { + if err := pgConn.lock(); err != nil { + return &MultiResultReader{ + closed: true, + err: err, + } + } + + pgConn.multiResultReader = MultiResultReader{ + pgConn: pgConn, + ctx: ctx, + } + multiResult := &pgConn.multiResultReader + if ctx != context.Background() { + select { + case <-ctx.Done(): + multiResult.closed = true + multiResult.err = newContextAlreadyDoneError(ctx) + pgConn.unlock() + return multiResult + default: + } + pgConn.contextWatcher.Watch(ctx) + } + + pgConn.frontend.SendQuery(&pgproto3.Query{String: sql}) + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + pgConn.contextWatcher.Unwatch() + multiResult.closed = true + multiResult.err = err + pgConn.unlock() + return multiResult + } + + return multiResult +} + +// ExecParams executes a command via the PostgreSQL extended query protocol. +// +// sql is a SQL command string. It may only contain one query. Parameter substitution is positional using $1, $2, $3, +// etc. +// +// paramValues are the parameter values. It must be encoded in the format given by paramFormats. +// +// paramOIDs is a slice of data type OIDs for paramValues. If paramOIDs is nil, the server will infer the data type for +// all parameters. Any paramOID element that is 0 that will cause the server to infer the data type for that parameter. +// ExecParams will panic if len(paramOIDs) is not 0, 1, or len(paramValues). +// +// paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or +// binary format. If paramFormats is nil all params are text format. ExecParams will panic if +// len(paramFormats) is not 0, 1, or len(paramValues). +// +// resultFormats is a slice of format codes determining for each result column whether it is encoded in text or +// binary format. If resultFormats is nil all results will be in text format. +// +// [ResultReader] must be closed before [PgConn] can be used again. +func (pgConn *PgConn) ExecParams(ctx context.Context, sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) *ResultReader { + result := pgConn.execExtendedPrefix(ctx, paramValues) + if result.closed { + return result + } + + pgConn.frontend.SendParse(&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}) + pgConn.frontend.SendBind(&pgproto3.Bind{ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + + pgConn.execExtendedSuffix(result, nil, nil) + + return result +} + +// ExecPrepared enqueues the execution of a prepared statement via the PostgreSQL extended query protocol. +// +// paramValues are the parameter values. It must be encoded in the format given by paramFormats. +// +// paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or +// binary format. If paramFormats is nil all params are text format. ExecPrepared will panic if +// len(paramFormats) is not 0, 1, or len(paramValues). +// +// resultFormats is a slice of format codes determining for each result column whether it is encoded in text or +// binary format. If resultFormats is nil all results will be in text format. +// +// [ResultReader] must be closed before [PgConn] can be used again. +func (pgConn *PgConn) ExecPrepared(ctx context.Context, stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) *ResultReader { + result := pgConn.execExtendedPrefix(ctx, paramValues) + if result.closed { + return result + } + + pgConn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + + pgConn.execExtendedSuffix(result, nil, nil) + + return result +} + +// ExecStatement enqueues the execution of a prepared statement via the PostgreSQL extended query protocol. +// +// This differs from [PgConn.ExecPrepared] in that it takes a [*StatementDescription] instead of the prepared statement name. +// Because it has the [*StatementDescription] it can avoid the Describe Portal message that [PgConn.ExecPrepared] must send to get +// the result column descriptions. +// +// paramValues are the parameter values. It must be encoded in the format given by paramFormats. +// +// paramFormats is a slice of format codes determining for each paramValue column whether it is encoded in text or +// binary format. If paramFormats is nil all params are text format. ExecStatement will panic if len(paramFormats) is not +// 0, 1, or len(paramValues). +// +// resultFormats is a slice of format codes determining for each result column whether it is encoded in text or binary +// format. If resultFormats is nil all results will be in text format. +// +// [ResultReader] must be closed before [PgConn] can be used again. +func (pgConn *PgConn) ExecStatement(ctx context.Context, statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) *ResultReader { + result := pgConn.execExtendedPrefix(ctx, paramValues) + if result.closed { + return result + } + + pgConn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: statementDescription.Name, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + + pgConn.execExtendedSuffix(result, statementDescription, resultFormats) + + return result +} + +func (pgConn *PgConn) execExtendedPrefix(ctx context.Context, paramValues [][]byte) *ResultReader { + pgConn.resultReader = ResultReader{ + pgConn: pgConn, + ctx: ctx, + } + result := &pgConn.resultReader + + if err := pgConn.lock(); err != nil { + result.concludeCommand(CommandTag{}, err) + result.closed = true + return result + } + + if len(paramValues) > math.MaxUint16 { + result.concludeCommand(CommandTag{}, fmt.Errorf("extended protocol limited to %v parameters", math.MaxUint16)) + result.closed = true + pgConn.unlock() + return result + } + + if ctx != context.Background() { + select { + case <-ctx.Done(): + result.concludeCommand(CommandTag{}, newContextAlreadyDoneError(ctx)) + result.closed = true + pgConn.unlock() + return result + default: + } + pgConn.contextWatcher.Watch(ctx) + } + + return result +} + +func (pgConn *PgConn) execExtendedSuffix(result *ResultReader, statementDescription *StatementDescription, resultFormats []int16) { + if statementDescription == nil { + pgConn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) + } + pgConn.frontend.SendExecute(&pgproto3.Execute{}) + pgConn.frontend.SendSync(&pgproto3.Sync{}) + + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + result.concludeCommand(CommandTag{}, err) + pgConn.contextWatcher.Unwatch() + result.closed = true + pgConn.unlock() + return + } + + result.readUntilRowDescription(statementDescription, resultFormats) +} + +// CopyTo executes the copy command sql and copies the results to w. +func (pgConn *PgConn) CopyTo(ctx context.Context, w io.Writer, sql string) (CommandTag, error) { + if err := pgConn.lock(); err != nil { + return CommandTag{}, err + } + + if ctx != context.Background() { + select { + case <-ctx.Done(): + pgConn.unlock() + return CommandTag{}, newContextAlreadyDoneError(ctx) + default: + } + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + // Send copy to command + pgConn.frontend.SendQuery(&pgproto3.Query{String: sql}) + + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + pgConn.unlock() + return CommandTag{}, err + } + + // Read results + var commandTag CommandTag + var pgErr error + for { + msg, err := pgConn.receiveMessage() + if err != nil { + pgConn.asyncClose() + return CommandTag{}, normalizeTimeoutError(ctx, err) + } + + switch msg := msg.(type) { + case *pgproto3.CopyDone: + case *pgproto3.CopyData: + _, err := w.Write(msg.Data) + if err != nil { + pgConn.asyncClose() + return CommandTag{}, err + } + case *pgproto3.ReadyForQuery: + pgConn.unlock() + return commandTag, pgErr + case *pgproto3.CommandComplete: + commandTag = pgConn.makeCommandTag(msg.CommandTag) + case *pgproto3.ErrorResponse: + pgErr = ErrorResponseToPgError(msg) + } + } +} + +// CopyFrom executes the copy command sql and copies all of r to the PostgreSQL server. +// +// Note: context cancellation will only interrupt operations on the underlying PostgreSQL network connection. Reads on r +// could still block. +func (pgConn *PgConn) CopyFrom(ctx context.Context, r io.Reader, sql string) (CommandTag, error) { + if err := pgConn.lock(); err != nil { + return CommandTag{}, err + } + defer pgConn.unlock() + + if ctx != context.Background() { + select { + case <-ctx.Done(): + return CommandTag{}, newContextAlreadyDoneError(ctx) + default: + } + pgConn.contextWatcher.Watch(ctx) + defer pgConn.contextWatcher.Unwatch() + } + + // Send copy from query + pgConn.frontend.SendQuery(&pgproto3.Query{String: sql}) + err := pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + return CommandTag{}, err + } + + // Send copy data + abortCopyChan := make(chan struct{}) + copyErrChan := make(chan error, 1) + signalMessageChan := pgConn.signalMessage() + var wg sync.WaitGroup + wg.Go(func() { + buf := iobufpool.Get(65536) + defer iobufpool.Put(buf) + (*buf)[0] = 'd' + + for { + n, readErr := r.Read((*buf)[5:cap(*buf)]) + if n > 0 { + *buf = (*buf)[0 : n+5] + pgio.SetInt32((*buf)[1:], int32(n+4)) + + writeErr := pgConn.frontend.SendUnbufferedEncodedCopyData(*buf) + if writeErr != nil { + // Write errors are always fatal, but we can't use asyncClose because we are in a different goroutine. Not + // setting pgConn.status or closing pgConn.cleanupDone for the same reason. + pgConn.conn.Close() + + copyErrChan <- writeErr + return + } + } + if readErr != nil { + copyErrChan <- readErr + return + } + + select { + case <-abortCopyChan: + return + default: + } + } + }) + + var pgErr error + var copyErr error + for copyErr == nil && pgErr == nil { + select { + case copyErr = <-copyErrChan: + case <-signalMessageChan: + // If pgConn.receiveMessage encounters an error it will call pgConn.asyncClose. But that is a race condition with + // the goroutine. So instead check pgConn.bufferingReceiveErr which will have been set by the signalMessage. If an + // error is found then forcibly close the connection without sending the Terminate message. + if err := pgConn.bufferingReceiveErr; err != nil { + pgConn.status = connStatusClosed + pgConn.conn.Close() + close(pgConn.cleanupDone) + return CommandTag{}, normalizeTimeoutError(ctx, err) + } + // peekMessage never returns err in the bufferingReceive mode - it only forwards the bufferingReceive variables. + // Therefore, the only case for receiveMessage to return err is during handling of the ErrorResponse message type + // and using pgOnError handler to determine the connection is no longer valid (and thus closing the conn). + msg, serverError := pgConn.receiveMessage() + if serverError != nil { + close(abortCopyChan) + return CommandTag{}, serverError + } + + switch msg := msg.(type) { + case *pgproto3.ErrorResponse: + pgErr = ErrorResponseToPgError(msg) + default: + signalMessageChan = pgConn.signalMessage() + } + } + } + close(abortCopyChan) + // Make sure io goroutine finishes before writing. + wg.Wait() + + if copyErr == io.EOF || pgErr != nil { + pgConn.frontend.Send(&pgproto3.CopyDone{}) + } else { + pgConn.frontend.Send(&pgproto3.CopyFail{Message: copyErr.Error()}) + } + err = pgConn.flushWithPotentialWriteReadDeadlock() + if err != nil { + pgConn.asyncClose() + return CommandTag{}, err + } + + // Read results + var commandTag CommandTag + for { + msg, err := pgConn.receiveMessage() + if err != nil { + pgConn.asyncClose() + return CommandTag{}, normalizeTimeoutError(ctx, err) + } + + switch msg := msg.(type) { + case *pgproto3.ReadyForQuery: + return commandTag, pgErr + case *pgproto3.CommandComplete: + commandTag = pgConn.makeCommandTag(msg.CommandTag) + case *pgproto3.ErrorResponse: + pgErr = ErrorResponseToPgError(msg) + } + } +} + +// MultiResultReader is a reader for a command that could return multiple results such as Exec or ExecBatch. +type MultiResultReader struct { + pgConn *PgConn + ctx context.Context + + rr *ResultReader + + // Data from when the batch was queued. + statementDescriptions []*StatementDescription + resultFormats [][]int16 + + closed bool + err error +} + +// ReadAll reads all available results. Calling ReadAll is mutually exclusive with all other MultiResultReader methods. +func (mrr *MultiResultReader) ReadAll() ([]*Result, error) { + var results []*Result + + for mrr.NextResult() { + results = append(results, mrr.ResultReader().Read()) + } + err := mrr.Close() + + return results, err +} + +func (mrr *MultiResultReader) receiveMessage() (pgproto3.BackendMessage, error) { + msg, err := mrr.pgConn.receiveMessage() + if err != nil { + mrr.pgConn.contextWatcher.Unwatch() + mrr.err = normalizeTimeoutError(mrr.ctx, err) + mrr.closed = true + mrr.pgConn.asyncClose() + return nil, mrr.err + } + + switch msg := msg.(type) { + case *pgproto3.ReadyForQuery: + mrr.closed = true + mrr.pgConn.contextWatcher.Unwatch() + mrr.pgConn.unlock() + case *pgproto3.ErrorResponse: + mrr.err = ErrorResponseToPgError(msg) + } + + return msg, nil +} + +// NextResult returns advances the MultiResultReader to the next result and returns true if a result is available. +func (mrr *MultiResultReader) NextResult() bool { + for !mrr.closed && mrr.err == nil { + msg, _ := mrr.pgConn.peekMessage() + if _, ok := msg.(*pgproto3.DataRow); ok { + if len(mrr.statementDescriptions) > 0 { + rr := ResultReader{ + pgConn: mrr.pgConn, + multiResultReader: mrr, + ctx: mrr.ctx, + } + + // This result corresponds to a prepared statement description that was provided when queuing the batch. + sd := mrr.statementDescriptions[0] + mrr.statementDescriptions = mrr.statementDescriptions[1:] + + resultFormats := mrr.resultFormats[0] + mrr.resultFormats = mrr.resultFormats[1:] + + sdFields := sd.Fields + rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(sdFields)) + + err := combineFieldDescriptionsAndResultFormats(rr.fieldDescriptions, sdFields, resultFormats) + if err != nil { + rr.concludeCommand(CommandTag{}, err) + } + + mrr.pgConn.resultReader = rr + mrr.rr = &mrr.pgConn.resultReader + return true + } + + mrr.err = fmt.Errorf("unexpected DataRow message without preceding RowDescription") + return false + } + + msg, err := mrr.receiveMessage() + if err != nil { + return false + } + + switch msg := msg.(type) { + case *pgproto3.RowDescription: + mrr.pgConn.resultReader = ResultReader{ + pgConn: mrr.pgConn, + multiResultReader: mrr, + ctx: mrr.ctx, + fieldDescriptions: mrr.pgConn.getFieldDescriptionSlice(len(msg.Fields)), + } + convertRowDescription(mrr.pgConn.resultReader.fieldDescriptions, msg) + + mrr.rr = &mrr.pgConn.resultReader + return true + case *pgproto3.CommandComplete: + mrr.pgConn.resultReader = ResultReader{ + commandTag: mrr.pgConn.makeCommandTag(msg.CommandTag), + commandConcluded: true, + closed: true, + } + mrr.rr = &mrr.pgConn.resultReader + return true + case *pgproto3.EmptyQueryResponse: + mrr.pgConn.resultReader = ResultReader{ + commandConcluded: true, + closed: true, + } + mrr.rr = &mrr.pgConn.resultReader + return true + } + } + + return false +} + +// ResultReader returns the current ResultReader. +func (mrr *MultiResultReader) ResultReader() *ResultReader { + return mrr.rr +} + +// Close closes the MultiResultReader and returns the first error that occurred during the MultiResultReader's use. +func (mrr *MultiResultReader) Close() error { + for !mrr.closed { + _, err := mrr.receiveMessage() + if err != nil { + return mrr.err + } + } + + return mrr.err +} + +// ResultReader is a reader for the result of a single query. +type ResultReader struct { + pgConn *PgConn + multiResultReader *MultiResultReader + pipeline *Pipeline + ctx context.Context + + fieldDescriptions []FieldDescription + rowValues [][]byte + commandTag CommandTag + preloaded bool + commandConcluded bool + closed bool + err error +} + +// Result is the saved query response that is returned by calling Read on a ResultReader. +type Result struct { + FieldDescriptions []FieldDescription + Rows [][][]byte + CommandTag CommandTag + Err error +} + +// Read saves the query response to a Result. +func (rr *ResultReader) Read() *Result { + br := &Result{} + + for rr.NextRow() { + if br.FieldDescriptions == nil { + br.FieldDescriptions = make([]FieldDescription, len(rr.FieldDescriptions())) + copy(br.FieldDescriptions, rr.FieldDescriptions()) + } + + values := rr.Values() + row := make([][]byte, len(values)) + for i := range row { + if values[i] != nil { + row[i] = make([]byte, len(values[i])) + copy(row[i], values[i]) + } + } + br.Rows = append(br.Rows, row) + } + + br.CommandTag, br.Err = rr.Close() + + return br +} + +// NextRow advances the ResultReader to the next row and returns true if a row is available. +func (rr *ResultReader) NextRow() bool { + if rr.preloaded { + rr.preloaded = false + return true + } + + for !rr.commandConcluded { + msg, err := rr.receiveMessage() + if err != nil { + return false + } + + if msg, ok := msg.(*pgproto3.DataRow); ok { + rr.rowValues = msg.Values + return true + } + } + + return false +} + +func (rr *ResultReader) preloadRowValues(values [][]byte) { + rr.rowValues = values + rr.preloaded = true +} + +// FieldDescriptions returns the field descriptions for the current result set. The returned slice is only valid until +// the ResultReader is closed. It may return nil (for example, if the query did not return a result set or an error was +// encountered.) +func (rr *ResultReader) FieldDescriptions() []FieldDescription { + return rr.fieldDescriptions +} + +// Values returns the current row data. NextRow must have been previously been called. The returned [][]byte is only +// valid until the next NextRow call or the ResultReader is closed. +func (rr *ResultReader) Values() [][]byte { + return rr.rowValues +} + +// Close consumes any remaining result data and returns the command tag or +// error. +func (rr *ResultReader) Close() (CommandTag, error) { + if rr.closed { + return rr.commandTag, rr.err + } + rr.closed = true + + for !rr.commandConcluded { + _, err := rr.receiveMessage() + if err != nil { + return CommandTag{}, rr.err + } + } + + if rr.multiResultReader == nil && rr.pipeline == nil { + for { + msg, err := rr.receiveMessage() + if err != nil { + return CommandTag{}, rr.err + } + + switch msg := msg.(type) { + // Detect a deferred constraint violation where the ErrorResponse is sent after CommandComplete. + case *pgproto3.ErrorResponse: + rr.err = ErrorResponseToPgError(msg) + case *pgproto3.ReadyForQuery: + rr.pgConn.contextWatcher.Unwatch() + rr.pgConn.unlock() + return rr.commandTag, rr.err + } + } + } + + return rr.commandTag, rr.err +} + +// readUntilRowDescription ensures the ResultReader's fieldDescriptions are loaded. It does not return an error as any +// error will be stored in the ResultReader. +func (rr *ResultReader) readUntilRowDescription(statementDescription *StatementDescription, resultFormats []int16) { + for !rr.commandConcluded { + msg, _ := rr.receiveMessage() + switch msg := msg.(type) { + case *pgproto3.RowDescription: + return + case *pgproto3.DataRow: + rr.preloadRowValues(msg.Values) + if statementDescription != nil { + sdFields := statementDescription.Fields + rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(sdFields)) + + err := combineFieldDescriptionsAndResultFormats(rr.fieldDescriptions, sdFields, resultFormats) + if err != nil { + rr.concludeCommand(CommandTag{}, err) + } + } + return + case *pgproto3.CommandComplete: + if statementDescription != nil { + sdFields := statementDescription.Fields + rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(sdFields)) + + err := combineFieldDescriptionsAndResultFormats(rr.fieldDescriptions, sdFields, resultFormats) + if err != nil { + rr.concludeCommand(CommandTag{}, err) + } + } + return + } + } +} + +func (rr *ResultReader) receiveMessage() (msg pgproto3.BackendMessage, err error) { + if rr.multiResultReader == nil { + msg, err = rr.pgConn.receiveMessage() + } else { + msg, err = rr.multiResultReader.receiveMessage() + } + + if err != nil { + err = normalizeTimeoutError(rr.ctx, err) + rr.concludeCommand(CommandTag{}, err) + rr.pgConn.contextWatcher.Unwatch() + rr.closed = true + if rr.multiResultReader == nil { + rr.pgConn.asyncClose() + } + + return nil, rr.err + } + + switch msg := msg.(type) { + case *pgproto3.RowDescription: + rr.fieldDescriptions = rr.pgConn.getFieldDescriptionSlice(len(msg.Fields)) + convertRowDescription(rr.fieldDescriptions, msg) + case *pgproto3.CommandComplete: + rr.concludeCommand(rr.pgConn.makeCommandTag(msg.CommandTag), nil) + case *pgproto3.EmptyQueryResponse: + rr.concludeCommand(CommandTag{}, nil) + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + if rr.pipeline != nil { + rr.pipeline.state.HandleError(pgErr) + } + rr.concludeCommand(CommandTag{}, pgErr) + } + + return msg, nil +} + +func (rr *ResultReader) concludeCommand(commandTag CommandTag, err error) { + // Keep the first error that is recorded. Store the error before checking if the command is already concluded to + // allow for receiving an error after CommandComplete but before ReadyForQuery. + if err != nil && rr.err == nil { + rr.err = err + } + + if rr.commandConcluded { + return + } + + rr.commandTag = commandTag + rr.rowValues = nil + rr.commandConcluded = true +} + +// Batch is a collection of queries that can be sent to the PostgreSQL server in a single round-trip. +type Batch struct { + buf []byte + statementDescriptions []*StatementDescription + resultFormats [][]int16 + err error +} + +// ExecParams appends an ExecParams command to the batch. See PgConn.ExecParams for parameter descriptions. +func (batch *Batch) ExecParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) { + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}).Encode(batch.buf) + if batch.err != nil { + return + } + batch.ExecPrepared("", paramValues, paramFormats, resultFormats) +} + +// ExecPrepared appends an ExecPrepared e command to the batch. See PgConn.ExecPrepared for parameter descriptions. +func (batch *Batch) ExecPrepared(stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) { + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Describe{ObjectType: 'P'}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Execute{}).Encode(batch.buf) + if batch.err != nil { + return + } +} + +// ExecStatement appends an ExecStatement command to the batch. See PgConn.ExecPrepared for parameter descriptions. +// +// This differs from ExecPrepared in that it takes a *StatementDescription instead of just the prepared statement name. +// Because it has the *StatementDescription it can avoid the Describe Portal message that ExecPrepared must send to get +// the result column descriptions. +func (batch *Batch) ExecStatement(statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) { + if batch.err != nil { + return + } + + batch.buf, batch.err = (&pgproto3.Bind{PreparedStatement: statementDescription.Name, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}).Encode(batch.buf) + if batch.err != nil { + return + } + + batch.statementDescriptions = append(batch.statementDescriptions, statementDescription) + batch.resultFormats = append(batch.resultFormats, resultFormats) + + batch.buf, batch.err = (&pgproto3.Execute{}).Encode(batch.buf) + if batch.err != nil { + return + } +} + +// ExecBatch executes all the queries in batch in a single round-trip. Execution is implicitly transactional unless a +// transaction is already in progress or SQL contains transaction control statements. This is a simpler way of executing +// multiple queries in a single round trip than using pipeline mode. +func (pgConn *PgConn) ExecBatch(ctx context.Context, batch *Batch) *MultiResultReader { + if batch.err != nil { + return &MultiResultReader{ + closed: true, + err: batch.err, + } + } + + if err := pgConn.lock(); err != nil { + return &MultiResultReader{ + closed: true, + err: err, + } + } + + pgConn.multiResultReader = MultiResultReader{ + pgConn: pgConn, + ctx: ctx, + statementDescriptions: batch.statementDescriptions, + resultFormats: batch.resultFormats, + } + multiResult := &pgConn.multiResultReader + + if ctx != context.Background() { + select { + case <-ctx.Done(): + multiResult.closed = true + multiResult.err = newContextAlreadyDoneError(ctx) + pgConn.unlock() + return multiResult + default: + } + pgConn.contextWatcher.Watch(ctx) + } + + batch.buf, batch.err = (&pgproto3.Sync{}).Encode(batch.buf) + if batch.err != nil { + pgConn.contextWatcher.Unwatch() + multiResult.err = normalizeTimeoutError(multiResult.ctx, batch.err) + multiResult.closed = true + pgConn.asyncClose() + return multiResult + } + + _, err := func(buf []byte) (int, error) { + pgConn.enterPotentialWriteReadDeadlock() + defer pgConn.exitPotentialWriteReadDeadlock() + return pgConn.conn.Write(buf) + }(batch.buf) + if err != nil { + pgConn.contextWatcher.Unwatch() + multiResult.err = normalizeTimeoutError(multiResult.ctx, err) + multiResult.closed = true + pgConn.asyncClose() + return multiResult + } + + return multiResult +} + +// EscapeString escapes a string such that it can safely be interpolated into a SQL command string. It does not include +// the surrounding single quotes. +// +// The current implementation requires that standard_conforming_strings=on and client_encoding="UTF8". If these +// conditions are not met an error will be returned. It is possible these restrictions will be lifted in the future. +func (pgConn *PgConn) EscapeString(s string) (string, error) { + if pgConn.ParameterStatus("standard_conforming_strings") != "on" { + return "", errors.New("EscapeString must be run with standard_conforming_strings=on") + } + + if pgConn.ParameterStatus("client_encoding") != "UTF8" { + return "", errors.New("EscapeString must be run with client_encoding=UTF8") + } + + return strings.ReplaceAll(s, "'", "''"), nil +} + +// CheckConn checks the underlying connection without writing any bytes. This is currently implemented by doing a read +// with a very short deadline. This can be useful because a TCP connection can be broken such that a write will appear +// to succeed even though it will never actually reach the server. Reading immediately before a write will detect this +// condition. If this is done immediately before sending a query it reduces the chances a query will be sent that fails +// without the client knowing whether the server received it or not. +// +// Deprecated: CheckConn is deprecated in favor of Ping. CheckConn cannot detect all types of broken connections where +// the write would still appear to succeed. Prefer Ping unless on a high latency connection. +func (pgConn *PgConn) CheckConn() error { + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond) + defer cancel() + + _, err := pgConn.ReceiveMessage(ctx) + if err != nil { + if !Timeout(err) { + return err + } + } + + return nil +} + +// Ping pings the server. This can be useful because a TCP connection can be broken such that a write will appear to +// succeed even though it will never actually reach the server. Pinging immediately before sending a query reduces the +// chances a query will be sent that fails without the client knowing whether the server received it or not. +func (pgConn *PgConn) Ping(ctx context.Context) error { + return pgConn.Exec(ctx, "-- ping").Close() +} + +// makeCommandTag makes a CommandTag. It does not retain a reference to buf or buf's underlying memory. +func (pgConn *PgConn) makeCommandTag(buf []byte) CommandTag { + return CommandTag{s: string(buf)} +} + +// enterPotentialWriteReadDeadlock must be called before a write that could deadlock if the server is simultaneously +// blocked writing to us. +func (pgConn *PgConn) enterPotentialWriteReadDeadlock() { + // The time to wait is somewhat arbitrary. A Write should only take as long as the syscall and memcpy to the OS + // outbound network buffer unless the buffer is full (which potentially is a block). It needs to be long enough for + // the normal case, but short enough not to kill performance if a block occurs. + // + // In addition, on Windows the default timer resolution is 15.6ms. So setting the timer to less than that is + // ineffective. + if pgConn.slowWriteTimer.Reset(15 * time.Millisecond) { + panic("BUG: slow write timer already active") + } +} + +// exitPotentialWriteReadDeadlock must be called after a call to enterPotentialWriteReadDeadlock. +func (pgConn *PgConn) exitPotentialWriteReadDeadlock() { + if !pgConn.slowWriteTimer.Stop() { + // The timer starts its function in a separate goroutine. It is necessary to ensure the background reader has + // started before calling Stop. Otherwise, the background reader may not be stopped. That on its own is not a + // serious problem. But what is a serious problem is that the background reader may start at an inopportune time in + // a subsequent query. For example, if a subsequent query was canceled then a deadline may be set on the net.Conn to + // interrupt an in-progress read. After the read is interrupted, but before the deadline is cleared, the background + // reader could start and read a deadline error. Then the next query would receive the an unexpected deadline error. + <-pgConn.bgReaderStarted + pgConn.bgReader.Stop() + } +} + +func (pgConn *PgConn) flushWithPotentialWriteReadDeadlock() error { + pgConn.enterPotentialWriteReadDeadlock() + defer pgConn.exitPotentialWriteReadDeadlock() + err := pgConn.frontend.Flush() + return err +} + +// SyncConn prepares the underlying net.Conn for direct use. PgConn may internally buffer reads or use goroutines for +// background IO. This means that any direct use of the underlying net.Conn may be corrupted if a read is already +// buffered or a read is in progress. SyncConn drains read buffers and stops background IO. In some cases this may +// require sending a ping to the server. ctx can be used to cancel this operation. This should be called before any +// operation that will use the underlying net.Conn directly. e.g. Before Conn() or Hijack(). +// +// This should not be confused with the PostgreSQL protocol Sync message. +func (pgConn *PgConn) SyncConn(ctx context.Context) error { + for range 10 { + if pgConn.bgReader.Status() == bgreader.StatusStopped && pgConn.frontend.ReadBufferLen() == 0 { + return nil + } + + err := pgConn.Ping(ctx) + if err != nil { + return fmt.Errorf("SyncConn: Ping failed while syncing conn: %w", err) + } + } + + // This should never happen. Only way I can imagine this occurring is if the server is constantly sending data such as + // LISTEN/NOTIFY or log notifications such that we never can get an empty buffer. + return errors.New("SyncConn: conn never synchronized") +} + +// CustomData returns a map that can be used to associate custom data with the connection. +func (pgConn *PgConn) CustomData() map[string]any { + return pgConn.customData +} + +// HijackedConn is the result of hijacking a connection. +// +// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning +// compatibility. +type HijackedConn struct { + Conn net.Conn + TLSConfig *tls.Config // tls.Config that Conn was negotiated with; nil if Conn is not TLS + PID uint32 // backend pid + SecretKey []byte // key to use to send a cancel query message to the server + ParameterStatuses map[string]string // parameters that have been reported by the server + TxStatus byte + Frontend *pgproto3.Frontend + Config *Config + CustomData map[string]any +} + +// Hijack extracts the internal connection data. pgConn must be in an idle state. SyncConn should be called immediately +// before Hijack. pgConn is unusable after hijacking. Hijacking is typically only useful when using pgconn to establish +// a connection, but taking complete control of the raw connection after that (e.g. a load balancer or proxy). +// +// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning +// compatibility. +func (pgConn *PgConn) Hijack() (*HijackedConn, error) { + if err := pgConn.lock(); err != nil { + return nil, err + } + pgConn.status = connStatusClosed + + return &HijackedConn{ + Conn: pgConn.conn, + TLSConfig: pgConn.tlsConfig, + PID: pgConn.pid, + SecretKey: pgConn.secretKey, + ParameterStatuses: pgConn.parameterStatuses, + TxStatus: pgConn.txStatus, + Frontend: pgConn.frontend, + Config: pgConn.config, + CustomData: pgConn.customData, + }, nil +} + +// Construct created a PgConn from an already established connection to a PostgreSQL server. This is the inverse of +// PgConn.Hijack. The connection must be in an idle state. +// +// hc.Frontend is replaced by a new pgproto3.Frontend built by hc.Config.BuildFrontend. +// +// Due to the necessary exposure of internal implementation details, it is not covered by the semantic versioning +// compatibility. +func Construct(hc *HijackedConn) (*PgConn, error) { + pgConn := &PgConn{ + conn: hc.Conn, + tlsConfig: hc.TLSConfig, + pid: hc.PID, + secretKey: hc.SecretKey, + parameterStatuses: hc.ParameterStatuses, + txStatus: hc.TxStatus, + frontend: hc.Frontend, + config: hc.Config, + customData: hc.CustomData, + + status: connStatusIdle, + + cleanupDone: make(chan struct{}), + } + + pgConn.contextWatcher = ctxwatch.NewContextWatcher(hc.Config.BuildContextWatcherHandler(pgConn)) + pgConn.bgReader = bgreader.New(pgConn.conn) + pgConn.slowWriteTimer = time.AfterFunc(time.Duration(math.MaxInt64), + func() { + pgConn.bgReader.Start() + pgConn.bgReaderStarted <- struct{}{} + }, + ) + pgConn.slowWriteTimer.Stop() + pgConn.bgReaderStarted = make(chan struct{}) + pgConn.frontend = hc.Config.BuildFrontend(pgConn.bgReader, pgConn.conn) + + return pgConn, nil +} + +// Pipeline represents a connection in pipeline mode. +// +// SendPrepare, SendQueryParams, SendQueryPrepared, and SendQueryStatement queue requests to the server. These requests +// are not written until pipeline is flushed by Flush or Sync. Sync must be called after the last request is queued. +// Requests between synchronization points are implicitly transactional unless explicit transaction control statements +// have been issued. +// +// The context the pipeline was started with is in effect for the entire life of the Pipeline. +// +// For a deeper understanding of pipeline mode see the PostgreSQL documentation for the extended query protocol +// (https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) and the libpq pipeline mode +// (https://www.postgresql.org/docs/current/libpq-pipeline-mode.html). +type Pipeline struct { + conn *PgConn + ctx context.Context + + state pipelineState + err error + closed bool +} + +// PipelineSync is returned by GetResults when a ReadyForQuery message is received. +type PipelineSync struct{} + +// CloseComplete is returned by GetResults when a CloseComplete message is received. +type CloseComplete struct{} + +type pipelineRequestType int + +const ( + pipelineNil pipelineRequestType = iota + pipelinePrepare + pipelineQueryParams + pipelineQueryPrepared + pipelineQueryStatement + pipelineDeallocate + pipelineSyncRequest + pipelineFlushRequest +) + +type pipelineRequestEvent struct { + RequestType pipelineRequestType + WasSentToServer bool + BeforeFlushOrSync bool +} + +type pipelineState struct { + requestEventQueue list.List + statementDescriptionsQueue list.List + resultFormatsQueue list.List + lastRequestType pipelineRequestType + pgErr *PgError + expectedReadyForQueryCount int +} + +func (s *pipelineState) Init() { + s.requestEventQueue.Init() + s.statementDescriptionsQueue.Init() + s.resultFormatsQueue.Init() + s.lastRequestType = pipelineNil +} + +func (s *pipelineState) RegisterSendingToServer() { + for elem := s.requestEventQueue.Back(); elem != nil; elem = elem.Prev() { + val := elem.Value.(pipelineRequestEvent) + if val.WasSentToServer { + return + } + val.WasSentToServer = true + elem.Value = val + } +} + +func (s *pipelineState) registerFlushingBufferOnServer() { + for elem := s.requestEventQueue.Back(); elem != nil; elem = elem.Prev() { + val := elem.Value.(pipelineRequestEvent) + if val.BeforeFlushOrSync { + return + } + val.BeforeFlushOrSync = true + elem.Value = val + } +} + +func (s *pipelineState) PushBackRequestType(req pipelineRequestType) { + if req == pipelineNil { + return + } + + if req != pipelineFlushRequest { + s.requestEventQueue.PushBack(pipelineRequestEvent{RequestType: req}) + } + if req == pipelineFlushRequest || req == pipelineSyncRequest { + s.registerFlushingBufferOnServer() + } + s.lastRequestType = req + + if req == pipelineSyncRequest { + s.expectedReadyForQueryCount++ + } +} + +func (s *pipelineState) ExtractFrontRequestType() pipelineRequestType { + for { + elem := s.requestEventQueue.Front() + if elem == nil { + return pipelineNil + } + val := elem.Value.(pipelineRequestEvent) + if !(val.WasSentToServer && val.BeforeFlushOrSync) { + return pipelineNil + } + + s.requestEventQueue.Remove(elem) + if val.RequestType == pipelineSyncRequest { + s.pgErr = nil + } + if s.pgErr == nil { + return val.RequestType + } + } +} + +func (s *pipelineState) PushBackStatementData(sd *StatementDescription, resultFormats []int16) { + s.statementDescriptionsQueue.PushBack(sd) + s.resultFormatsQueue.PushBack(resultFormats) +} + +func (s *pipelineState) ExtractFrontStatementData() (*StatementDescription, []int16) { + sdElem := s.statementDescriptionsQueue.Front() + var sd *StatementDescription + if sdElem != nil { + s.statementDescriptionsQueue.Remove(sdElem) + sd = sdElem.Value.(*StatementDescription) + } + + rfElem := s.resultFormatsQueue.Front() + var resultFormats []int16 + if rfElem != nil { + s.resultFormatsQueue.Remove(rfElem) + resultFormats = rfElem.Value.([]int16) + } + + return sd, resultFormats +} + +func (s *pipelineState) HandleError(err *PgError) { + s.pgErr = err +} + +func (s *pipelineState) HandleReadyForQuery() { + s.expectedReadyForQueryCount-- +} + +func (s *pipelineState) PendingSync() bool { + var notPendingSync bool + + if elem := s.requestEventQueue.Back(); elem != nil { + val := elem.Value.(pipelineRequestEvent) + notPendingSync = (val.RequestType == pipelineSyncRequest) && val.WasSentToServer + } else { + notPendingSync = (s.lastRequestType == pipelineSyncRequest) || (s.lastRequestType == pipelineNil) + } + + return !notPendingSync +} + +func (s *pipelineState) ExpectedReadyForQuery() int { + return s.expectedReadyForQueryCount +} + +// StartPipeline switches the connection to pipeline mode and returns a *Pipeline. In pipeline mode requests can be sent +// to the server without waiting for a response. Close must be called on the returned *Pipeline to return the connection +// to normal mode. While in pipeline mode, no methods that communicate with the server may be called except +// CancelRequest and Close. ctx is in effect for entire life of the *Pipeline. +// +// Prefer ExecBatch when only sending one group of queries at once. +func (pgConn *PgConn) StartPipeline(ctx context.Context) *Pipeline { + if err := pgConn.lock(); err != nil { + pipeline := &Pipeline{ + closed: true, + err: err, + } + pipeline.state.Init() + + return pipeline + } + + pgConn.resultReader = ResultReader{closed: true} + + pgConn.pipeline = Pipeline{ + conn: pgConn, + ctx: ctx, + } + pgConn.pipeline.state.Init() + + pipeline := &pgConn.pipeline + + if ctx != context.Background() { + select { + case <-ctx.Done(): + pipeline.closed = true + pipeline.err = newContextAlreadyDoneError(ctx) + pgConn.unlock() + return pipeline + default: + } + pgConn.contextWatcher.Watch(ctx) + } + + return pipeline +} + +// SendPrepare is the pipeline version of *PgConn.Prepare. +func (p *Pipeline) SendPrepare(name, sql string, paramOIDs []uint32) { + if p.closed { + return + } + + p.conn.frontend.SendParse(&pgproto3.Parse{Name: name, Query: sql, ParameterOIDs: paramOIDs}) + p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'S', Name: name}) + p.state.PushBackRequestType(pipelinePrepare) +} + +// SendDeallocate deallocates a prepared statement. +func (p *Pipeline) SendDeallocate(name string) { + if p.closed { + return + } + + p.conn.frontend.SendClose(&pgproto3.Close{ObjectType: 'S', Name: name}) + p.state.PushBackRequestType(pipelineDeallocate) +} + +// SendQueryParams is the pipeline version of *PgConn.ExecParams. +func (p *Pipeline) SendQueryParams(sql string, paramValues [][]byte, paramOIDs []uint32, paramFormats, resultFormats []int16) { + if p.closed { + return + } + + p.conn.frontend.SendParse(&pgproto3.Parse{Query: sql, ParameterOIDs: paramOIDs}) + p.conn.frontend.SendBind(&pgproto3.Bind{ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) + p.conn.frontend.SendExecute(&pgproto3.Execute{}) + p.state.PushBackRequestType(pipelineQueryParams) +} + +// SendQueryPrepared is the pipeline version of *PgConn.ExecPrepared. +func (p *Pipeline) SendQueryPrepared(stmtName string, paramValues [][]byte, paramFormats, resultFormats []int16) { + if p.closed { + return + } + + p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: stmtName, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + p.conn.frontend.SendDescribe(&pgproto3.Describe{ObjectType: 'P'}) + p.conn.frontend.SendExecute(&pgproto3.Execute{}) + p.state.PushBackRequestType(pipelineQueryPrepared) +} + +// SendQueryStatement is the pipeline version of *PgConn.ExecStatement. +func (p *Pipeline) SendQueryStatement(statementDescription *StatementDescription, paramValues [][]byte, paramFormats, resultFormats []int16) { + if p.closed { + return + } + + p.conn.frontend.SendBind(&pgproto3.Bind{PreparedStatement: statementDescription.Name, ParameterFormatCodes: paramFormats, Parameters: paramValues, ResultFormatCodes: resultFormats}) + p.conn.frontend.SendExecute(&pgproto3.Execute{}) + p.state.PushBackRequestType(pipelineQueryStatement) + p.state.PushBackStatementData(statementDescription, resultFormats) +} + +// SendFlushRequest sends a request for the server to flush its output buffer. +// +// The server flushes its output buffer automatically as a result of Sync being called, +// or on any request when not in pipeline mode; this function is useful to cause the server +// to flush its output buffer in pipeline mode without establishing a synchronization point. +// Note that the request is not itself flushed to the server automatically; use Flush if +// necessary. This copies the behavior of libpq PQsendFlushRequest. +func (p *Pipeline) SendFlushRequest() { + if p.closed { + return + } + + p.conn.frontend.Send(&pgproto3.Flush{}) + p.state.PushBackRequestType(pipelineFlushRequest) +} + +// SendPipelineSync marks a synchronization point in a pipeline by sending a sync message +// without flushing the send buffer. This serves as the delimiter of an implicit +// transaction and an error recovery point. +// +// Note that the request is not itself flushed to the server automatically; use Flush if +// necessary. This copies the behavior of libpq PQsendPipelineSync. +func (p *Pipeline) SendPipelineSync() { + if p.closed { + return + } + + p.conn.frontend.SendSync(&pgproto3.Sync{}) + p.state.PushBackRequestType(pipelineSyncRequest) +} + +// Flush flushes the queued requests without establishing a synchronization point. +func (p *Pipeline) Flush() error { + if p.closed { + if p.err != nil { + return p.err + } + return errors.New("pipeline closed") + } + + err := p.conn.flushWithPotentialWriteReadDeadlock() + if err != nil { + err = normalizeTimeoutError(p.ctx, err) + + p.conn.asyncClose() + + p.conn.contextWatcher.Unwatch() + p.conn.unlock() + p.closed = true + p.err = err + return err + } + + p.state.RegisterSendingToServer() + return nil +} + +// Sync establishes a synchronization point and flushes the queued requests. +func (p *Pipeline) Sync() error { + p.SendPipelineSync() + return p.Flush() +} + +// GetResults gets the next results. If results are present, results may be a *ResultReader, *StatementDescription, or +// *PipelineSync. If an ErrorResponse is received from the server, results will be nil and err will be a *PgError. If no +// results are available, results and err will both be nil. +func (p *Pipeline) GetResults() (results any, err error) { + if p.closed { + if p.err != nil { + return nil, p.err + } + return nil, errors.New("pipeline closed") + } + + return p.getResults() +} + +func (p *Pipeline) getResults() (results any, err error) { + if !p.conn.resultReader.closed { + _, err := p.conn.resultReader.Close() + if err != nil { + return nil, err + } + } + + currentRequestType := p.state.ExtractFrontRequestType() + switch currentRequestType { + case pipelineNil: + return nil, nil + case pipelinePrepare: + return p.getResultsPrepare() + case pipelineQueryParams: + return p.getResultsQueryParams() + case pipelineQueryPrepared: + return p.getResultsQueryPrepared() + case pipelineQueryStatement: + return p.getResultsQueryStatement() + case pipelineDeallocate: + return p.getResultsDeallocate() + case pipelineSyncRequest: + return p.getResultsSync() + case pipelineFlushRequest: + return nil, errors.New("BUG: pipelineFlushRequest should not be in request queue") + default: + return nil, errors.New("BUG: unknown pipeline request type") + } +} + +func (p *Pipeline) getResultsPrepare() (*StatementDescription, error) { + err := p.receiveParseComplete("Prepare") + if err != nil { + return nil, err + } + + psd := &StatementDescription{} + + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.ParameterDescription: + psd.ParamOIDs = make([]uint32, len(msg.ParameterOIDs)) + copy(psd.ParamOIDs, msg.ParameterOIDs) + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("Prepare ParameterDescription", msg) + } + + msg, err = p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.RowDescription: + psd.Fields = make([]FieldDescription, len(msg.Fields)) + convertRowDescription(psd.Fields, msg) + return psd, nil + + // NoData is returned instead of RowDescription when there is no expected result. e.g. An INSERT without a RETURNING + // clause. + case *pgproto3.NoData: + return psd, nil + + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("Prepare RowDescription", msg) + } +} + +func (p *Pipeline) getResultsQueryParams() (*ResultReader, error) { + err := p.receiveParseComplete("QueryParams") + if err != nil { + return nil, err + } + + err = p.receiveBindComplete("QueryParams") + if err != nil { + return nil, err + } + + return p.receiveDescribedResultReader("QueryParams") +} + +func (p *Pipeline) getResultsQueryPrepared() (*ResultReader, error) { + err := p.receiveBindComplete("QueryPrepared") + if err != nil { + return nil, err + } + + return p.receiveDescribedResultReader("QueryPrepared") +} + +func (p *Pipeline) getResultsQueryStatement() (*ResultReader, error) { + err := p.receiveBindComplete("QueryStatement") + if err != nil { + return nil, err + } + + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + sd, resultFormats := p.state.ExtractFrontStatementData() + if sd == nil { + return nil, errors.New("BUG: missing statement description or result formats for QueryStatement") + } + sdFields := sd.Fields + fieldDescriptions := p.conn.getFieldDescriptionSlice(len(sdFields)) + err = combineFieldDescriptionsAndResultFormats(fieldDescriptions, sdFields, resultFormats) + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.DataRow: + rr := ResultReader{ + pgConn: p.conn, + pipeline: p, + ctx: p.ctx, + fieldDescriptions: fieldDescriptions, + } + rr.preloadRowValues(msg.Values) + p.conn.resultReader = rr + return &p.conn.resultReader, nil + case *pgproto3.CommandComplete: + p.conn.resultReader = ResultReader{ + commandTag: p.conn.makeCommandTag(msg.CommandTag), + commandConcluded: true, + closed: true, + fieldDescriptions: fieldDescriptions, + } + return &p.conn.resultReader, nil + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("QueryStatement", msg) + } +} + +func (p *Pipeline) getResultsDeallocate() (*CloseComplete, error) { + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.CloseComplete: + return &CloseComplete{}, nil + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("Deallocate", msg) + } +} + +func (p *Pipeline) getResultsSync() (*PipelineSync, error) { + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.ReadyForQuery: + p.state.HandleReadyForQuery() + return &PipelineSync{}, nil + case *pgproto3.ErrorResponse: + // Error message that is received while expecting a Sync message still consumes the expected Sync. Put it back. + p.state.requestEventQueue.PushFront(pipelineRequestEvent{RequestType: pipelineSyncRequest, WasSentToServer: true, BeforeFlushOrSync: true}) + + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage("Sync", msg) + } +} + +func (p *Pipeline) receiveParseComplete(errStr string) error { + msg, err := p.receiveMessage() + if err != nil { + return err + } + + switch msg := msg.(type) { + case *pgproto3.ParseComplete: + return nil + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + return pgErr + default: + return p.handleUnexpectedMessage(fmt.Sprintf("%s Parse", errStr), msg) + } +} + +func (p *Pipeline) receiveBindComplete(errStr string) error { + msg, err := p.receiveMessage() + if err != nil { + return err + } + + switch msg := msg.(type) { + case *pgproto3.BindComplete: + return nil + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + return pgErr + default: + return p.handleUnexpectedMessage(fmt.Sprintf("%s Bind", errStr), msg) + } +} + +func (p *Pipeline) receiveDescribedResultReader(errStr string) (*ResultReader, error) { + msg, err := p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.RowDescription: + p.conn.resultReader = ResultReader{ + pgConn: p.conn, + pipeline: p, + ctx: p.ctx, + fieldDescriptions: p.conn.getFieldDescriptionSlice(len(msg.Fields)), + } + convertRowDescription(p.conn.resultReader.fieldDescriptions, msg) + return &p.conn.resultReader, nil + case *pgproto3.NoData: + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage(fmt.Sprintf("%s RowDescription or NoData", errStr), msg) + } + + msg, err = p.receiveMessage() + if err != nil { + return nil, err + } + + switch msg := msg.(type) { + case *pgproto3.CommandComplete: + p.conn.resultReader = ResultReader{ + commandTag: p.conn.makeCommandTag(msg.CommandTag), + commandConcluded: true, + closed: true, + } + return &p.conn.resultReader, nil + case *pgproto3.ErrorResponse: + pgErr := ErrorResponseToPgError(msg) + p.state.HandleError(pgErr) + p.conn.resultReader.closed = true + return nil, pgErr + default: + return nil, p.handleUnexpectedMessage(fmt.Sprintf("%s CommandComplete", errStr), msg) + } +} + +func (p *Pipeline) receiveMessage() (pgproto3.BackendMessage, error) { + for { + msg, err := p.conn.receiveMessage() + if err != nil { + p.err = err + p.conn.asyncClose() + return nil, normalizeTimeoutError(p.ctx, err) + } + + switch msg := msg.(type) { + case *pgproto3.ParameterStatus, *pgproto3.NoticeResponse, *pgproto3.NotificationResponse: + // Filter these message types out in pipeline mode. The normal processing is handled by PgConn.receiveMessage. + default: + return msg, nil + } + } +} + +func (p *Pipeline) handleUnexpectedMessage(errStr string, msg pgproto3.BackendMessage) error { + p.err = fmt.Errorf("pipeline: %s: received unexpected message type %T", errStr, msg) + p.conn.asyncClose() + return p.err +} + +// Close closes the pipeline and returns the connection to normal mode. +func (p *Pipeline) Close() error { + if p.closed { + return p.err + } + + p.closed = true + + if p.state.PendingSync() { + p.conn.asyncClose() + p.err = errors.New("pipeline has unsynced requests") + p.conn.contextWatcher.Unwatch() + p.conn.unlock() + + return p.err + } + + for p.state.ExpectedReadyForQuery() > 0 { + results, err := p.getResults() + if err != nil { + p.err = err + var pgErr *PgError + if !errors.As(err, &pgErr) { + p.conn.asyncClose() + break + } + } else if results == nil { + // getResults returns (nil, nil) when the request queue is exhausted but + // ExpectedReadyForQuery is still > 0. This can happen when FATAL errors consume + // queued request slots without the server ever sending ReadyForQuery. + p.conn.asyncClose() + if p.err == nil { + p.err = errors.New("pipeline: no more results but expected ReadyForQuery") + } + break + } + } + + p.conn.contextWatcher.Unwatch() + p.conn.unlock() + + return p.err +} + +// DeadlineContextWatcherHandler handles canceled contexts by setting a deadline on a net.Conn. +type DeadlineContextWatcherHandler struct { + Conn net.Conn + + // DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled. + DeadlineDelay time.Duration +} + +func (h *DeadlineContextWatcherHandler) HandleCancel(ctx context.Context) { + h.Conn.SetDeadline(time.Now().Add(h.DeadlineDelay)) +} + +func (h *DeadlineContextWatcherHandler) HandleUnwatchAfterCancel() { + h.Conn.SetDeadline(time.Time{}) +} + +// CancelRequestContextWatcherHandler handles canceled contexts by sending a cancel request to the server. It also sets +// a deadline on a net.Conn as a fallback. +type CancelRequestContextWatcherHandler struct { + Conn *PgConn + + // CancelRequestDelay is the delay before sending the cancel request to the server. + CancelRequestDelay time.Duration + + // DeadlineDelay is the delay to set on the deadline set on net.Conn when the context is canceled. + DeadlineDelay time.Duration + + cancelFinishedChan chan struct{} + handleUnwatchAfterCancelCalled func() +} + +func (h *CancelRequestContextWatcherHandler) HandleCancel(context.Context) { + h.cancelFinishedChan = make(chan struct{}) + var handleUnwatchedAfterCancelCalledCtx context.Context + handleUnwatchedAfterCancelCalledCtx, h.handleUnwatchAfterCancelCalled = context.WithCancel(context.Background()) + + deadline := time.Now().Add(h.DeadlineDelay) + h.Conn.conn.SetDeadline(deadline) + + go func() { + defer close(h.cancelFinishedChan) + + select { + case <-handleUnwatchedAfterCancelCalledCtx.Done(): + return + case <-time.After(h.CancelRequestDelay): + } + + cancelRequestCtx, cancel := context.WithDeadline(handleUnwatchedAfterCancelCalledCtx, deadline) + defer cancel() + h.Conn.CancelRequest(cancelRequestCtx) + + // CancelRequest is inherently racy. Even though the cancel request has been received by the server at this point, + // it hasn't necessarily been delivered to the other connection. If we immediately return and the connection is + // immediately used then it is possible the CancelRequest will actually cancel our next query. The + // TestCancelRequestContextWatcherHandler Stress test can produce this error without the sleep below. The sleep time + // is arbitrary, but should be sufficient to prevent this error case. + time.Sleep(100 * time.Millisecond) + }() +} + +func (h *CancelRequestContextWatcherHandler) HandleUnwatchAfterCancel() { + h.handleUnwatchAfterCancelCalled() + <-h.cancelFinishedChan + + h.Conn.conn.SetDeadline(time.Time{}) +} + +func combineFieldDescriptionsAndResultFormats(outputFields, inputFields []FieldDescription, resultFormats []int16) error { + switch { + case len(resultFormats) == 0: + // No format codes provided means text format for all columns. + for i := range inputFields { + outputFields[i] = inputFields[i] + outputFields[i].Format = pgtype.TextFormatCode + } + case len(resultFormats) == 1: + // Single format code applies to all columns. + format := resultFormats[0] + for i := range inputFields { + outputFields[i] = inputFields[i] + outputFields[i].Format = format + } + case len(resultFormats) == len(inputFields): + // One format code per column. + for i := range inputFields { + outputFields[i] = inputFields[i] + outputFields[i].Format = resultFormats[i] + } + default: + // This should not occur if Bind validation is correct, but handle gracefully + return fmt.Errorf("result format codes length %d does not match field count %d", len(resultFormats), len(inputFields)) + } + + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgconn/require_auth.go b/vendor/github.com/jackc/pgx/v5/pgconn/require_auth.go new file mode 100644 index 0000000..3449a2f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgconn/require_auth.go @@ -0,0 +1,146 @@ +package pgconn + +import ( + "fmt" + "strings" +) + +// authMethod is one of the method keywords accepted by libpq's require_auth. +type authMethod uint8 + +const ( + authMethodPassword authMethod = iota + authMethodMD5 + authMethodGSS + authMethodSSPI + authMethodSCRAMSHA256 + authMethodOAuth + authMethodNone + authMethodCount +) + +var authMethodNames = [authMethodCount]string{ + authMethodPassword: "password", + authMethodMD5: "md5", + authMethodGSS: "gss", + authMethodSSPI: "sspi", + authMethodSCRAMSHA256: "scram-sha-256", + authMethodOAuth: "oauth", + authMethodNone: "none", +} + +// requireAuth is the parsed form of the require_auth connection parameter. It mirrors libpq's +// auth_required / allowed_auth_methods bookkeeping (see fe-connect.c, conn->allowed_auth_methods). +type requireAuth struct { + // raw is the original parameter value, used in error messages. + raw string + + // authRequired is true when the server must complete an authentication exchange before sending + // AuthenticationOk. It is false when the parameter is unset, fully negated, or "none" is in the + // allowed set. + authRequired bool + + // allowed is a bitmask of permitted authMethod values. + allowed uint8 +} + +func (ra requireAuth) allows(m authMethod) bool { + return ra.allowed&(1< 1 { + idx := bytes.IndexByte(authMechanisms, 0) + if idx == -1 { + return &invalidMessageFormatErr{messageType: "AuthenticationSASL", details: "unterminated string"} + } + dst.AuthMechanisms = append(dst.AuthMechanisms, string(authMechanisms[:idx])) + authMechanisms = authMechanisms[idx+1:] + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *AuthenticationSASL) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') + dst = pgio.AppendUint32(dst, AuthTypeSASL) + + for _, s := range src.AuthMechanisms { + dst = append(dst, []byte(s)...) + dst = append(dst, 0) + } + dst = append(dst, 0) + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src AuthenticationSASL) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + AuthMechanisms []string + }{ + Type: "AuthenticationSASL", + AuthMechanisms: src.AuthMechanisms, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go new file mode 100644 index 0000000..70fba4a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_continue.go @@ -0,0 +1,75 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// AuthenticationSASLContinue is a message sent from the backend containing a SASL challenge. +type AuthenticationSASLContinue struct { + Data []byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*AuthenticationSASLContinue) Backend() {} + +// Backend identifies this message as an authentication response. +func (*AuthenticationSASLContinue) AuthenticationResponse() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *AuthenticationSASLContinue) Decode(src []byte) error { + if len(src) < 4 { + return errors.New("authentication message too short") + } + + authType := binary.BigEndian.Uint32(src) + + if authType != AuthTypeSASLContinue { + return errors.New("bad auth type") + } + + dst.Data = src[4:] + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *AuthenticationSASLContinue) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') + dst = pgio.AppendUint32(dst, AuthTypeSASLContinue) + dst = append(dst, src.Data...) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src AuthenticationSASLContinue) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Data string + }{ + Type: "AuthenticationSASLContinue", + Data: string(src.Data), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *AuthenticationSASLContinue) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + Data string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.Data = []byte(msg.Data) + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go new file mode 100644 index 0000000..84976c2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/authentication_sasl_final.go @@ -0,0 +1,75 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// AuthenticationSASLFinal is a message sent from the backend indicating a SASL authentication has completed. +type AuthenticationSASLFinal struct { + Data []byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*AuthenticationSASLFinal) Backend() {} + +// Backend identifies this message as an authentication response. +func (*AuthenticationSASLFinal) AuthenticationResponse() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *AuthenticationSASLFinal) Decode(src []byte) error { + if len(src) < 4 { + return errors.New("authentication message too short") + } + + authType := binary.BigEndian.Uint32(src) + + if authType != AuthTypeSASLFinal { + return errors.New("bad auth type") + } + + dst.Data = src[4:] + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *AuthenticationSASLFinal) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'R') + dst = pgio.AppendUint32(dst, AuthTypeSASLFinal) + dst = append(dst, src.Data...) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Unmarshaler. +func (src AuthenticationSASLFinal) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Data string + }{ + Type: "AuthenticationSASLFinal", + Data: string(src.Data), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *AuthenticationSASLFinal) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + Data string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.Data = []byte(msg.Data) + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go b/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go new file mode 100644 index 0000000..65388ad --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/backend.go @@ -0,0 +1,299 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" +) + +// Backend acts as a server for the PostgreSQL wire protocol version 3. +type Backend struct { + cr *chunkReader + w io.Writer + + // tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced + // before it is actually transmitted (i.e. before Flush). + tracer *tracer + + wbuf []byte + encodeError error + + // Frontend message flyweights + bind Bind + cancelRequest CancelRequest + _close Close + copyFail CopyFail + copyData CopyData + copyDone CopyDone + describe Describe + execute Execute + flush Flush + functionCall FunctionCall + gssEncRequest GSSEncRequest + parse Parse + query Query + sslRequest SSLRequest + startupMessage StartupMessage + sync Sync + terminate Terminate + + bodyLen int + maxBodyLen int // maxBodyLen is the maximum length of a message body in octets. If a message body exceeds this length, Receive will return an error. + msgType byte + partialMsg bool + authType uint32 +} + +const ( + minStartupPacketLen = 4 // minStartupPacketLen is a single 32-bit int version or code. + maxStartupPacketLen = 10_000 // maxStartupPacketLen is MAX_STARTUP_PACKET_LENGTH from PG source. +) + +// NewBackend creates a new Backend. +func NewBackend(r io.Reader, w io.Writer) *Backend { + cr := newChunkReader(r, 0) + return &Backend{cr: cr, w: w} +} + +// Send sends a message to the frontend (i.e. the client). The message is buffered until Flush is called. Any error +// encountered will be returned from Flush. +func (b *Backend) Send(msg BackendMessage) { + if b.encodeError != nil { + return + } + + prevLen := len(b.wbuf) + newBuf, err := msg.Encode(b.wbuf) + if err != nil { + b.encodeError = err + return + } + b.wbuf = newBuf + + if b.tracer != nil { + b.tracer.traceMessage('B', int32(len(b.wbuf)-prevLen), msg) + } +} + +// Flush writes any pending messages to the frontend (i.e. the client). +func (b *Backend) Flush() error { + if err := b.encodeError; err != nil { + b.encodeError = nil + b.wbuf = b.wbuf[:0] + return &writeError{err: err, safeToRetry: true} + } + + n, err := b.w.Write(b.wbuf) + + const maxLen = 1024 + if len(b.wbuf) > maxLen { + b.wbuf = make([]byte, 0, maxLen) + } else { + b.wbuf = b.wbuf[:0] + } + + if err != nil { + return &writeError{err: err, safeToRetry: n == 0} + } + + return nil +} + +// Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function +// PQtrace. +func (b *Backend) Trace(w io.Writer, options TracerOptions) { + b.tracer = &tracer{ + w: w, + buf: &bytes.Buffer{}, + TracerOptions: options, + } +} + +// Untrace stops tracing. +func (b *Backend) Untrace() { + b.tracer = nil +} + +// ReceiveStartupMessage receives the initial connection message. This method is used of the normal Receive method +// because the initial connection message is "special" and does not include the message type as the first byte. This +// will return either a StartupMessage, SSLRequest, GSSEncRequest, or CancelRequest. +func (b *Backend) ReceiveStartupMessage() (FrontendMessage, error) { + buf, err := b.cr.Next(4) + if err != nil { + return nil, err + } + msgSize := int(int32(binary.BigEndian.Uint32(buf)) - 4) + + if msgSize < minStartupPacketLen || msgSize > maxStartupPacketLen { + return nil, fmt.Errorf("invalid length of startup packet: %d", msgSize) + } + + buf, err = b.cr.Next(msgSize) + if err != nil { + return nil, translateEOFtoErrUnexpectedEOF(err) + } + + code := binary.BigEndian.Uint32(buf) + + switch code { + case ProtocolVersion30, ProtocolVersion32: + err = b.startupMessage.Decode(buf) + if err != nil { + return nil, err + } + return &b.startupMessage, nil + case sslRequestNumber: + err = b.sslRequest.Decode(buf) + if err != nil { + return nil, err + } + return &b.sslRequest, nil + case cancelRequestCode: + err = b.cancelRequest.Decode(buf) + if err != nil { + return nil, err + } + return &b.cancelRequest, nil + case gssEncReqNumber: + err = b.gssEncRequest.Decode(buf) + if err != nil { + return nil, err + } + return &b.gssEncRequest, nil + default: + return nil, fmt.Errorf("unknown startup message code: %d", code) + } +} + +// Receive receives a message from the frontend. The returned message is only valid until the next call to Receive. +func (b *Backend) Receive() (FrontendMessage, error) { + if !b.partialMsg { + header, err := b.cr.Next(5) + if err != nil { + return nil, translateEOFtoErrUnexpectedEOF(err) + } + + b.msgType = header[0] + + msgLength := int(int32(binary.BigEndian.Uint32(header[1:]))) + if msgLength < 4 { + return nil, fmt.Errorf("invalid message length: %d", msgLength) + } + + b.bodyLen = msgLength - 4 + if b.maxBodyLen > 0 && b.bodyLen > b.maxBodyLen { + return nil, &ExceededMaxBodyLenErr{b.maxBodyLen, b.bodyLen} + } + b.partialMsg = true + } + + var msg FrontendMessage + switch b.msgType { + case 'B': + msg = &b.bind + case 'C': + msg = &b._close + case 'D': + msg = &b.describe + case 'E': + msg = &b.execute + case 'F': + msg = &b.functionCall + case 'f': + msg = &b.copyFail + case 'd': + msg = &b.copyData + case 'c': + msg = &b.copyDone + case 'H': + msg = &b.flush + case 'P': + msg = &b.parse + case 'p': + switch b.authType { + case AuthTypeSASL: + msg = &SASLInitialResponse{} + case AuthTypeSASLContinue: + msg = &SASLResponse{} + case AuthTypeSASLFinal: + msg = &SASLResponse{} + case AuthTypeGSS, AuthTypeGSSCont: + msg = &GSSResponse{} + case AuthTypeCleartextPassword, AuthTypeMD5Password: + fallthrough + default: + // to maintain backwards compatibility + msg = &PasswordMessage{} + } + case 'Q': + msg = &b.query + case 'S': + msg = &b.sync + case 'X': + msg = &b.terminate + default: + return nil, fmt.Errorf("unknown message type: %c", b.msgType) + } + + msgBody, err := b.cr.Next(b.bodyLen) + if err != nil { + return nil, translateEOFtoErrUnexpectedEOF(err) + } + + b.partialMsg = false + + err = msg.Decode(msgBody) + if err != nil { + return nil, err + } + + if b.tracer != nil { + b.tracer.traceMessage('F', int32(5+len(msgBody)), msg) + } + + return msg, nil +} + +// SetAuthType sets the authentication type in the backend. +// Since multiple message types can start with 'p', SetAuthType allows +// contextual identification of FrontendMessages. For example, in the +// PG message flow documentation for PasswordMessage: +// +// Byte1('p') +// +// Identifies the message as a password response. Note that this is also used for +// GSSAPI, SSPI and SASL response messages. The exact message type can be deduced from +// the context. +// +// Since the Frontend does not know about the state of a backend, it is important +// to call SetAuthType() after an authentication request is received by the Frontend. +func (b *Backend) SetAuthType(authType uint32) error { + switch authType { + case AuthTypeOk, + AuthTypeCleartextPassword, + AuthTypeMD5Password, + AuthTypeSCMCreds, + AuthTypeGSS, + AuthTypeGSSCont, + AuthTypeSSPI, + AuthTypeSASL, + AuthTypeSASLContinue, + AuthTypeSASLFinal: + b.authType = authType + default: + return fmt.Errorf("authType not recognized: %d", authType) + } + + return nil +} + +// SetMaxBodyLen sets the maximum length of a message body in octets. +// If a message body exceeds this length, Receive will return an error. +// This is useful for protecting against malicious clients that send +// large messages with the intent of causing memory exhaustion. +// The default value is 0. +// If maxBodyLen is 0, then no maximum is enforced. +func (b *Backend) SetMaxBodyLen(maxBodyLen int) { + b.maxBodyLen = maxBodyLen +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go new file mode 100644 index 0000000..c73b2da --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/backend_key_data.go @@ -0,0 +1,71 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/hex" + "encoding/json" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type BackendKeyData struct { + ProcessID uint32 + SecretKey []byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*BackendKeyData) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *BackendKeyData) Decode(src []byte) error { + if len(src) < 8 { + return &invalidMessageLenErr{messageType: "BackendKeyData", expectedLen: 8, actualLen: len(src)} + } + + dst.ProcessID = binary.BigEndian.Uint32(src[:4]) + dst.SecretKey = make([]byte, len(src)-4) + copy(dst.SecretKey, src[4:]) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *BackendKeyData) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'K') + dst = pgio.AppendUint32(dst, src.ProcessID) + dst = append(dst, src.SecretKey...) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src BackendKeyData) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ProcessID uint32 + SecretKey string + }{ + Type: "BackendKeyData", + ProcessID: src.ProcessID, + SecretKey: hex.EncodeToString(src.SecretKey), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *BackendKeyData) UnmarshalJSON(data []byte) error { + var msg struct { + ProcessID uint32 + SecretKey string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.ProcessID = msg.ProcessID + secretKey, err := hex.DecodeString(msg.SecretKey) + if err != nil { + return err + } + dst.SecretKey = secretKey + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go b/vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go new file mode 100644 index 0000000..f7bdb97 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/big_endian.go @@ -0,0 +1,37 @@ +package pgproto3 + +import ( + "encoding/binary" +) + +type BigEndianBuf [8]byte + +func (b BigEndianBuf) Int16(n int16) []byte { + buf := b[0:2] + binary.BigEndian.PutUint16(buf, uint16(n)) + return buf +} + +func (b BigEndianBuf) Uint16(n uint16) []byte { + buf := b[0:2] + binary.BigEndian.PutUint16(buf, n) + return buf +} + +func (b BigEndianBuf) Int32(n int32) []byte { + buf := b[0:4] + binary.BigEndian.PutUint32(buf, uint32(n)) + return buf +} + +func (b BigEndianBuf) Uint32(n uint32) []byte { + buf := b[0:4] + binary.BigEndian.PutUint32(buf, n) + return buf +} + +func (b BigEndianBuf) Int64(n int64) []byte { + buf := b[0:8] + binary.BigEndian.PutUint64(buf, uint64(n)) + return buf +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go b/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go new file mode 100644 index 0000000..fb56e4d --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/bind.go @@ -0,0 +1,223 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Bind struct { + DestinationPortal string + PreparedStatement string + ParameterFormatCodes []int16 + Parameters [][]byte + ResultFormatCodes []int16 +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Bind) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Bind) Decode(src []byte) error { + *dst = Bind{} + + idx := bytes.IndexByte(src, 0) + if idx < 0 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + dst.DestinationPortal = string(src[:idx]) + rp := idx + 1 + + idx = bytes.IndexByte(src[rp:], 0) + if idx < 0 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + dst.PreparedStatement = string(src[rp : rp+idx]) + rp += idx + 1 + + if len(src[rp:]) < 2 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + parameterFormatCodeCount := int(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + if parameterFormatCodeCount > 0 { + dst.ParameterFormatCodes = make([]int16, parameterFormatCodeCount) + + if len(src[rp:]) < len(dst.ParameterFormatCodes)*2 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + for i := range parameterFormatCodeCount { + dst.ParameterFormatCodes[i] = int16(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + } + } + + if len(src[rp:]) < 2 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + parameterCount := int(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + if parameterCount > 0 { + dst.Parameters = make([][]byte, parameterCount) + + for i := range parameterCount { + if len(src[rp:]) < 4 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + + msgSize := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + + // null + if msgSize == -1 { + continue + } + + if msgSize < 0 || len(src[rp:]) < msgSize { + return &invalidMessageFormatErr{messageType: "Bind"} + } + + dst.Parameters[i] = src[rp : rp+msgSize] + rp += msgSize + } + } + + if len(src[rp:]) < 2 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + resultFormatCodeCount := int(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + dst.ResultFormatCodes = make([]int16, resultFormatCodeCount) + if len(src[rp:]) < len(dst.ResultFormatCodes)*2 { + return &invalidMessageFormatErr{messageType: "Bind"} + } + for i := range resultFormatCodeCount { + dst.ResultFormatCodes[i] = int16(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Bind) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'B') + + dst = append(dst, src.DestinationPortal...) + dst = append(dst, 0) + dst = append(dst, src.PreparedStatement...) + dst = append(dst, 0) + + if len(src.ParameterFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many parameter format codes") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ParameterFormatCodes))) + for _, fc := range src.ParameterFormatCodes { + dst = pgio.AppendInt16(dst, fc) + } + + if len(src.Parameters) > math.MaxUint16 { + return nil, errors.New("too many parameters") + } + dst = pgio.AppendUint16(dst, uint16(len(src.Parameters))) + for _, p := range src.Parameters { + if p == nil { + dst = pgio.AppendInt32(dst, -1) + continue + } + + dst = pgio.AppendInt32(dst, int32(len(p))) + dst = append(dst, p...) + } + + if len(src.ResultFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many result format codes") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ResultFormatCodes))) + for _, fc := range src.ResultFormatCodes { + dst = pgio.AppendInt16(dst, fc) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Bind) MarshalJSON() ([]byte, error) { + formattedParameters := make([]map[string]string, len(src.Parameters)) + for i, p := range src.Parameters { + if p == nil { + continue + } + + textFormat := true + if len(src.ParameterFormatCodes) == 1 { + textFormat = src.ParameterFormatCodes[0] == 0 + } else if len(src.ParameterFormatCodes) > 1 { + textFormat = src.ParameterFormatCodes[i] == 0 + } + + if textFormat { + formattedParameters[i] = map[string]string{"text": string(p)} + } else { + formattedParameters[i] = map[string]string{"binary": hex.EncodeToString(p)} + } + } + + return json.Marshal(struct { + Type string + DestinationPortal string + PreparedStatement string + ParameterFormatCodes []int16 + Parameters []map[string]string + ResultFormatCodes []int16 + }{ + Type: "Bind", + DestinationPortal: src.DestinationPortal, + PreparedStatement: src.PreparedStatement, + ParameterFormatCodes: src.ParameterFormatCodes, + Parameters: formattedParameters, + ResultFormatCodes: src.ResultFormatCodes, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *Bind) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + DestinationPortal string + PreparedStatement string + ParameterFormatCodes []int16 + Parameters []map[string]string + ResultFormatCodes []int16 + } + err := json.Unmarshal(data, &msg) + if err != nil { + return err + } + dst.DestinationPortal = msg.DestinationPortal + dst.PreparedStatement = msg.PreparedStatement + dst.ParameterFormatCodes = msg.ParameterFormatCodes + dst.Parameters = make([][]byte, len(msg.Parameters)) + dst.ResultFormatCodes = msg.ResultFormatCodes + for n, parameter := range msg.Parameters { + dst.Parameters[n], err = getValueFromJSON(parameter) + if err != nil { + return fmt.Errorf("cannot get param %d: %w", n, err) + } + } + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go new file mode 100644 index 0000000..bacf30d --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/bind_complete.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type BindComplete struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*BindComplete) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *BindComplete) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "BindComplete", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *BindComplete) Encode(dst []byte) ([]byte, error) { + return append(dst, '2', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src BindComplete) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "BindComplete", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go new file mode 100644 index 0000000..63ebe5c --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/cancel_request.go @@ -0,0 +1,85 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const cancelRequestCode = 80877102 + +type CancelRequest struct { + ProcessID uint32 + SecretKey []byte +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*CancelRequest) Frontend() {} + +func (dst *CancelRequest) Decode(src []byte) error { + if len(src) < 12 { + return errors.New("cancel request too short") + } + if len(src) > 264 { + return errors.New("cancel request too long") + } + + requestCode := binary.BigEndian.Uint32(src) + if requestCode != cancelRequestCode { + return errors.New("bad cancel request code") + } + + dst.ProcessID = binary.BigEndian.Uint32(src[4:]) + dst.SecretKey = make([]byte, len(src)-8) + copy(dst.SecretKey, src[8:]) + + return nil +} + +// Encode encodes src into dst. dst will include the 4 byte message length. +func (src *CancelRequest) Encode(dst []byte) ([]byte, error) { + if len(src.SecretKey) > 256 { + return nil, errors.New("secret key too long") + } + msgLen := int32(12 + len(src.SecretKey)) + dst = pgio.AppendInt32(dst, msgLen) + dst = pgio.AppendInt32(dst, cancelRequestCode) + dst = pgio.AppendUint32(dst, src.ProcessID) + dst = append(dst, src.SecretKey...) + return dst, nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CancelRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ProcessID uint32 + SecretKey string + }{ + Type: "CancelRequest", + ProcessID: src.ProcessID, + SecretKey: hex.EncodeToString(src.SecretKey), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *CancelRequest) UnmarshalJSON(data []byte) error { + var msg struct { + ProcessID uint32 + SecretKey string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.ProcessID = msg.ProcessID + secretKey, err := hex.DecodeString(msg.SecretKey) + if err != nil { + return err + } + dst.SecretKey = secretKey + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go b/vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go new file mode 100644 index 0000000..fc0fa61 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/chunkreader.go @@ -0,0 +1,90 @@ +package pgproto3 + +import ( + "io" + + "github.com/jackc/pgx/v5/internal/iobufpool" +) + +// chunkReader is a io.Reader wrapper that minimizes IO reads and memory allocations. It allocates memory in chunks and +// will read as much as will fit in the current buffer in a single call regardless of how large a read is actually +// requested. The memory returned via Next is only valid until the next call to Next. +// +// This is roughly equivalent to a bufio.Reader that only uses Peek and Discard to never copy bytes. +type chunkReader struct { + r io.Reader + + buf *[]byte + rp, wp int // buf read position and write position + + minBufSize int +} + +// newChunkReader creates and returns a new chunkReader for r with default configuration. If minBufSize is <= 0 it uses +// a default value. +func newChunkReader(r io.Reader, minBufSize int) *chunkReader { + if minBufSize <= 0 { + // By historical reasons Postgres currently has 8KB send buffer inside, + // so here we want to have at least the same size buffer. + // @see https://github.com/postgres/postgres/blob/249d64999615802752940e017ee5166e726bc7cd/src/backend/libpq/pqcomm.c#L134 + // @see https://www.postgresql.org/message-id/0cdc5485-cb3c-5e16-4a46-e3b2f7a41322%40ya.ru + // + // In addition, testing has found no benefit of any larger buffer. + minBufSize = 8192 + } + + return &chunkReader{ + r: r, + minBufSize: minBufSize, + buf: iobufpool.Get(minBufSize), + } +} + +// Next returns buf filled with the next n bytes. buf is only valid until next call of Next. If an error occurs, buf +// will be nil. +func (r *chunkReader) Next(n int) (buf []byte, err error) { + // Reset the buffer if it is empty + if r.rp == r.wp { + if len(*r.buf) != r.minBufSize { + iobufpool.Put(r.buf) + r.buf = iobufpool.Get(r.minBufSize) + } + r.rp = 0 + r.wp = 0 + } + + // n bytes already in buf + if (r.wp - r.rp) >= n { + buf = (*r.buf)[r.rp : r.rp+n : r.rp+n] + r.rp += n + return buf, err + } + + // buf is smaller than requested number of bytes + if len(*r.buf) < n { + bigBuf := iobufpool.Get(n) + r.wp = copy((*bigBuf), (*r.buf)[r.rp:r.wp]) + r.rp = 0 + iobufpool.Put(r.buf) + r.buf = bigBuf + } + + // buf is large enough, but need to shift filled area to start to make enough contiguous space + minReadCount := n - (r.wp - r.rp) + if (len(*r.buf) - r.wp) < minReadCount { + r.wp = copy((*r.buf), (*r.buf)[r.rp:r.wp]) + r.rp = 0 + } + + // Read at least the required number of bytes from the underlying io.Reader + readBytesCount, err := io.ReadAtLeast(r.r, (*r.buf)[r.wp:], minReadCount) + r.wp += readBytesCount + // fmt.Println("read", n) + if err != nil { + return nil, err + } + + buf = (*r.buf)[r.rp : r.rp+n : r.rp+n] + r.rp += n + return buf, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/close.go b/vendor/github.com/jackc/pgx/v5/pgproto3/close.go new file mode 100644 index 0000000..0e7e049 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/close.go @@ -0,0 +1,81 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" + "errors" +) + +type Close struct { + ObjectType byte // 'S' = prepared statement, 'P' = portal + Name string +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Close) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Close) Decode(src []byte) error { + if len(src) < 2 { + return &invalidMessageFormatErr{messageType: "Close"} + } + + dst.ObjectType = src[0] + rp := 1 + + idx := bytes.IndexByte(src[rp:], 0) + if idx != len(src[rp:])-1 { + return &invalidMessageFormatErr{messageType: "Close"} + } + + dst.Name = string(src[rp : len(src)-1]) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Close) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'C') + dst = append(dst, src.ObjectType) + dst = append(dst, src.Name...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Close) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ObjectType string + Name string + }{ + Type: "Close", + ObjectType: string(src.ObjectType), + Name: src.Name, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *Close) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + ObjectType string + Name string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + if len(msg.ObjectType) != 1 { + return errors.New("invalid length for Close.ObjectType") + } + + dst.ObjectType = msg.ObjectType[0] + dst.Name = msg.Name + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go new file mode 100644 index 0000000..833f7a1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/close_complete.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type CloseComplete struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*CloseComplete) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CloseComplete) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "CloseComplete", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CloseComplete) Encode(dst []byte) ([]byte, error) { + return append(dst, '3', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CloseComplete) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "CloseComplete", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go new file mode 100644 index 0000000..eba7094 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/command_complete.go @@ -0,0 +1,66 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" +) + +type CommandComplete struct { + CommandTag []byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*CommandComplete) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CommandComplete) Decode(src []byte) error { + idx := bytes.IndexByte(src, 0) + if idx == -1 { + return &invalidMessageFormatErr{messageType: "CommandComplete", details: "unterminated string"} + } + if idx != len(src)-1 { + return &invalidMessageFormatErr{messageType: "CommandComplete", details: "string terminated too early"} + } + + dst.CommandTag = src[:idx] + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CommandComplete) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'C') + dst = append(dst, src.CommandTag...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CommandComplete) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + CommandTag string + }{ + Type: "CommandComplete", + CommandTag: string(src.CommandTag), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *CommandComplete) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + CommandTag string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.CommandTag = []byte(msg.CommandTag) + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go new file mode 100644 index 0000000..e2a402f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_both_response.go @@ -0,0 +1,95 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type CopyBothResponse struct { + OverallFormat byte + ColumnFormatCodes []uint16 +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*CopyBothResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CopyBothResponse) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + if buf.Len() < 3 { + return &invalidMessageFormatErr{messageType: "CopyBothResponse"} + } + + overallFormat := buf.Next(1)[0] + + columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) + if buf.Len() != columnCount*2 { + return &invalidMessageFormatErr{messageType: "CopyBothResponse"} + } + + columnFormatCodes := make([]uint16, columnCount) + for i := range columnCount { + columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) + } + + *dst = CopyBothResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CopyBothResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'W') + dst = append(dst, src.OverallFormat) + if len(src.ColumnFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many column format codes") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) + for _, fc := range src.ColumnFormatCodes { + dst = pgio.AppendUint16(dst, fc) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CopyBothResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ColumnFormatCodes []uint16 + }{ + Type: "CopyBothResponse", + ColumnFormatCodes: src.ColumnFormatCodes, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *CopyBothResponse) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + OverallFormat string + ColumnFormatCodes []uint16 + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + if len(msg.OverallFormat) != 1 { + return errors.New("invalid length for CopyBothResponse.OverallFormat") + } + + dst.OverallFormat = msg.OverallFormat[0] + dst.ColumnFormatCodes = msg.ColumnFormatCodes + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go new file mode 100644 index 0000000..d72e1f3 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_data.go @@ -0,0 +1,67 @@ +package pgproto3 + +import ( + "encoding/hex" + "encoding/json" +) + +type CopyData struct { + Data []byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*CopyData) Backend() {} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*CopyData) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CopyData) Decode(src []byte) error { + dst.Data = src + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CopyData) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'd') + dst = append(dst, src.Data...) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CopyData) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Data string + }{ + Type: "CopyData", + Data: hex.EncodeToString(src.Data), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *CopyData) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + Data string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + if msg.Data == "" { + dst.Data = []byte{} + return nil + } + b, err := hex.DecodeString(msg.Data) + if err != nil { + return err + } + dst.Data = b + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go new file mode 100644 index 0000000..c3421a9 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_done.go @@ -0,0 +1,37 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type CopyDone struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*CopyDone) Backend() {} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*CopyDone) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CopyDone) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "CopyDone", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CopyDone) Encode(dst []byte) ([]byte, error) { + return append(dst, 'c', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CopyDone) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "CopyDone", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go new file mode 100644 index 0000000..f8a00b8 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_fail.go @@ -0,0 +1,49 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" +) + +type CopyFail struct { + Message string +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*CopyFail) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CopyFail) Decode(src []byte) error { + if len(src) == 0 { + return &invalidMessageFormatErr{messageType: "CopyFail"} + } + + idx := bytes.IndexByte(src, 0) + if idx != len(src)-1 { + return &invalidMessageFormatErr{messageType: "CopyFail"} + } + + dst.Message = string(src[:idx]) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CopyFail) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'f') + dst = append(dst, src.Message...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CopyFail) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Message string + }{ + Type: "CopyFail", + Message: src.Message, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go new file mode 100644 index 0000000..0633935 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_in_response.go @@ -0,0 +1,96 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type CopyInResponse struct { + OverallFormat byte + ColumnFormatCodes []uint16 +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*CopyInResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CopyInResponse) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + if buf.Len() < 3 { + return &invalidMessageFormatErr{messageType: "CopyInResponse"} + } + + overallFormat := buf.Next(1)[0] + + columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) + if buf.Len() != columnCount*2 { + return &invalidMessageFormatErr{messageType: "CopyInResponse"} + } + + columnFormatCodes := make([]uint16, columnCount) + for i := range columnCount { + columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) + } + + *dst = CopyInResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CopyInResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'G') + + dst = append(dst, src.OverallFormat) + if len(src.ColumnFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many column format codes") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) + for _, fc := range src.ColumnFormatCodes { + dst = pgio.AppendUint16(dst, fc) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CopyInResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ColumnFormatCodes []uint16 + }{ + Type: "CopyInResponse", + ColumnFormatCodes: src.ColumnFormatCodes, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *CopyInResponse) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + OverallFormat string + ColumnFormatCodes []uint16 + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + if len(msg.OverallFormat) != 1 { + return errors.New("invalid length for CopyInResponse.OverallFormat") + } + + dst.OverallFormat = msg.OverallFormat[0] + dst.ColumnFormatCodes = msg.ColumnFormatCodes + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go new file mode 100644 index 0000000..006864a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/copy_out_response.go @@ -0,0 +1,96 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type CopyOutResponse struct { + OverallFormat byte + ColumnFormatCodes []uint16 +} + +func (*CopyOutResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *CopyOutResponse) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + if buf.Len() < 3 { + return &invalidMessageFormatErr{messageType: "CopyOutResponse"} + } + + overallFormat := buf.Next(1)[0] + + columnCount := int(binary.BigEndian.Uint16(buf.Next(2))) + if buf.Len() != columnCount*2 { + return &invalidMessageFormatErr{messageType: "CopyOutResponse"} + } + + columnFormatCodes := make([]uint16, columnCount) + for i := range columnCount { + columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2)) + } + + *dst = CopyOutResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes} + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *CopyOutResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'H') + + dst = append(dst, src.OverallFormat) + + if len(src.ColumnFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many column format codes") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes))) + for _, fc := range src.ColumnFormatCodes { + dst = pgio.AppendUint16(dst, fc) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src CopyOutResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ColumnFormatCodes []uint16 + }{ + Type: "CopyOutResponse", + ColumnFormatCodes: src.ColumnFormatCodes, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *CopyOutResponse) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + OverallFormat string + ColumnFormatCodes []uint16 + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + if len(msg.OverallFormat) != 1 { + return errors.New("invalid length for CopyOutResponse.OverallFormat") + } + + dst.OverallFormat = msg.OverallFormat[0] + dst.ColumnFormatCodes = msg.ColumnFormatCodes + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go b/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go new file mode 100644 index 0000000..54418d5 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/data_row.go @@ -0,0 +1,140 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type DataRow struct { + Values [][]byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*DataRow) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *DataRow) Decode(src []byte) error { + if len(src) < 2 { + return &invalidMessageFormatErr{messageType: "DataRow"} + } + rp := 0 + fieldCount := int(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + // If the capacity of the values slice is too small OR substantially too + // large reallocate. This is too avoid one row with many columns from + // permanently allocating memory. + if cap(dst.Values) < fieldCount || cap(dst.Values)-fieldCount > 32 { + newCap := max(32, fieldCount) + dst.Values = make([][]byte, fieldCount, newCap) + } else { + dst.Values = dst.Values[:fieldCount] + } + + for i := range fieldCount { + if len(src[rp:]) < 4 { + return &invalidMessageFormatErr{messageType: "DataRow"} + } + + valueLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + + // null + if valueLen == -1 { + dst.Values[i] = nil + } else { + if len(src[rp:]) < valueLen || valueLen < 0 { + return &invalidMessageFormatErr{messageType: "DataRow"} + } + + dst.Values[i] = src[rp : rp+valueLen : rp+valueLen] + rp += valueLen + } + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *DataRow) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'D') + + if len(src.Values) > math.MaxUint16 { + return nil, errors.New("too many values") + } + dst = pgio.AppendUint16(dst, uint16(len(src.Values))) + for _, v := range src.Values { + if v == nil { + dst = pgio.AppendInt32(dst, -1) + continue + } + + dst = pgio.AppendInt32(dst, int32(len(v))) + dst = append(dst, v...) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src DataRow) MarshalJSON() ([]byte, error) { + formattedValues := make([]map[string]string, len(src.Values)) + for i, v := range src.Values { + if v == nil { + continue + } + + var hasNonPrintable bool + for _, b := range v { + if b < 32 { + hasNonPrintable = true + break + } + } + + if hasNonPrintable { + formattedValues[i] = map[string]string{"binary": hex.EncodeToString(v)} + } else { + formattedValues[i] = map[string]string{"text": string(v)} + } + } + + return json.Marshal(struct { + Type string + Values []map[string]string + }{ + Type: "DataRow", + Values: formattedValues, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *DataRow) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + Values []map[string]string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.Values = make([][]byte, len(msg.Values)) + for n, parameter := range msg.Values { + var err error + dst.Values[n], err = getValueFromJSON(parameter) + if err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go b/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go new file mode 100644 index 0000000..0c396f1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/describe.go @@ -0,0 +1,80 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" + "errors" +) + +type Describe struct { + ObjectType byte // 'S' = prepared statement, 'P' = portal + Name string +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Describe) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Describe) Decode(src []byte) error { + if len(src) < 2 { + return &invalidMessageFormatErr{messageType: "Describe"} + } + + dst.ObjectType = src[0] + rp := 1 + + idx := bytes.IndexByte(src[rp:], 0) + if idx != len(src[rp:])-1 { + return &invalidMessageFormatErr{messageType: "Describe"} + } + + dst.Name = string(src[rp : len(src)-1]) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Describe) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'D') + dst = append(dst, src.ObjectType) + dst = append(dst, src.Name...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Describe) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ObjectType string + Name string + }{ + Type: "Describe", + ObjectType: string(src.ObjectType), + Name: src.Name, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *Describe) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + ObjectType string + Name string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + if len(msg.ObjectType) != 1 { + return errors.New("invalid length for Describe.ObjectType") + } + + dst.ObjectType = msg.ObjectType[0] + dst.Name = msg.Name + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/doc.go b/vendor/github.com/jackc/pgx/v5/pgproto3/doc.go new file mode 100644 index 0000000..0afd18e --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/doc.go @@ -0,0 +1,11 @@ +// Package pgproto3 is an encoder and decoder of the PostgreSQL wire protocol version 3. +// +// The primary interfaces are Frontend and Backend. They correspond to a client and server respectively. Messages are +// sent with Send (or a specialized Send variant). Messages are automatically buffered to minimize small writes. Call +// Flush to ensure a message has actually been sent. +// +// The Trace method of Frontend and Backend can be used to examine the wire-level message traffic. It outputs in a +// similar format to the PQtrace function in libpq. +// +// See https://www.postgresql.org/docs/current/protocol-message-formats.html for meanings of the different messages. +package pgproto3 diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go new file mode 100644 index 0000000..cb6cca0 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/empty_query_response.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type EmptyQueryResponse struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*EmptyQueryResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *EmptyQueryResponse) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "EmptyQueryResponse", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *EmptyQueryResponse) Encode(dst []byte) ([]byte, error) { + return append(dst, 'I', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src EmptyQueryResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "EmptyQueryResponse", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go new file mode 100644 index 0000000..6ef9bd0 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/error_response.go @@ -0,0 +1,326 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" + "strconv" +) + +type ErrorResponse struct { + Severity string + SeverityUnlocalized string // only in 9.6 and greater + Code string + Message string + Detail string + Hint string + Position int32 + InternalPosition int32 + InternalQuery string + Where string + SchemaName string + TableName string + ColumnName string + DataTypeName string + ConstraintName string + File string + Line int32 + Routine string + + UnknownFields map[byte]string +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*ErrorResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *ErrorResponse) Decode(src []byte) error { + *dst = ErrorResponse{} + + buf := bytes.NewBuffer(src) + + for { + k, err := buf.ReadByte() + if err != nil { + return err + } + if k == 0 { + break + } + + vb, err := buf.ReadBytes(0) + if err != nil { + return err + } + v := string(vb[:len(vb)-1]) + + switch k { + case 'S': + dst.Severity = v + case 'V': + dst.SeverityUnlocalized = v + case 'C': + dst.Code = v + case 'M': + dst.Message = v + case 'D': + dst.Detail = v + case 'H': + dst.Hint = v + case 'P': + s := v + n, _ := strconv.ParseInt(s, 10, 32) + dst.Position = int32(n) + case 'p': + s := v + n, _ := strconv.ParseInt(s, 10, 32) + dst.InternalPosition = int32(n) + case 'q': + dst.InternalQuery = v + case 'W': + dst.Where = v + case 's': + dst.SchemaName = v + case 't': + dst.TableName = v + case 'c': + dst.ColumnName = v + case 'd': + dst.DataTypeName = v + case 'n': + dst.ConstraintName = v + case 'F': + dst.File = v + case 'L': + s := v + n, _ := strconv.ParseInt(s, 10, 32) + dst.Line = int32(n) + case 'R': + dst.Routine = v + + default: + if dst.UnknownFields == nil { + dst.UnknownFields = make(map[byte]string) + } + dst.UnknownFields[k] = v + } + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *ErrorResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'E') + dst = src.appendFields(dst) + return finishMessage(dst, sp) +} + +func (src *ErrorResponse) appendFields(dst []byte) []byte { + if src.Severity != "" { + dst = append(dst, 'S') + dst = append(dst, src.Severity...) + dst = append(dst, 0) + } + if src.SeverityUnlocalized != "" { + dst = append(dst, 'V') + dst = append(dst, src.SeverityUnlocalized...) + dst = append(dst, 0) + } + if src.Code != "" { + dst = append(dst, 'C') + dst = append(dst, src.Code...) + dst = append(dst, 0) + } + if src.Message != "" { + dst = append(dst, 'M') + dst = append(dst, src.Message...) + dst = append(dst, 0) + } + if src.Detail != "" { + dst = append(dst, 'D') + dst = append(dst, src.Detail...) + dst = append(dst, 0) + } + if src.Hint != "" { + dst = append(dst, 'H') + dst = append(dst, src.Hint...) + dst = append(dst, 0) + } + if src.Position != 0 { + dst = append(dst, 'P') + dst = append(dst, strconv.Itoa(int(src.Position))...) + dst = append(dst, 0) + } + if src.InternalPosition != 0 { + dst = append(dst, 'p') + dst = append(dst, strconv.Itoa(int(src.InternalPosition))...) + dst = append(dst, 0) + } + if src.InternalQuery != "" { + dst = append(dst, 'q') + dst = append(dst, src.InternalQuery...) + dst = append(dst, 0) + } + if src.Where != "" { + dst = append(dst, 'W') + dst = append(dst, src.Where...) + dst = append(dst, 0) + } + if src.SchemaName != "" { + dst = append(dst, 's') + dst = append(dst, src.SchemaName...) + dst = append(dst, 0) + } + if src.TableName != "" { + dst = append(dst, 't') + dst = append(dst, src.TableName...) + dst = append(dst, 0) + } + if src.ColumnName != "" { + dst = append(dst, 'c') + dst = append(dst, src.ColumnName...) + dst = append(dst, 0) + } + if src.DataTypeName != "" { + dst = append(dst, 'd') + dst = append(dst, src.DataTypeName...) + dst = append(dst, 0) + } + if src.ConstraintName != "" { + dst = append(dst, 'n') + dst = append(dst, src.ConstraintName...) + dst = append(dst, 0) + } + if src.File != "" { + dst = append(dst, 'F') + dst = append(dst, src.File...) + dst = append(dst, 0) + } + if src.Line != 0 { + dst = append(dst, 'L') + dst = append(dst, strconv.Itoa(int(src.Line))...) + dst = append(dst, 0) + } + if src.Routine != "" { + dst = append(dst, 'R') + dst = append(dst, src.Routine...) + dst = append(dst, 0) + } + + for k, v := range src.UnknownFields { + dst = append(dst, k) + dst = append(dst, v...) + dst = append(dst, 0) + } + + dst = append(dst, 0) + + return dst +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src ErrorResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Severity string + SeverityUnlocalized string // only in 9.6 and greater + Code string + Message string + Detail string + Hint string + Position int32 + InternalPosition int32 + InternalQuery string + Where string + SchemaName string + TableName string + ColumnName string + DataTypeName string + ConstraintName string + File string + Line int32 + Routine string + + UnknownFields map[byte]string + }{ + Type: "ErrorResponse", + Severity: src.Severity, + SeverityUnlocalized: src.SeverityUnlocalized, + Code: src.Code, + Message: src.Message, + Detail: src.Detail, + Hint: src.Hint, + Position: src.Position, + InternalPosition: src.InternalPosition, + InternalQuery: src.InternalQuery, + Where: src.Where, + SchemaName: src.SchemaName, + TableName: src.TableName, + ColumnName: src.ColumnName, + DataTypeName: src.DataTypeName, + ConstraintName: src.ConstraintName, + File: src.File, + Line: src.Line, + Routine: src.Routine, + UnknownFields: src.UnknownFields, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *ErrorResponse) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + Type string + Severity string + SeverityUnlocalized string // only in 9.6 and greater + Code string + Message string + Detail string + Hint string + Position int32 + InternalPosition int32 + InternalQuery string + Where string + SchemaName string + TableName string + ColumnName string + DataTypeName string + ConstraintName string + File string + Line int32 + Routine string + + UnknownFields map[byte]string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.Severity = msg.Severity + dst.SeverityUnlocalized = msg.SeverityUnlocalized + dst.Code = msg.Code + dst.Message = msg.Message + dst.Detail = msg.Detail + dst.Hint = msg.Hint + dst.Position = msg.Position + dst.InternalPosition = msg.InternalPosition + dst.InternalQuery = msg.InternalQuery + dst.Where = msg.Where + dst.SchemaName = msg.SchemaName + dst.TableName = msg.TableName + dst.ColumnName = msg.ColumnName + dst.DataTypeName = msg.DataTypeName + dst.ConstraintName = msg.ConstraintName + dst.File = msg.File + dst.Line = msg.Line + dst.Routine = msg.Routine + + dst.UnknownFields = msg.UnknownFields + + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go b/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go new file mode 100644 index 0000000..31bc714 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/execute.go @@ -0,0 +1,58 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Execute struct { + Portal string + MaxRows uint32 +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Execute) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Execute) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + b, err := buf.ReadBytes(0) + if err != nil { + return err + } + dst.Portal = string(b[:len(b)-1]) + + if buf.Len() < 4 { + return &invalidMessageFormatErr{messageType: "Execute"} + } + dst.MaxRows = binary.BigEndian.Uint32(buf.Next(4)) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Execute) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'E') + dst = append(dst, src.Portal...) + dst = append(dst, 0) + dst = pgio.AppendUint32(dst, src.MaxRows) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Execute) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Portal string + MaxRows uint32 + }{ + Type: "Execute", + Portal: src.Portal, + MaxRows: src.MaxRows, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go b/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go new file mode 100644 index 0000000..e5dc1fb --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/flush.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type Flush struct{} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Flush) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Flush) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "Flush", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Flush) Encode(dst []byte) ([]byte, error) { + return append(dst, 'H', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Flush) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "Flush", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go b/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go new file mode 100644 index 0000000..9fc85f2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/frontend.go @@ -0,0 +1,475 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" +) + +// Frontend acts as a client for the PostgreSQL wire protocol version 3. +type Frontend struct { + cr *chunkReader + w io.Writer + + // tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced + // before it is actually transmitted (i.e. before Flush). It is safe to change this variable when the Frontend is + // idle. Setting and unsetting tracer provides equivalent functionality to PQtrace and PQuntrace in libpq. + tracer *tracer + + wbuf []byte + encodeError error + + // Backend message flyweights + authenticationOk AuthenticationOk + authenticationCleartextPassword AuthenticationCleartextPassword + authenticationMD5Password AuthenticationMD5Password + authenticationGSS AuthenticationGSS + authenticationGSSContinue AuthenticationGSSContinue + authenticationSASL AuthenticationSASL + authenticationSASLContinue AuthenticationSASLContinue + authenticationSASLFinal AuthenticationSASLFinal + backendKeyData BackendKeyData + bindComplete BindComplete + closeComplete CloseComplete + commandComplete CommandComplete + copyBothResponse CopyBothResponse + copyData CopyData + copyInResponse CopyInResponse + copyOutResponse CopyOutResponse + copyDone CopyDone + dataRow DataRow + emptyQueryResponse EmptyQueryResponse + errorResponse ErrorResponse + functionCallResponse FunctionCallResponse + noData NoData + noticeResponse NoticeResponse + notificationResponse NotificationResponse + parameterDescription ParameterDescription + parameterStatus ParameterStatus + parseComplete ParseComplete + readyForQuery ReadyForQuery + rowDescription RowDescription + portalSuspended PortalSuspended + negotiateProtocolVersion NegotiateProtocolVersion + + bodyLen int + maxBodyLen int // maxBodyLen is the maximum length of a message body in octets. If a message body exceeds this length, Receive will return an error. + msgType byte + partialMsg bool + authType uint32 +} + +// NewFrontend creates a new Frontend. +// +// The maximum accepted message body length defaults to the same ~1 GiB limit the PostgreSQL +// server enforces on inbound messages (PQ_LARGE_MESSAGE_LIMIT in src/include/libpq/libpq.h). +// Use [Frontend.SetMaxBodyLen] to change or remove the limit. +func NewFrontend(r io.Reader, w io.Writer) *Frontend { + cr := newChunkReader(r, 0) + return &Frontend{cr: cr, w: w, maxBodyLen: maxMessageBodyLen} +} + +// Send sends a message to the backend (i.e. the server). The message is buffered until Flush is called. Any error +// encountered will be returned from Flush. +// +// Send can work with any FrontendMessage. Some commonly used message types such as Bind have specialized send methods +// such as SendBind. These methods should be preferred when the type of message is known up front (e.g. when building an +// extended query protocol query) as they may be faster due to knowing the type of msg rather than it being hidden +// behind an interface. +func (f *Frontend) Send(msg FrontendMessage) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceMessage('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// Flush writes any pending messages to the backend (i.e. the server). +func (f *Frontend) Flush() error { + if err := f.encodeError; err != nil { + f.encodeError = nil + f.wbuf = f.wbuf[:0] + return &writeError{err: err, safeToRetry: true} + } + + if len(f.wbuf) == 0 { + return nil + } + + n, err := f.w.Write(f.wbuf) + + const maxLen = 1024 + if len(f.wbuf) > maxLen { + f.wbuf = make([]byte, 0, maxLen) + } else { + f.wbuf = f.wbuf[:0] + } + + if err != nil { + return &writeError{err: err, safeToRetry: n == 0} + } + + return nil +} + +// Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function +// PQtrace. +func (f *Frontend) Trace(w io.Writer, options TracerOptions) { + f.tracer = &tracer{ + w: w, + buf: &bytes.Buffer{}, + TracerOptions: options, + } +} + +// Untrace stops tracing. +func (f *Frontend) Untrace() { + f.tracer = nil +} + +// SendBind sends a Bind message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. +func (f *Frontend) SendBind(msg *Bind) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceBind('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendParse sends a Parse message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. +func (f *Frontend) SendParse(msg *Parse) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceParse('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendClose sends a Close message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. +func (f *Frontend) SendClose(msg *Close) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceClose('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendDescribe sends a Describe message to the backend (i.e. the server). The message is buffered until Flush is +// called. Any error encountered will be returned from Flush. +func (f *Frontend) SendDescribe(msg *Describe) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceDescribe('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendExecute sends an Execute message to the backend (i.e. the server). The message is buffered until Flush is called. +// Any error encountered will be returned from Flush. +func (f *Frontend) SendExecute(msg *Execute) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceExecute('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendSync sends a Sync message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. +func (f *Frontend) SendSync(msg *Sync) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceSync('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendQuery sends a Query message to the backend (i.e. the server). The message is buffered until Flush is called. Any +// error encountered will be returned from Flush. +func (f *Frontend) SendQuery(msg *Query) { + if f.encodeError != nil { + return + } + + prevLen := len(f.wbuf) + newBuf, err := msg.Encode(f.wbuf) + if err != nil { + f.encodeError = err + return + } + f.wbuf = newBuf + + if f.tracer != nil { + f.tracer.traceQuery('F', int32(len(f.wbuf)-prevLen), msg) + } +} + +// SendUnbufferedEncodedCopyData immediately sends an encoded CopyData message to the backend (i.e. the server). This method +// is more efficient than sending a CopyData message with Send as the message data is not copied to the internal buffer +// before being written out. The internal buffer is flushed before the message is sent. +func (f *Frontend) SendUnbufferedEncodedCopyData(msg []byte) error { + err := f.Flush() + if err != nil { + return err + } + + n, err := f.w.Write(msg) + if err != nil { + return &writeError{err: err, safeToRetry: n == 0} + } + + if f.tracer != nil { + f.tracer.traceCopyData('F', int32(len(msg)-1), &CopyData{}) + } + + return nil +} + +func translateEOFtoErrUnexpectedEOF(err error) error { + if err == io.EOF { + return io.ErrUnexpectedEOF + } + return err +} + +// Receive receives a message from the backend. The returned message is only valid until the next call to Receive. +func (f *Frontend) Receive() (BackendMessage, error) { + if !f.partialMsg { + header, err := f.cr.Next(5) + if err != nil { + return nil, translateEOFtoErrUnexpectedEOF(err) + } + + f.msgType = header[0] + + msgLength := int(int32(binary.BigEndian.Uint32(header[1:]))) + if msgLength < 4 { + return nil, fmt.Errorf("invalid message length: %d", msgLength) + } + + f.bodyLen = msgLength - 4 + if f.maxBodyLen > 0 && f.bodyLen > f.maxBodyLen { + return nil, &ExceededMaxBodyLenErr{f.maxBodyLen, f.bodyLen} + } + f.partialMsg = true + } + + msgBody, err := f.cr.Next(f.bodyLen) + if err != nil { + return nil, translateEOFtoErrUnexpectedEOF(err) + } + + f.partialMsg = false + + var msg BackendMessage + switch f.msgType { + case '1': + msg = &f.parseComplete + case '2': + msg = &f.bindComplete + case '3': + msg = &f.closeComplete + case 'A': + msg = &f.notificationResponse + case 'c': + msg = &f.copyDone + case 'C': + msg = &f.commandComplete + case 'd': + msg = &f.copyData + case 'D': + msg = &f.dataRow + case 'E': + msg = &f.errorResponse + case 'G': + msg = &f.copyInResponse + case 'H': + msg = &f.copyOutResponse + case 'I': + msg = &f.emptyQueryResponse + case 'K': + msg = &f.backendKeyData + case 'n': + msg = &f.noData + case 'N': + msg = &f.noticeResponse + case 'R': + var err error + msg, err = f.findAuthenticationMessageType(msgBody) + if err != nil { + return nil, err + } + case 's': + msg = &f.portalSuspended + case 'S': + msg = &f.parameterStatus + case 't': + msg = &f.parameterDescription + case 'T': + msg = &f.rowDescription + case 'V': + msg = &f.functionCallResponse + case 'W': + msg = &f.copyBothResponse + case 'Z': + msg = &f.readyForQuery + case 'v': + msg = &f.negotiateProtocolVersion + default: + return nil, fmt.Errorf("unknown message type: %c", f.msgType) + } + + err = msg.Decode(msgBody) + if err != nil { + return nil, err + } + + if f.tracer != nil { + f.tracer.traceMessage('B', int32(5+len(msgBody)), msg) + } + + return msg, nil +} + +// Authentication message type constants. +// See src/include/libpq/pqcomm.h for all +// constants. +const ( + AuthTypeOk = 0 + AuthTypeCleartextPassword = 3 + AuthTypeMD5Password = 5 + AuthTypeSCMCreds = 6 + AuthTypeGSS = 7 + AuthTypeGSSCont = 8 + AuthTypeSSPI = 9 + AuthTypeSASL = 10 + AuthTypeSASLContinue = 11 + AuthTypeSASLFinal = 12 +) + +func (f *Frontend) findAuthenticationMessageType(src []byte) (BackendMessage, error) { + if len(src) < 4 { + return nil, errors.New("authentication message too short") + } + f.authType = binary.BigEndian.Uint32(src[:4]) + + switch f.authType { + case AuthTypeOk: + return &f.authenticationOk, nil + case AuthTypeCleartextPassword: + return &f.authenticationCleartextPassword, nil + case AuthTypeMD5Password: + return &f.authenticationMD5Password, nil + case AuthTypeSCMCreds: + return nil, errors.New("AuthTypeSCMCreds is unimplemented") + case AuthTypeGSS: + return &f.authenticationGSS, nil + case AuthTypeGSSCont: + return &f.authenticationGSSContinue, nil + case AuthTypeSSPI: + return nil, errors.New("AuthTypeSSPI is unimplemented") + case AuthTypeSASL: + return &f.authenticationSASL, nil + case AuthTypeSASLContinue: + return &f.authenticationSASLContinue, nil + case AuthTypeSASLFinal: + return &f.authenticationSASLFinal, nil + default: + return nil, fmt.Errorf("unknown authentication type: %d", f.authType) + } +} + +// GetAuthType returns the authType used in the current state of the frontend. +// See SetAuthType for more information. +func (f *Frontend) GetAuthType() uint32 { + return f.authType +} + +func (f *Frontend) ReadBufferLen() int { + return f.cr.wp - f.cr.rp +} + +// SetMaxBodyLen sets the maximum length of a message body in octets. +// If a message body exceeds this length, Receive will return an error. +// This is useful for protecting against a corrupted server that sends +// messages with incorrect length, which can cause memory exhaustion. +// The default value is 0. +// If maxBodyLen is 0, then no maximum is enforced. +func (f *Frontend) SetMaxBodyLen(maxBodyLen int) { + f.maxBodyLen = maxBodyLen +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go new file mode 100644 index 0000000..ef3cfd3 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call.go @@ -0,0 +1,124 @@ +package pgproto3 + +import ( + "encoding/binary" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type FunctionCall struct { + Function uint32 + ArgFormatCodes []uint16 + Arguments [][]byte + ResultFormatCode uint16 +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*FunctionCall) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *FunctionCall) Decode(src []byte) error { + *dst = FunctionCall{} + rp := 0 + + if len(src) < 8 { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + + // Specifies the object ID of the function to call. + dst.Function = binary.BigEndian.Uint32(src[rp:]) + rp += 4 + // The number of argument format codes that follow (denoted C below). + // This can be zero to indicate that there are no arguments or that the arguments all use the default format (text); + // or one, in which case the specified format code is applied to all arguments; + // or it can equal the actual number of arguments. + nArgumentCodes := int(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + if len(src[rp:]) < nArgumentCodes*2+2 { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + + argumentCodes := make([]uint16, nArgumentCodes) + for i := range nArgumentCodes { + // The argument format codes. Each must presently be zero (text) or one (binary). + ac := binary.BigEndian.Uint16(src[rp:]) + if ac != 0 && ac != 1 { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + argumentCodes[i] = ac + rp += 2 + } + dst.ArgFormatCodes = argumentCodes + + // Specifies the number of arguments being supplied to the function. + nArguments := int(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + arguments := make([][]byte, nArguments) + for i := range nArguments { + if len(src[rp:]) < 4 { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + // The length of the argument value, in bytes (this count does not include itself). Can be zero. + // As a special case, -1 indicates a NULL argument value. No value bytes follow in the NULL case. + argumentLength := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + switch { + case argumentLength == -1: + arguments[i] = nil + case argumentLength < 0: + return &invalidMessageFormatErr{messageType: "FunctionCall"} + default: + if len(src[rp:]) < argumentLength { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + // The value of the argument, in the format indicated by the associated format code. n is the above length. + argumentValue := src[rp : rp+argumentLength] + rp += argumentLength + arguments[i] = argumentValue + } + } + dst.Arguments = arguments + // The format code for the function result. Must presently be zero (text) or one (binary). + if len(src[rp:]) < 2 { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + resultFormatCode := binary.BigEndian.Uint16(src[rp:]) + if resultFormatCode != 0 && resultFormatCode != 1 { + return &invalidMessageFormatErr{messageType: "FunctionCall"} + } + dst.ResultFormatCode = resultFormatCode + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *FunctionCall) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'F') + dst = pgio.AppendUint32(dst, src.Function) + + if len(src.ArgFormatCodes) > math.MaxUint16 { + return nil, errors.New("too many arg format codes") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ArgFormatCodes))) + for _, argFormatCode := range src.ArgFormatCodes { + dst = pgio.AppendUint16(dst, argFormatCode) + } + + if len(src.Arguments) > math.MaxUint16 { + return nil, errors.New("too many arguments") + } + dst = pgio.AppendUint16(dst, uint16(len(src.Arguments))) + for _, argument := range src.Arguments { + if argument == nil { + dst = pgio.AppendInt32(dst, -1) + } else { + dst = pgio.AppendInt32(dst, int32(len(argument))) + dst = append(dst, argument...) + } + } + dst = pgio.AppendUint16(dst, src.ResultFormatCode) + return finishMessage(dst, sp) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go new file mode 100644 index 0000000..6b6ed8b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/function_call_response.go @@ -0,0 +1,97 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/hex" + "encoding/json" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type FunctionCallResponse struct { + Result []byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*FunctionCallResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *FunctionCallResponse) Decode(src []byte) error { + if len(src) < 4 { + return &invalidMessageFormatErr{messageType: "FunctionCallResponse"} + } + rp := 0 + resultSize := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + + if resultSize == -1 { + dst.Result = nil + return nil + } + + if resultSize < 0 || len(src[rp:]) != resultSize { + return &invalidMessageFormatErr{messageType: "FunctionCallResponse"} + } + + dst.Result = src[rp:] + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *FunctionCallResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'V') + + if src.Result == nil { + dst = pgio.AppendInt32(dst, -1) + } else { + dst = pgio.AppendInt32(dst, int32(len(src.Result))) + dst = append(dst, src.Result...) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src FunctionCallResponse) MarshalJSON() ([]byte, error) { + var formattedValue map[string]string + var hasNonPrintable bool + for _, b := range src.Result { + if b < 32 { + hasNonPrintable = true + break + } + } + + if hasNonPrintable { + formattedValue = map[string]string{"binary": hex.EncodeToString(src.Result)} + } else { + formattedValue = map[string]string{"text": string(src.Result)} + } + + return json.Marshal(struct { + Type string + Result map[string]string + }{ + Type: "FunctionCallResponse", + Result: formattedValue, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *FunctionCallResponse) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + Result map[string]string + } + err := json.Unmarshal(data, &msg) + if err != nil { + return err + } + dst.Result, err = getValueFromJSON(msg.Result) + return err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go new file mode 100644 index 0000000..122d134 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_enc_request.go @@ -0,0 +1,48 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const gssEncReqNumber = 80877104 + +type GSSEncRequest struct{} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*GSSEncRequest) Frontend() {} + +func (dst *GSSEncRequest) Decode(src []byte) error { + if len(src) < 4 { + return errors.New("gss encoding request too short") + } + + requestCode := binary.BigEndian.Uint32(src) + + if requestCode != gssEncReqNumber { + return errors.New("bad gss encoding request code") + } + + return nil +} + +// Encode encodes src into dst. dst will include the 4 byte message length. +func (src *GSSEncRequest) Encode(dst []byte) ([]byte, error) { + dst = pgio.AppendInt32(dst, 8) + dst = pgio.AppendInt32(dst, gssEncReqNumber) + return dst, nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src GSSEncRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ProtocolVersion uint32 + Parameters map[string]string + }{ + Type: "GSSEncRequest", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go new file mode 100644 index 0000000..10d9377 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/gss_response.go @@ -0,0 +1,46 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type GSSResponse struct { + Data []byte +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (g *GSSResponse) Frontend() {} + +func (g *GSSResponse) Decode(data []byte) error { + g.Data = data + return nil +} + +func (g *GSSResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') + dst = append(dst, g.Data...) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (g *GSSResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Data []byte + }{ + Type: "GSSResponse", + Data: g.Data, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (g *GSSResponse) UnmarshalJSON(data []byte) error { + var msg struct { + Data []byte + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + g.Data = msg.Data + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go b/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go new file mode 100644 index 0000000..43bd7ec --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/negotiate_protocol_version.go @@ -0,0 +1,93 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/json" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type NegotiateProtocolVersion struct { + NewestMinorProtocol uint32 + UnrecognizedOptions []string +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*NegotiateProtocolVersion) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *NegotiateProtocolVersion) Decode(src []byte) error { + if len(src) < 8 { + return &invalidMessageLenErr{messageType: "NegotiateProtocolVersion", expectedLen: 8, actualLen: len(src)} + } + + dst.NewestMinorProtocol = binary.BigEndian.Uint32(src[:4]) + optionCount := int(binary.BigEndian.Uint32(src[4:8])) + + rp := 8 + + // Use the remaining message size as an upper bound for capacity to prevent + // malicious optionCount values from causing excessive memory allocation. + capHint := optionCount + if remaining := len(src) - rp; capHint > remaining { + capHint = remaining + } + dst.UnrecognizedOptions = make([]string, 0, capHint) + for i := 0; i < optionCount; i++ { + if rp >= len(src) { + return &invalidMessageFormatErr{messageType: "NegotiateProtocolVersion"} + } + end := rp + for end < len(src) && src[end] != 0 { + end++ + } + if end >= len(src) { + return &invalidMessageFormatErr{messageType: "NegotiateProtocolVersion"} + } + dst.UnrecognizedOptions = append(dst.UnrecognizedOptions, string(src[rp:end])) + rp = end + 1 + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *NegotiateProtocolVersion) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'v') + dst = pgio.AppendUint32(dst, src.NewestMinorProtocol) + dst = pgio.AppendUint32(dst, uint32(len(src.UnrecognizedOptions))) + for _, option := range src.UnrecognizedOptions { + dst = append(dst, option...) + dst = append(dst, 0) + } + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src NegotiateProtocolVersion) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + NewestMinorProtocol uint32 + UnrecognizedOptions []string + }{ + Type: "NegotiateProtocolVersion", + NewestMinorProtocol: src.NewestMinorProtocol, + UnrecognizedOptions: src.UnrecognizedOptions, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *NegotiateProtocolVersion) UnmarshalJSON(data []byte) error { + var msg struct { + NewestMinorProtocol uint32 + UnrecognizedOptions []string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + + dst.NewestMinorProtocol = msg.NewestMinorProtocol + dst.UnrecognizedOptions = msg.UnrecognizedOptions + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go b/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go new file mode 100644 index 0000000..cbcaad4 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/no_data.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type NoData struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*NoData) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *NoData) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "NoData", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *NoData) Encode(dst []byte) ([]byte, error) { + return append(dst, 'n', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src NoData) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "NoData", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go new file mode 100644 index 0000000..497aba6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/notice_response.go @@ -0,0 +1,19 @@ +package pgproto3 + +type NoticeResponse ErrorResponse + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*NoticeResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *NoticeResponse) Decode(src []byte) error { + return (*ErrorResponse)(dst).Decode(src) +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *NoticeResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'N') + dst = (*ErrorResponse)(src).appendFields(dst) + return finishMessage(dst, sp) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go new file mode 100644 index 0000000..243b6bf --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/notification_response.go @@ -0,0 +1,71 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type NotificationResponse struct { + PID uint32 + Channel string + Payload string +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*NotificationResponse) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *NotificationResponse) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + if buf.Len() < 4 { + return &invalidMessageFormatErr{messageType: "NotificationResponse", details: "too short"} + } + + pid := binary.BigEndian.Uint32(buf.Next(4)) + + b, err := buf.ReadBytes(0) + if err != nil { + return err + } + channel := string(b[:len(b)-1]) + + b, err = buf.ReadBytes(0) + if err != nil { + return err + } + payload := string(b[:len(b)-1]) + + *dst = NotificationResponse{PID: pid, Channel: channel, Payload: payload} + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *NotificationResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'A') + dst = pgio.AppendUint32(dst, src.PID) + dst = append(dst, src.Channel...) + dst = append(dst, 0) + dst = append(dst, src.Payload...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src NotificationResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + PID uint32 + Channel string + Payload string + }{ + Type: "NotificationResponse", + PID: src.PID, + Channel: src.Channel, + Payload: src.Payload, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go new file mode 100644 index 0000000..58eb26e --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_description.go @@ -0,0 +1,67 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type ParameterDescription struct { + ParameterOIDs []uint32 +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*ParameterDescription) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *ParameterDescription) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + if buf.Len() < 2 { + return &invalidMessageFormatErr{messageType: "ParameterDescription"} + } + + // Reported parameter count will be incorrect when number of args is greater than uint16 + buf.Next(2) + // Instead infer parameter count by remaining size of message + parameterCount := buf.Len() / 4 + + *dst = ParameterDescription{ParameterOIDs: make([]uint32, parameterCount)} + + for i := range parameterCount { + dst.ParameterOIDs[i] = binary.BigEndian.Uint32(buf.Next(4)) + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *ParameterDescription) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 't') + + if len(src.ParameterOIDs) > math.MaxUint16 { + return nil, errors.New("too many parameter oids") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs))) + for _, oid := range src.ParameterOIDs { + dst = pgio.AppendUint32(dst, oid) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src ParameterDescription) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ParameterOIDs []uint32 + }{ + Type: "ParameterDescription", + ParameterOIDs: src.ParameterOIDs, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go new file mode 100644 index 0000000..9ee0720 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parameter_status.go @@ -0,0 +1,58 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" +) + +type ParameterStatus struct { + Name string + Value string +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*ParameterStatus) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *ParameterStatus) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + b, err := buf.ReadBytes(0) + if err != nil { + return err + } + name := string(b[:len(b)-1]) + + b, err = buf.ReadBytes(0) + if err != nil { + return err + } + value := string(b[:len(b)-1]) + + *dst = ParameterStatus{Name: name, Value: value} + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *ParameterStatus) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'S') + dst = append(dst, src.Name...) + dst = append(dst, 0) + dst = append(dst, src.Value...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (ps ParameterStatus) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Name string + Value string + }{ + Type: "ParameterStatus", + Name: ps.Name, + Value: ps.Value, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go new file mode 100644 index 0000000..8fb8de5 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parse.go @@ -0,0 +1,89 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Parse struct { + Name string + Query string + ParameterOIDs []uint32 +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Parse) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Parse) Decode(src []byte) error { + *dst = Parse{} + + buf := bytes.NewBuffer(src) + + b, err := buf.ReadBytes(0) + if err != nil { + return err + } + dst.Name = string(b[:len(b)-1]) + + b, err = buf.ReadBytes(0) + if err != nil { + return err + } + dst.Query = string(b[:len(b)-1]) + + if buf.Len() < 2 { + return &invalidMessageFormatErr{messageType: "Parse"} + } + parameterOIDCount := int(binary.BigEndian.Uint16(buf.Next(2))) + + for range parameterOIDCount { + if buf.Len() < 4 { + return &invalidMessageFormatErr{messageType: "Parse"} + } + dst.ParameterOIDs = append(dst.ParameterOIDs, binary.BigEndian.Uint32(buf.Next(4))) + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Parse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'P') + + dst = append(dst, src.Name...) + dst = append(dst, 0) + dst = append(dst, src.Query...) + dst = append(dst, 0) + + if len(src.ParameterOIDs) > math.MaxUint16 { + return nil, errors.New("too many parameter oids") + } + dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs))) + for _, oid := range src.ParameterOIDs { + dst = pgio.AppendUint32(dst, oid) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Parse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Name string + Query string + ParameterOIDs []uint32 + }{ + Type: "Parse", + Name: src.Name, + Query: src.Query, + ParameterOIDs: src.ParameterOIDs, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go b/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go new file mode 100644 index 0000000..cff9e27 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/parse_complete.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type ParseComplete struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*ParseComplete) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *ParseComplete) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "ParseComplete", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *ParseComplete) Encode(dst []byte) ([]byte, error) { + return append(dst, '1', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src ParseComplete) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "ParseComplete", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go new file mode 100644 index 0000000..67b7851 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/password_message.go @@ -0,0 +1,49 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" +) + +type PasswordMessage struct { + Password string +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*PasswordMessage) Frontend() {} + +// InitialResponse identifies this message as an authentication response. +func (*PasswordMessage) InitialResponse() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *PasswordMessage) Decode(src []byte) error { + buf := bytes.NewBuffer(src) + + b, err := buf.ReadBytes(0) + if err != nil { + return err + } + dst.Password = string(b[:len(b)-1]) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *PasswordMessage) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') + dst = append(dst, src.Password...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src PasswordMessage) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Password string + }{ + Type: "PasswordMessage", + Password: src.Password, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go b/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go new file mode 100644 index 0000000..128f97f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/pgproto3.go @@ -0,0 +1,120 @@ +package pgproto3 + +import ( + "encoding/hex" + "errors" + "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// maxMessageBodyLen is the maximum length of a message body in bytes. See PG_LARGE_MESSAGE_LIMIT in the PostgreSQL +// source. It is defined as (MaxAllocSize - 1). MaxAllocSize is defined as 0x3fffffff. +const maxMessageBodyLen = (0x3fffffff - 1) + +// Message is the interface implemented by an object that can decode and encode +// a particular PostgreSQL message. +type Message interface { + // Decode is allowed and expected to retain a reference to data after + // returning (unlike encoding.BinaryUnmarshaler). + Decode(data []byte) error + + // Encode appends itself to dst and returns the new buffer. + Encode(dst []byte) ([]byte, error) +} + +// FrontendMessage is a message sent by the frontend (i.e. the client). +type FrontendMessage interface { + Message + Frontend() // no-op method to distinguish frontend from backend methods +} + +// BackendMessage is a message sent by the backend (i.e. the server). +type BackendMessage interface { + Message + Backend() // no-op method to distinguish frontend from backend methods +} + +type AuthenticationResponseMessage interface { + BackendMessage + AuthenticationResponse() // no-op method to distinguish authentication responses +} + +type invalidMessageLenErr struct { + messageType string + expectedLen int + actualLen int +} + +func (e *invalidMessageLenErr) Error() string { + return fmt.Sprintf("%s body must have length of %d, but it is %d", e.messageType, e.expectedLen, e.actualLen) +} + +type invalidMessageFormatErr struct { + messageType string + details string +} + +func (e *invalidMessageFormatErr) Error() string { + return fmt.Sprintf("%s body is invalid %s", e.messageType, e.details) +} + +type writeError struct { + err error + safeToRetry bool +} + +func (e *writeError) Error() string { + return fmt.Sprintf("write failed: %s", e.err.Error()) +} + +func (e *writeError) SafeToRetry() bool { + return e.safeToRetry +} + +func (e *writeError) Unwrap() error { + return e.err +} + +type ExceededMaxBodyLenErr struct { + MaxExpectedBodyLen int + ActualBodyLen int +} + +func (e *ExceededMaxBodyLenErr) Error() string { + return fmt.Sprintf("invalid body length: expected at most %d, but got %d", e.MaxExpectedBodyLen, e.ActualBodyLen) +} + +// getValueFromJSON gets the value from a protocol message representation in JSON. +func getValueFromJSON(v map[string]string) ([]byte, error) { + if v == nil { + return nil, nil + } + if text, ok := v["text"]; ok { + return []byte(text), nil + } + if binary, ok := v["binary"]; ok { + return hex.DecodeString(binary) + } + return nil, errors.New("unknown protocol representation") +} + +// beginMessage begins a new message of type t. It appends the message type and a placeholder for the message length to +// dst. It returns the new buffer and the position of the message length placeholder. +func beginMessage(dst []byte, t byte) ([]byte, int) { + dst = append(dst, t) + sp := len(dst) + dst = pgio.AppendInt32(dst, -1) + return dst, sp +} + +// finishMessage finishes a message that was started with beginMessage. It computes the message length and writes it to +// dst[sp]. If the message length is too large it returns an error. Otherwise it returns the final message buffer. +func finishMessage(dst []byte, sp int) ([]byte, error) { + messageBodyLen := len(dst[sp:]) + if messageBodyLen > maxMessageBodyLen { + return nil, errors.New("message body too large") + } + pgio.SetInt32(dst[sp:], int32(messageBodyLen)) + return dst, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go b/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go new file mode 100644 index 0000000..9e2f8cb --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/portal_suspended.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type PortalSuspended struct{} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*PortalSuspended) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *PortalSuspended) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "PortalSuspended", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *PortalSuspended) Encode(dst []byte) ([]byte, error) { + return append(dst, 's', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src PortalSuspended) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "PortalSuspended", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/query.go b/vendor/github.com/jackc/pgx/v5/pgproto3/query.go new file mode 100644 index 0000000..9e16465 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/query.go @@ -0,0 +1,49 @@ +package pgproto3 + +import ( + "bytes" + "encoding/json" +) + +type Query struct { + String string +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Query) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Query) Decode(src []byte) error { + if len(src) == 0 { + return &invalidMessageFormatErr{messageType: "Query"} + } + + i := bytes.IndexByte(src, 0) + if i != len(src)-1 { + return &invalidMessageFormatErr{messageType: "Query"} + } + + dst.String = string(src[:i]) + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Query) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'Q') + dst = append(dst, src.String...) + dst = append(dst, 0) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Query) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + String string + }{ + Type: "Query", + String: src.String, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go b/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go new file mode 100644 index 0000000..a56af9f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/ready_for_query.go @@ -0,0 +1,61 @@ +package pgproto3 + +import ( + "encoding/json" + "errors" +) + +type ReadyForQuery struct { + TxStatus byte +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*ReadyForQuery) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *ReadyForQuery) Decode(src []byte) error { + if len(src) != 1 { + return &invalidMessageLenErr{messageType: "ReadyForQuery", expectedLen: 1, actualLen: len(src)} + } + + dst.TxStatus = src[0] + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *ReadyForQuery) Encode(dst []byte) ([]byte, error) { + return append(dst, 'Z', 0, 0, 0, 5, src.TxStatus), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src ReadyForQuery) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + TxStatus string + }{ + Type: "ReadyForQuery", + TxStatus: string(src.TxStatus), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *ReadyForQuery) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + TxStatus string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + if len(msg.TxStatus) != 1 { + return errors.New("invalid length for ReadyForQuery.TxStatus") + } + dst.TxStatus = msg.TxStatus[0] + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go b/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go new file mode 100644 index 0000000..b46f510 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/row_description.go @@ -0,0 +1,165 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "math" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const ( + TextFormat = 0 + BinaryFormat = 1 +) + +type FieldDescription struct { + Name []byte + TableOID uint32 + TableAttributeNumber uint16 + DataTypeOID uint32 + DataTypeSize int16 + TypeModifier int32 + Format int16 +} + +// MarshalJSON implements encoding/json.Marshaler. +func (fd FieldDescription) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Name string + TableOID uint32 + TableAttributeNumber uint16 + DataTypeOID uint32 + DataTypeSize int16 + TypeModifier int32 + Format int16 + }{ + Name: string(fd.Name), + TableOID: fd.TableOID, + TableAttributeNumber: fd.TableAttributeNumber, + DataTypeOID: fd.DataTypeOID, + DataTypeSize: fd.DataTypeSize, + TypeModifier: fd.TypeModifier, + Format: fd.Format, + }) +} + +type RowDescription struct { + Fields []FieldDescription +} + +// Backend identifies this message as sendable by the PostgreSQL backend. +func (*RowDescription) Backend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *RowDescription) Decode(src []byte) error { + if len(src) < 2 { + return &invalidMessageFormatErr{messageType: "RowDescription"} + } + fieldCount := int(binary.BigEndian.Uint16(src)) + rp := 2 + + dst.Fields = dst.Fields[0:0] + + for range fieldCount { + var fd FieldDescription + + idx := bytes.IndexByte(src[rp:], 0) + if idx < 0 { + return &invalidMessageFormatErr{messageType: "RowDescription"} + } + fd.Name = src[rp : rp+idx] + rp += idx + 1 + + // Since buf.Next() doesn't return an error if we hit the end of the buffer + // check Len ahead of time + if len(src[rp:]) < 18 { + return &invalidMessageFormatErr{messageType: "RowDescription"} + } + + fd.TableOID = binary.BigEndian.Uint32(src[rp:]) + rp += 4 + fd.TableAttributeNumber = binary.BigEndian.Uint16(src[rp:]) + rp += 2 + fd.DataTypeOID = binary.BigEndian.Uint32(src[rp:]) + rp += 4 + fd.DataTypeSize = int16(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + fd.TypeModifier = int32(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + fd.Format = int16(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + dst.Fields = append(dst.Fields, fd) + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *RowDescription) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'T') + + if len(src.Fields) > math.MaxUint16 { + return nil, errors.New("too many fields") + } + dst = pgio.AppendUint16(dst, uint16(len(src.Fields))) + for _, fd := range src.Fields { + dst = append(dst, fd.Name...) + dst = append(dst, 0) + + dst = pgio.AppendUint32(dst, fd.TableOID) + dst = pgio.AppendUint16(dst, fd.TableAttributeNumber) + dst = pgio.AppendUint32(dst, fd.DataTypeOID) + dst = pgio.AppendInt16(dst, fd.DataTypeSize) + dst = pgio.AppendInt32(dst, fd.TypeModifier) + dst = pgio.AppendInt16(dst, fd.Format) + } + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src RowDescription) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Fields []FieldDescription + }{ + Type: "RowDescription", + Fields: src.Fields, + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *RowDescription) UnmarshalJSON(data []byte) error { + var msg struct { + Fields []struct { + Name string + TableOID uint32 + TableAttributeNumber uint16 + DataTypeOID uint32 + DataTypeSize int16 + TypeModifier int32 + Format int16 + } + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + dst.Fields = make([]FieldDescription, len(msg.Fields)) + for n, field := range msg.Fields { + dst.Fields[n] = FieldDescription{ + Name: []byte(field.Name), + TableOID: field.TableOID, + TableAttributeNumber: field.TableAttributeNumber, + DataTypeOID: field.DataTypeOID, + DataTypeSize: field.DataTypeSize, + TypeModifier: field.TypeModifier, + Format: field.Format, + } + } + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go new file mode 100644 index 0000000..123f3cd --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_initial_response.go @@ -0,0 +1,93 @@ +package pgproto3 + +import ( + "bytes" + "encoding/hex" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type SASLInitialResponse struct { + AuthMechanism string + Data []byte +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*SASLInitialResponse) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *SASLInitialResponse) Decode(src []byte) error { + *dst = SASLInitialResponse{} + + rp := 0 + + idx := bytes.IndexByte(src, 0) + if idx < 0 { + return errors.New("invalid SASLInitialResponse") + } + + dst.AuthMechanism = string(src[rp:idx]) + rp = idx + 1 + + if len(src[rp:]) < 4 { + return errors.New("invalid SASLInitialResponse") + } + rp += 4 // The rest of the message is data so we can just skip the size + dst.Data = src[rp:] + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *SASLInitialResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') + + dst = append(dst, []byte(src.AuthMechanism)...) + dst = append(dst, 0) + + dst = pgio.AppendInt32(dst, int32(len(src.Data))) + dst = append(dst, src.Data...) + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src SASLInitialResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + AuthMechanism string + Data string + }{ + Type: "SASLInitialResponse", + AuthMechanism: src.AuthMechanism, + Data: string(src.Data), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error { + // Ignore null, like in the main JSON package. + if string(data) == "null" { + return nil + } + + var msg struct { + AuthMechanism string + Data string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + dst.AuthMechanism = msg.AuthMechanism + if msg.Data != "" { + decoded, err := hex.DecodeString(msg.Data) + if err != nil { + return err + } + dst.Data = decoded + } + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go new file mode 100644 index 0000000..1b604c2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/sasl_response.go @@ -0,0 +1,56 @@ +package pgproto3 + +import ( + "encoding/hex" + "encoding/json" +) + +type SASLResponse struct { + Data []byte +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*SASLResponse) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *SASLResponse) Decode(src []byte) error { + *dst = SASLResponse{Data: src} + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *SASLResponse) Encode(dst []byte) ([]byte, error) { + dst, sp := beginMessage(dst, 'p') + dst = append(dst, src.Data...) + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src SASLResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + Data string + }{ + Type: "SASLResponse", + Data: string(src.Data), + }) +} + +// UnmarshalJSON implements encoding/json.Unmarshaler. +func (dst *SASLResponse) UnmarshalJSON(data []byte) error { + var msg struct { + Data string + } + if err := json.Unmarshal(data, &msg); err != nil { + return err + } + if msg.Data != "" { + decoded, err := hex.DecodeString(msg.Data) + if err != nil { + return err + } + dst.Data = decoded + } + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go b/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go new file mode 100644 index 0000000..bdfc7c4 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/ssl_request.go @@ -0,0 +1,48 @@ +package pgproto3 + +import ( + "encoding/binary" + "encoding/json" + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const sslRequestNumber = 80877103 + +type SSLRequest struct{} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*SSLRequest) Frontend() {} + +func (dst *SSLRequest) Decode(src []byte) error { + if len(src) < 4 { + return errors.New("ssl request too short") + } + + requestCode := binary.BigEndian.Uint32(src) + + if requestCode != sslRequestNumber { + return errors.New("bad ssl request code") + } + + return nil +} + +// Encode encodes src into dst. dst will include the 4 byte message length. +func (src *SSLRequest) Encode(dst []byte) ([]byte, error) { + dst = pgio.AppendInt32(dst, 8) + dst = pgio.AppendInt32(dst, sslRequestNumber) + return dst, nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src SSLRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ProtocolVersion uint32 + Parameters map[string]string + }{ + Type: "SSLRequest", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go new file mode 100644 index 0000000..eb48f72 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/startup_message.go @@ -0,0 +1,99 @@ +package pgproto3 + +import ( + "bytes" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const ( + ProtocolVersion30 = 196608 // 3.0 + ProtocolVersion32 = 196610 // 3.2 + ProtocolVersionLatest = ProtocolVersion32 // Latest is 3.2 + ProtocolVersionNumber = ProtocolVersion30 // Default is still 3.0 +) + +type StartupMessage struct { + ProtocolVersion uint32 + Parameters map[string]string +} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*StartupMessage) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *StartupMessage) Decode(src []byte) error { + if len(src) < 4 { + return errors.New("startup message too short") + } + + dst.ProtocolVersion = binary.BigEndian.Uint32(src) + rp := 4 + + if dst.ProtocolVersion != ProtocolVersion30 && dst.ProtocolVersion != ProtocolVersion32 { + return fmt.Errorf("Bad startup message version number. Expected %d or %d, got %d", ProtocolVersion30, ProtocolVersion32, dst.ProtocolVersion) + } + + dst.Parameters = make(map[string]string) + for { + idx := bytes.IndexByte(src[rp:], 0) + if idx < 0 { + return &invalidMessageFormatErr{messageType: "StartupMessage"} + } + key := string(src[rp : rp+idx]) + rp += idx + 1 + + idx = bytes.IndexByte(src[rp:], 0) + if idx < 0 { + return &invalidMessageFormatErr{messageType: "StartupMessage"} + } + value := string(src[rp : rp+idx]) + rp += idx + 1 + + dst.Parameters[key] = value + + if len(src[rp:]) == 1 { + if src[rp] != 0 { + return fmt.Errorf("Bad startup message last byte. Expected 0, got %d", src[rp]) + } + break + } + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *StartupMessage) Encode(dst []byte) ([]byte, error) { + sp := len(dst) + dst = pgio.AppendInt32(dst, -1) + + dst = pgio.AppendUint32(dst, src.ProtocolVersion) + for k, v := range src.Parameters { + dst = append(dst, k...) + dst = append(dst, 0) + dst = append(dst, v...) + dst = append(dst, 0) + } + dst = append(dst, 0) + + return finishMessage(dst, sp) +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src StartupMessage) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + ProtocolVersion uint32 + Parameters map[string]string + }{ + Type: "StartupMessage", + ProtocolVersion: src.ProtocolVersion, + Parameters: src.Parameters, + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go b/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go new file mode 100644 index 0000000..ea4fc95 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/sync.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type Sync struct{} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Sync) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Sync) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "Sync", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Sync) Encode(dst []byte) ([]byte, error) { + return append(dst, 'S', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Sync) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "Sync", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go b/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go new file mode 100644 index 0000000..35a9dc8 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/terminate.go @@ -0,0 +1,34 @@ +package pgproto3 + +import ( + "encoding/json" +) + +type Terminate struct{} + +// Frontend identifies this message as sendable by a PostgreSQL frontend. +func (*Terminate) Frontend() {} + +// Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message +// type identifier and 4 byte message length. +func (dst *Terminate) Decode(src []byte) error { + if len(src) != 0 { + return &invalidMessageLenErr{messageType: "Terminate", expectedLen: 0, actualLen: len(src)} + } + + return nil +} + +// Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length. +func (src *Terminate) Encode(dst []byte) ([]byte, error) { + return append(dst, 'X', 0, 0, 0, 4), nil +} + +// MarshalJSON implements encoding/json.Marshaler. +func (src Terminate) MarshalJSON() ([]byte, error) { + return json.Marshal(struct { + Type string + }{ + Type: "Terminate", + }) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgproto3/trace.go b/vendor/github.com/jackc/pgx/v5/pgproto3/trace.go new file mode 100644 index 0000000..2f9da62 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgproto3/trace.go @@ -0,0 +1,416 @@ +package pgproto3 + +import ( + "bytes" + "fmt" + "io" + "strconv" + "strings" + "sync" + "time" +) + +// tracer traces the messages send to and from a Backend or Frontend. The format it produces roughly mimics the +// format produced by the libpq C function PQtrace. +type tracer struct { + TracerOptions + + mux sync.Mutex + w io.Writer + buf *bytes.Buffer +} + +// TracerOptions controls tracing behavior. It is roughly equivalent to the libpq function PQsetTraceFlags. +type TracerOptions struct { + // SuppressTimestamps prevents printing of timestamps. + SuppressTimestamps bool + + // RegressMode redacts fields that may be vary between executions. + RegressMode bool +} + +func (t *tracer) traceMessage(sender byte, encodedLen int32, msg Message) { + switch msg := msg.(type) { + case *AuthenticationCleartextPassword: + t.traceAuthenticationCleartextPassword(sender, encodedLen, msg) + case *AuthenticationGSS: + t.traceAuthenticationGSS(sender, encodedLen, msg) + case *AuthenticationGSSContinue: + t.traceAuthenticationGSSContinue(sender, encodedLen, msg) + case *AuthenticationMD5Password: + t.traceAuthenticationMD5Password(sender, encodedLen, msg) + case *AuthenticationOk: + t.traceAuthenticationOk(sender, encodedLen, msg) + case *AuthenticationSASL: + t.traceAuthenticationSASL(sender, encodedLen, msg) + case *AuthenticationSASLContinue: + t.traceAuthenticationSASLContinue(sender, encodedLen, msg) + case *AuthenticationSASLFinal: + t.traceAuthenticationSASLFinal(sender, encodedLen, msg) + case *BackendKeyData: + t.traceBackendKeyData(sender, encodedLen, msg) + case *Bind: + t.traceBind(sender, encodedLen, msg) + case *BindComplete: + t.traceBindComplete(sender, encodedLen, msg) + case *CancelRequest: + t.traceCancelRequest(sender, encodedLen, msg) + case *Close: + t.traceClose(sender, encodedLen, msg) + case *CloseComplete: + t.traceCloseComplete(sender, encodedLen, msg) + case *CommandComplete: + t.traceCommandComplete(sender, encodedLen, msg) + case *CopyBothResponse: + t.traceCopyBothResponse(sender, encodedLen, msg) + case *CopyData: + t.traceCopyData(sender, encodedLen, msg) + case *CopyDone: + t.traceCopyDone(sender, encodedLen, msg) + case *CopyFail: + t.traceCopyFail(sender, encodedLen, msg) + case *CopyInResponse: + t.traceCopyInResponse(sender, encodedLen, msg) + case *CopyOutResponse: + t.traceCopyOutResponse(sender, encodedLen, msg) + case *DataRow: + t.traceDataRow(sender, encodedLen, msg) + case *Describe: + t.traceDescribe(sender, encodedLen, msg) + case *EmptyQueryResponse: + t.traceEmptyQueryResponse(sender, encodedLen, msg) + case *ErrorResponse: + t.traceErrorResponse(sender, encodedLen, msg) + case *Execute: + t.traceExecute(sender, encodedLen, msg) + case *Flush: + t.traceFlush(sender, encodedLen, msg) + case *FunctionCall: + t.traceFunctionCall(sender, encodedLen, msg) + case *FunctionCallResponse: + t.traceFunctionCallResponse(sender, encodedLen, msg) + case *GSSEncRequest: + t.traceGSSEncRequest(sender, encodedLen, msg) + case *NoData: + t.traceNoData(sender, encodedLen, msg) + case *NoticeResponse: + t.traceNoticeResponse(sender, encodedLen, msg) + case *NotificationResponse: + t.traceNotificationResponse(sender, encodedLen, msg) + case *ParameterDescription: + t.traceParameterDescription(sender, encodedLen, msg) + case *ParameterStatus: + t.traceParameterStatus(sender, encodedLen, msg) + case *Parse: + t.traceParse(sender, encodedLen, msg) + case *ParseComplete: + t.traceParseComplete(sender, encodedLen, msg) + case *PortalSuspended: + t.tracePortalSuspended(sender, encodedLen, msg) + case *Query: + t.traceQuery(sender, encodedLen, msg) + case *ReadyForQuery: + t.traceReadyForQuery(sender, encodedLen, msg) + case *RowDescription: + t.traceRowDescription(sender, encodedLen, msg) + case *SSLRequest: + t.traceSSLRequest(sender, encodedLen, msg) + case *StartupMessage: + t.traceStartupMessage(sender, encodedLen, msg) + case *Sync: + t.traceSync(sender, encodedLen, msg) + case *Terminate: + t.traceTerminate(sender, encodedLen, msg) + default: + t.writeTrace(sender, encodedLen, "Unknown", nil) + } +} + +func (t *tracer) traceAuthenticationCleartextPassword(sender byte, encodedLen int32, msg *AuthenticationCleartextPassword) { + t.writeTrace(sender, encodedLen, "AuthenticationCleartextPassword", nil) +} + +func (t *tracer) traceAuthenticationGSS(sender byte, encodedLen int32, msg *AuthenticationGSS) { + t.writeTrace(sender, encodedLen, "AuthenticationGSS", nil) +} + +func (t *tracer) traceAuthenticationGSSContinue(sender byte, encodedLen int32, msg *AuthenticationGSSContinue) { + t.writeTrace(sender, encodedLen, "AuthenticationGSSContinue", nil) +} + +func (t *tracer) traceAuthenticationMD5Password(sender byte, encodedLen int32, msg *AuthenticationMD5Password) { + t.writeTrace(sender, encodedLen, "AuthenticationMD5Password", nil) +} + +func (t *tracer) traceAuthenticationOk(sender byte, encodedLen int32, msg *AuthenticationOk) { + t.writeTrace(sender, encodedLen, "AuthenticationOk", nil) +} + +func (t *tracer) traceAuthenticationSASL(sender byte, encodedLen int32, msg *AuthenticationSASL) { + t.writeTrace(sender, encodedLen, "AuthenticationSASL", nil) +} + +func (t *tracer) traceAuthenticationSASLContinue(sender byte, encodedLen int32, msg *AuthenticationSASLContinue) { + t.writeTrace(sender, encodedLen, "AuthenticationSASLContinue", nil) +} + +func (t *tracer) traceAuthenticationSASLFinal(sender byte, encodedLen int32, msg *AuthenticationSASLFinal) { + t.writeTrace(sender, encodedLen, "AuthenticationSASLFinal", nil) +} + +func (t *tracer) traceBackendKeyData(sender byte, encodedLen int32, msg *BackendKeyData) { + t.writeTrace(sender, encodedLen, "BackendKeyData", func() { + if t.RegressMode { + t.buf.WriteString("\t NNNN NNNN") + } else { + fmt.Fprintf(t.buf, "\t %d %d", msg.ProcessID, msg.SecretKey) + } + }) +} + +func (t *tracer) traceBind(sender byte, encodedLen int32, msg *Bind) { + t.writeTrace(sender, encodedLen, "Bind", func() { + fmt.Fprintf(t.buf, "\t %s %s %d", traceDoubleQuotedString([]byte(msg.DestinationPortal)), traceDoubleQuotedString([]byte(msg.PreparedStatement)), len(msg.ParameterFormatCodes)) + for _, fc := range msg.ParameterFormatCodes { + fmt.Fprintf(t.buf, " %d", fc) + } + fmt.Fprintf(t.buf, " %d", len(msg.Parameters)) + for _, p := range msg.Parameters { + fmt.Fprintf(t.buf, " %s", traceSingleQuotedString(p)) + } + fmt.Fprintf(t.buf, " %d", len(msg.ResultFormatCodes)) + for _, fc := range msg.ResultFormatCodes { + fmt.Fprintf(t.buf, " %d", fc) + } + }) +} + +func (t *tracer) traceBindComplete(sender byte, encodedLen int32, msg *BindComplete) { + t.writeTrace(sender, encodedLen, "BindComplete", nil) +} + +func (t *tracer) traceCancelRequest(sender byte, encodedLen int32, msg *CancelRequest) { + t.writeTrace(sender, encodedLen, "CancelRequest", nil) +} + +func (t *tracer) traceClose(sender byte, encodedLen int32, msg *Close) { + t.writeTrace(sender, encodedLen, "Close", nil) +} + +func (t *tracer) traceCloseComplete(sender byte, encodedLen int32, msg *CloseComplete) { + t.writeTrace(sender, encodedLen, "CloseComplete", nil) +} + +func (t *tracer) traceCommandComplete(sender byte, encodedLen int32, msg *CommandComplete) { + t.writeTrace(sender, encodedLen, "CommandComplete", func() { + fmt.Fprintf(t.buf, "\t %s", traceDoubleQuotedString(msg.CommandTag)) + }) +} + +func (t *tracer) traceCopyBothResponse(sender byte, encodedLen int32, msg *CopyBothResponse) { + t.writeTrace(sender, encodedLen, "CopyBothResponse", nil) +} + +func (t *tracer) traceCopyData(sender byte, encodedLen int32, msg *CopyData) { + t.writeTrace(sender, encodedLen, "CopyData", nil) +} + +func (t *tracer) traceCopyDone(sender byte, encodedLen int32, msg *CopyDone) { + t.writeTrace(sender, encodedLen, "CopyDone", nil) +} + +func (t *tracer) traceCopyFail(sender byte, encodedLen int32, msg *CopyFail) { + t.writeTrace(sender, encodedLen, "CopyFail", func() { + fmt.Fprintf(t.buf, "\t %s", traceDoubleQuotedString([]byte(msg.Message))) + }) +} + +func (t *tracer) traceCopyInResponse(sender byte, encodedLen int32, msg *CopyInResponse) { + t.writeTrace(sender, encodedLen, "CopyInResponse", nil) +} + +func (t *tracer) traceCopyOutResponse(sender byte, encodedLen int32, msg *CopyOutResponse) { + t.writeTrace(sender, encodedLen, "CopyOutResponse", nil) +} + +func (t *tracer) traceDataRow(sender byte, encodedLen int32, msg *DataRow) { + t.writeTrace(sender, encodedLen, "DataRow", func() { + fmt.Fprintf(t.buf, "\t %d", len(msg.Values)) + for _, v := range msg.Values { + if v == nil { + t.buf.WriteString(" -1") + } else { + fmt.Fprintf(t.buf, " %d %s", len(v), traceSingleQuotedString(v)) + } + } + }) +} + +func (t *tracer) traceDescribe(sender byte, encodedLen int32, msg *Describe) { + t.writeTrace(sender, encodedLen, "Describe", func() { + fmt.Fprintf(t.buf, "\t %c %s", msg.ObjectType, traceDoubleQuotedString([]byte(msg.Name))) + }) +} + +func (t *tracer) traceEmptyQueryResponse(sender byte, encodedLen int32, msg *EmptyQueryResponse) { + t.writeTrace(sender, encodedLen, "EmptyQueryResponse", nil) +} + +func (t *tracer) traceErrorResponse(sender byte, encodedLen int32, msg *ErrorResponse) { + t.writeTrace(sender, encodedLen, "ErrorResponse", nil) +} + +func (t *tracer) traceExecute(sender byte, encodedLen int32, msg *Execute) { + t.writeTrace(sender, encodedLen, "Execute", func() { + fmt.Fprintf(t.buf, "\t %s %d", traceDoubleQuotedString([]byte(msg.Portal)), msg.MaxRows) + }) +} + +func (t *tracer) traceFlush(sender byte, encodedLen int32, msg *Flush) { + t.writeTrace(sender, encodedLen, "Flush", nil) +} + +func (t *tracer) traceFunctionCall(sender byte, encodedLen int32, msg *FunctionCall) { + t.writeTrace(sender, encodedLen, "FunctionCall", nil) +} + +func (t *tracer) traceFunctionCallResponse(sender byte, encodedLen int32, msg *FunctionCallResponse) { + t.writeTrace(sender, encodedLen, "FunctionCallResponse", nil) +} + +func (t *tracer) traceGSSEncRequest(sender byte, encodedLen int32, msg *GSSEncRequest) { + t.writeTrace(sender, encodedLen, "GSSEncRequest", nil) +} + +func (t *tracer) traceNoData(sender byte, encodedLen int32, msg *NoData) { + t.writeTrace(sender, encodedLen, "NoData", nil) +} + +func (t *tracer) traceNoticeResponse(sender byte, encodedLen int32, msg *NoticeResponse) { + t.writeTrace(sender, encodedLen, "NoticeResponse", nil) +} + +func (t *tracer) traceNotificationResponse(sender byte, encodedLen int32, msg *NotificationResponse) { + t.writeTrace(sender, encodedLen, "NotificationResponse", func() { + fmt.Fprintf(t.buf, "\t %d %s %s", msg.PID, traceDoubleQuotedString([]byte(msg.Channel)), traceDoubleQuotedString([]byte(msg.Payload))) + }) +} + +func (t *tracer) traceParameterDescription(sender byte, encodedLen int32, msg *ParameterDescription) { + t.writeTrace(sender, encodedLen, "ParameterDescription", nil) +} + +func (t *tracer) traceParameterStatus(sender byte, encodedLen int32, msg *ParameterStatus) { + t.writeTrace(sender, encodedLen, "ParameterStatus", func() { + fmt.Fprintf(t.buf, "\t %s %s", traceDoubleQuotedString([]byte(msg.Name)), traceDoubleQuotedString([]byte(msg.Value))) + }) +} + +func (t *tracer) traceParse(sender byte, encodedLen int32, msg *Parse) { + t.writeTrace(sender, encodedLen, "Parse", func() { + fmt.Fprintf(t.buf, "\t %s %s %d", traceDoubleQuotedString([]byte(msg.Name)), traceDoubleQuotedString([]byte(msg.Query)), len(msg.ParameterOIDs)) + for _, oid := range msg.ParameterOIDs { + fmt.Fprintf(t.buf, " %d", oid) + } + }) +} + +func (t *tracer) traceParseComplete(sender byte, encodedLen int32, msg *ParseComplete) { + t.writeTrace(sender, encodedLen, "ParseComplete", nil) +} + +func (t *tracer) tracePortalSuspended(sender byte, encodedLen int32, msg *PortalSuspended) { + t.writeTrace(sender, encodedLen, "PortalSuspended", nil) +} + +func (t *tracer) traceQuery(sender byte, encodedLen int32, msg *Query) { + t.writeTrace(sender, encodedLen, "Query", func() { + fmt.Fprintf(t.buf, "\t %s", traceDoubleQuotedString([]byte(msg.String))) + }) +} + +func (t *tracer) traceReadyForQuery(sender byte, encodedLen int32, msg *ReadyForQuery) { + t.writeTrace(sender, encodedLen, "ReadyForQuery", func() { + fmt.Fprintf(t.buf, "\t %c", msg.TxStatus) + }) +} + +func (t *tracer) traceRowDescription(sender byte, encodedLen int32, msg *RowDescription) { + t.writeTrace(sender, encodedLen, "RowDescription", func() { + fmt.Fprintf(t.buf, "\t %d", len(msg.Fields)) + for _, fd := range msg.Fields { + fmt.Fprintf(t.buf, ` %s %d %d %d %d %d %d`, traceDoubleQuotedString(fd.Name), fd.TableOID, fd.TableAttributeNumber, fd.DataTypeOID, fd.DataTypeSize, fd.TypeModifier, fd.Format) + } + }) +} + +func (t *tracer) traceSSLRequest(sender byte, encodedLen int32, msg *SSLRequest) { + t.writeTrace(sender, encodedLen, "SSLRequest", nil) +} + +func (t *tracer) traceStartupMessage(sender byte, encodedLen int32, msg *StartupMessage) { + t.writeTrace(sender, encodedLen, "StartupMessage", nil) +} + +func (t *tracer) traceSync(sender byte, encodedLen int32, msg *Sync) { + t.writeTrace(sender, encodedLen, "Sync", nil) +} + +func (t *tracer) traceTerminate(sender byte, encodedLen int32, msg *Terminate) { + t.writeTrace(sender, encodedLen, "Terminate", nil) +} + +func (t *tracer) writeTrace(sender byte, encodedLen int32, msgType string, writeDetails func()) { + t.mux.Lock() + defer t.mux.Unlock() + defer func() { + if t.buf.Cap() > 1024 { + t.buf = &bytes.Buffer{} + } else { + t.buf.Reset() + } + }() + + if !t.SuppressTimestamps { + now := time.Now() + t.buf.WriteString(now.Format("2006-01-02 15:04:05.000000")) + t.buf.WriteByte('\t') + } + + t.buf.WriteByte(sender) + t.buf.WriteByte('\t') + t.buf.WriteString(msgType) + t.buf.WriteByte('\t') + t.buf.WriteString(strconv.FormatInt(int64(encodedLen), 10)) + + if writeDetails != nil { + writeDetails() + } + + t.buf.WriteByte('\n') + t.buf.WriteTo(t.w) +} + +// traceDoubleQuotedString returns t.buf as a double-quoted string without any escaping. It is roughly equivalent to +// pqTraceOutputString in libpq. +func traceDoubleQuotedString(buf []byte) string { + return `"` + string(buf) + `"` +} + +// traceSingleQuotedString returns buf as a single-quoted string with non-printable characters hex-escaped. It is +// roughly equivalent to pqTraceOutputNchar in libpq. +func traceSingleQuotedString(buf []byte) string { + sb := &strings.Builder{} + + sb.WriteByte('\'') + for _, b := range buf { + if b < 32 || b > 126 { + fmt.Fprintf(sb, `\x%x`, b) + } else { + sb.WriteByte(b) + } + } + sb.WriteByte('\'') + + return sb.String() +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array.go b/vendor/github.com/jackc/pgx/v5/pgtype/array.go new file mode 100644 index 0000000..26505fb --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array.go @@ -0,0 +1,469 @@ +package pgtype + +import ( + "bytes" + "encoding/binary" + "fmt" + "io" + "strconv" + "strings" + "unicode" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// Information on the internals of PostgreSQL arrays can be found in +// src/include/utils/array.h and src/backend/utils/adt/arrayfuncs.c. Of +// particular interest is the array_send function. + +type arrayHeader struct { + ContainsNull bool + ElementOID uint32 + Dimensions []ArrayDimension +} + +type ArrayDimension struct { + Length int32 + LowerBound int32 +} + +// cardinality returns the number of elements in an array of dimensions size. +func cardinality(dimensions []ArrayDimension) int { + if len(dimensions) == 0 { + return 0 + } + + elementCount := int(dimensions[0].Length) + for _, d := range dimensions[1:] { + elementCount *= int(d.Length) + } + + if elementCount < 0 { + return 0 + } + + return elementCount +} + +func (dst *arrayHeader) DecodeBinary(m *Map, src []byte) (int, error) { + if len(src) < 12 { + return 0, fmt.Errorf("array header too short: %d", len(src)) + } + + rp := 0 + + numDims := int(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + + if numDims > 6 { + return 0, fmt.Errorf("array has too many dimensions: %d", numDims) + } + + dst.ContainsNull = binary.BigEndian.Uint32(src[rp:]) == 1 + rp += 4 + + dst.ElementOID = binary.BigEndian.Uint32(src[rp:]) + rp += 4 + + if len(src) < 12+numDims*8 { + return 0, fmt.Errorf("array header too short for %d dimensions: %d", numDims, len(src)) + } + dst.Dimensions = make([]ArrayDimension, numDims) + for i := range dst.Dimensions { + dst.Dimensions[i].Length = int32(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + + dst.Dimensions[i].LowerBound = int32(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + } + + return rp, nil +} + +func (src arrayHeader) EncodeBinary(buf []byte) []byte { + buf = pgio.AppendInt32(buf, int32(len(src.Dimensions))) + + var containsNull int32 + if src.ContainsNull { + containsNull = 1 + } + buf = pgio.AppendInt32(buf, containsNull) + + buf = pgio.AppendUint32(buf, src.ElementOID) + + for i := range src.Dimensions { + buf = pgio.AppendInt32(buf, src.Dimensions[i].Length) + buf = pgio.AppendInt32(buf, src.Dimensions[i].LowerBound) + } + + return buf +} + +type untypedTextArray struct { + Elements []string + Quoted []bool + Dimensions []ArrayDimension +} + +func parseUntypedTextArray(src string) (*untypedTextArray, error) { + dst := &untypedTextArray{ + Elements: []string{}, + Quoted: []bool{}, + Dimensions: []ArrayDimension{}, + } + + buf := bytes.NewBufferString(src) + + skipWhitespace(buf) + + r, _, err := buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + var explicitDimensions []ArrayDimension + + // Array has explicit dimensions + if r == '[' { + buf.UnreadRune() + + for { + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + if r == '=' { + break + } else if r != '[' { + return nil, fmt.Errorf("invalid array, expected '[' or '=' got %v", r) + } + + lower, err := arrayParseInteger(buf) + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + if r != ':' { + return nil, fmt.Errorf("invalid array, expected ':' got %v", r) + } + + upper, err := arrayParseInteger(buf) + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + if r != ']' { + return nil, fmt.Errorf("invalid array, expected ']' got %v", r) + } + + explicitDimensions = append(explicitDimensions, ArrayDimension{LowerBound: lower, Length: upper - lower + 1}) + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + } + + if r != '{' { + return nil, fmt.Errorf("invalid array, expected '{' got %v", r) + } + + implicitDimensions := []ArrayDimension{{LowerBound: 1, Length: 0}} + + // Consume all initial opening brackets. This provides number of dimensions. + for { + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + if r == '{' { + implicitDimensions[len(implicitDimensions)-1].Length = 1 + implicitDimensions = append(implicitDimensions, ArrayDimension{LowerBound: 1}) + } else { + buf.UnreadRune() + break + } + } + currentDim := len(implicitDimensions) - 1 + counterDim := currentDim + + for { + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + switch r { + case '{': + if currentDim == counterDim { + implicitDimensions[currentDim].Length++ + } + currentDim++ + case ',': + case '}': + currentDim-- + if currentDim < counterDim { + counterDim = currentDim + } + default: + buf.UnreadRune() + value, quoted, err := arrayParseValue(buf) + if err != nil { + return nil, fmt.Errorf("invalid array value: %w", err) + } + if currentDim == counterDim { + implicitDimensions[currentDim].Length++ + } + dst.Quoted = append(dst.Quoted, quoted) + dst.Elements = append(dst.Elements, value) + } + + if currentDim < 0 { + break + } + } + + skipWhitespace(buf) + + if buf.Len() > 0 { + return nil, fmt.Errorf("unexpected trailing data: %v", buf.String()) + } + + switch { + case len(dst.Elements) == 0: + case len(explicitDimensions) > 0: + dst.Dimensions = explicitDimensions + default: + dst.Dimensions = implicitDimensions + } + + return dst, nil +} + +func skipWhitespace(buf *bytes.Buffer) { + var r rune + var err error + for r, _, _ = buf.ReadRune(); unicode.IsSpace(r); r, _, _ = buf.ReadRune() { + } + + if err != io.EOF { + buf.UnreadRune() + } +} + +func arrayParseValue(buf *bytes.Buffer) (string, bool, error) { + r, _, err := buf.ReadRune() + if err != nil { + return "", false, err + } + if r == '"' { + return arrayParseQuotedValue(buf) + } + buf.UnreadRune() + + s := &bytes.Buffer{} + + for { + r, _, err := buf.ReadRune() + if err != nil { + return "", false, err + } + + switch r { + case ',', '}': + buf.UnreadRune() + return s.String(), false, nil + } + + s.WriteRune(r) + } +} + +func arrayParseQuotedValue(buf *bytes.Buffer) (string, bool, error) { + s := &bytes.Buffer{} + + for { + r, _, err := buf.ReadRune() + if err != nil { + return "", false, err + } + + switch r { + case '\\': + r, _, err = buf.ReadRune() + if err != nil { + return "", false, err + } + case '"': + _, _, err = buf.ReadRune() + if err != nil { + return "", false, err + } + buf.UnreadRune() + return s.String(), true, nil + } + s.WriteRune(r) + } +} + +func arrayParseInteger(buf *bytes.Buffer) (int32, error) { + s := &bytes.Buffer{} + + for { + r, _, err := buf.ReadRune() + if err != nil { + return 0, err + } + + if ('0' <= r && r <= '9') || r == '-' { + s.WriteRune(r) + } else { + buf.UnreadRune() + n, err := strconv.ParseInt(s.String(), 10, 32) + if err != nil { + return 0, err + } + return int32(n), nil + } + } +} + +func encodeTextArrayDimensions(buf []byte, dimensions []ArrayDimension) []byte { + var customDimensions bool + for _, dim := range dimensions { + if dim.LowerBound != 1 { + customDimensions = true + } + } + + if !customDimensions { + return buf + } + + for _, dim := range dimensions { + buf = append(buf, '[') + buf = append(buf, strconv.FormatInt(int64(dim.LowerBound), 10)...) + buf = append(buf, ':') + buf = append(buf, strconv.FormatInt(int64(dim.LowerBound+dim.Length-1), 10)...) + buf = append(buf, ']') + } + + return append(buf, '=') +} + +var quoteArrayReplacer = strings.NewReplacer(`\`, `\\`, `"`, `\"`) + +func quoteArrayElement(src string) string { + return `"` + quoteArrayReplacer.Replace(src) + `"` +} + +func isSpace(ch byte) bool { + // see array_isspace: + // https://github.com/postgres/postgres/blob/master/src/backend/utils/adt/arrayfuncs.c + return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\v' || ch == '\f' +} + +func quoteArrayElementIfNeeded(src string) string { + if src == "" || (len(src) == 4 && strings.EqualFold(src, "null")) || isSpace(src[0]) || isSpace(src[len(src)-1]) || strings.ContainsAny(src, `{},"\`) { + return quoteArrayElement(src) + } + return src +} + +// Array represents a PostgreSQL array for T. It implements the [ArrayGetter] and [ArraySetter] interfaces. It preserves +// PostgreSQL dimensions and custom lower bounds. Use [FlatArray] if these are not needed. +type Array[T any] struct { + Elements []T + Dims []ArrayDimension + Valid bool +} + +func (a Array[T]) Dimensions() []ArrayDimension { + return a.Dims +} + +func (a Array[T]) Index(i int) any { + return a.Elements[i] +} + +func (a Array[T]) IndexType() any { + var el T + return el +} + +func (a *Array[T]) SetDimensions(dimensions []ArrayDimension) error { + if dimensions == nil { + *a = Array[T]{} + return nil + } + + elementCount := cardinality(dimensions) + *a = Array[T]{ + Elements: make([]T, elementCount), + Dims: dimensions, + Valid: true, + } + + return nil +} + +func (a Array[T]) ScanIndex(i int) any { + return &a.Elements[i] +} + +func (a Array[T]) ScanIndexType() any { + return new(T) +} + +// FlatArray implements the [ArrayGetter] and [ArraySetter] interfaces for any slice of T. It ignores PostgreSQL dimensions +// and custom lower bounds. Use [Array] to preserve these. +type FlatArray[T any] []T + +func (a FlatArray[T]) Dimensions() []ArrayDimension { + if a == nil { + return nil + } + + return []ArrayDimension{{Length: int32(len(a)), LowerBound: 1}} +} + +func (a FlatArray[T]) Index(i int) any { + return a[i] +} + +func (a FlatArray[T]) IndexType() any { + var el T + return el +} + +func (a *FlatArray[T]) SetDimensions(dimensions []ArrayDimension) error { + if dimensions == nil { + *a = nil + return nil + } + + elementCount := cardinality(dimensions) + *a = make(FlatArray[T], elementCount) + return nil +} + +func (a FlatArray[T]) ScanIndex(i int) any { + return &a[i] +} + +func (a FlatArray[T]) ScanIndexType() any { + return new(T) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go new file mode 100644 index 0000000..ac01496 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/array_codec.go @@ -0,0 +1,428 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "reflect" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// ArrayGetter is a type that can be converted into a PostgreSQL array. +type ArrayGetter interface { + // Dimensions returns the array dimensions. If array is nil then nil is returned. + Dimensions() []ArrayDimension + + // Index returns the element at i. + Index(i int) any + + // IndexType returns a non-nil scan target of the type Index will return. This is used by ArrayCodec.PlanEncode. + IndexType() any +} + +// ArraySetter is a type can be set from a PostgreSQL array. +type ArraySetter interface { + // SetDimensions prepares the value such that ScanIndex can be called for each element. This will remove any existing + // elements. dimensions may be nil to indicate a NULL array. If unable to exactly preserve dimensions SetDimensions + // may return an error or silently flatten the array dimensions. + SetDimensions(dimensions []ArrayDimension) error + + // ScanIndex returns a value usable as a scan target for i. SetDimensions must be called before ScanIndex. + ScanIndex(i int) any + + // ScanIndexType returns a non-nil scan target of the type ScanIndex will return. This is used by + // ArrayCodec.PlanScan. + ScanIndexType() any +} + +// ArrayCodec is a codec for any array type. +type ArrayCodec struct { + ElementType *Type +} + +func (c *ArrayCodec) FormatSupported(format int16) bool { + return c.ElementType.Codec.FormatSupported(format) +} + +func (c *ArrayCodec) PreferredFormat() int16 { + // The binary format should always be preferred for arrays if it is supported. Usually, this will happen automatically + // because most types that support binary prefer it. However, text, json, and jsonb support binary but prefer the text + // format. This is because it is simpler for jsonb and PostgreSQL can be significantly faster using the text format + // for text-like data types than binary. However, arrays appear to always be faster in binary. + // + // https://www.postgresql.org/message-id/CAMovtNoHFod2jMAKQjjxv209PCTJx5Kc66anwWvX0mEiaXwgmA%40mail.gmail.com + if c.ElementType.Codec.FormatSupported(BinaryFormatCode) { + return BinaryFormatCode + } + return TextFormatCode +} + +func (c *ArrayCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + arrayValuer, ok := value.(ArrayGetter) + if !ok { + return nil + } + + elementType := arrayValuer.IndexType() + + elementEncodePlan := m.PlanEncode(c.ElementType.OID, format, elementType) + if elementEncodePlan == nil { + if reflect.TypeOf(elementType) != nil { + return nil + } + } + + switch format { + case BinaryFormatCode: + return &encodePlanArrayCodecBinary{ac: c, m: m, oid: oid} + case TextFormatCode: + return &encodePlanArrayCodecText{ac: c, m: m, oid: oid} + } + + return nil +} + +type encodePlanArrayCodecText struct { + ac *ArrayCodec + m *Map + oid uint32 +} + +func (p *encodePlanArrayCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + array := value.(ArrayGetter) + + dimensions := array.Dimensions() + if dimensions == nil { + return nil, nil + } + + elementCount := cardinality(dimensions) + if elementCount == 0 { + return append(buf, '{', '}'), nil + } + + buf = encodeTextArrayDimensions(buf, dimensions) + + // dimElemCounts is the multiples of elements that each array lies on. For + // example, a single dimension array of length 4 would have a dimElemCounts of + // [4]. A multi-dimensional array of lengths [3,5,2] would have a + // dimElemCounts of [30,10,2]. This is used to simplify when to render a '{' + // or '}'. + dimElemCounts := make([]int, len(dimensions)) + dimElemCounts[len(dimensions)-1] = int(dimensions[len(dimensions)-1].Length) + for i := len(dimensions) - 2; i > -1; i-- { + dimElemCounts[i] = int(dimensions[i].Length) * dimElemCounts[i+1] + } + + var encodePlan EncodePlan + var lastElemType reflect.Type + inElemBuf := make([]byte, 0, 32) + for i := range elementCount { + if i > 0 { + buf = append(buf, ',') + } + + for _, dec := range dimElemCounts { + if i%dec == 0 { + buf = append(buf, '{') + } + } + + elem := array.Index(i) + var elemBuf []byte + isNil, callNilDriverValuer := isNilDriverValuer(elem) + if !isNil { + elemType := reflect.TypeOf(elem) + if lastElemType != elemType { + lastElemType = elemType + encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, TextFormatCode, elem) + if encodePlan == nil { + return nil, fmt.Errorf("unable to encode %v", array.Index(i)) + } + } + elemBuf, err = encodePlan.Encode(elem, inElemBuf) + if err != nil { + return nil, err + } + } else if callNilDriverValuer { + elemBuf, err = (&encodePlanDriverValuer{m: p.m, oid: p.ac.ElementType.OID, formatCode: TextFormatCode}).Encode(elem, inElemBuf) + if err != nil { + return nil, err + } + } + + if elemBuf == nil { + buf = append(buf, `NULL`...) + } else { + buf = append(buf, quoteArrayElementIfNeeded(string(elemBuf))...) + } + + for _, dec := range dimElemCounts { + if (i+1)%dec == 0 { + buf = append(buf, '}') + } + } + } + + return buf, nil +} + +type encodePlanArrayCodecBinary struct { + ac *ArrayCodec + m *Map + oid uint32 +} + +func (p *encodePlanArrayCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + array := value.(ArrayGetter) + + dimensions := array.Dimensions() + if dimensions == nil { + return nil, nil + } + + arrayHeader := arrayHeader{ + Dimensions: dimensions, + ElementOID: p.ac.ElementType.OID, + } + + containsNullIndex := len(buf) + 4 + + buf = arrayHeader.EncodeBinary(buf) + + elementCount := cardinality(dimensions) + + var encodePlan EncodePlan + var lastElemType reflect.Type + for i := range elementCount { + sp := len(buf) + buf = pgio.AppendInt32(buf, -1) + + elem := array.Index(i) + var elemBuf []byte + isNil, callNilDriverValuer := isNilDriverValuer(elem) + if !isNil { + elemType := reflect.TypeOf(elem) + if lastElemType != elemType { + lastElemType = elemType + encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, BinaryFormatCode, elem) + if encodePlan == nil { + return nil, fmt.Errorf("unable to encode %v", array.Index(i)) + } + } + elemBuf, err = encodePlan.Encode(elem, buf) + if err != nil { + return nil, err + } + } else if callNilDriverValuer { + elemBuf, err = (&encodePlanDriverValuer{m: p.m, oid: p.ac.ElementType.OID, formatCode: BinaryFormatCode}).Encode(elem, buf) + if err != nil { + return nil, err + } + } + + if elemBuf == nil { + pgio.SetInt32(buf[containsNullIndex:], 1) + } else { + buf = elemBuf + pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) + } + } + + return buf, nil +} + +func (c *ArrayCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + arrayScanner, ok := target.(ArraySetter) + if !ok { + return nil + } + + // target / arrayScanner might be a pointer to a nil. If it is create one so we can call ScanIndexType to plan the + // scan of the elements. + if isNil, _ := isNilDriverValuer(target); isNil { + arrayScanner = reflect.New(reflect.TypeOf(target).Elem()).Interface().(ArraySetter) + } + + elementType := arrayScanner.ScanIndexType() + + elementScanPlan := m.PlanScan(c.ElementType.OID, format, elementType) + if _, ok := elementScanPlan.(*scanPlanFail); ok { + return nil + } + + return &scanPlanArrayCodec{ + arrayCodec: c, + m: m, + oid: oid, + formatCode: format, + } +} + +func (c *ArrayCodec) decodeBinary(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { + var arrayHeader arrayHeader + rp, err := arrayHeader.DecodeBinary(m, src) + if err != nil { + return err + } + + elementCount := cardinality(arrayHeader.Dimensions) + // Each element carries at minimum a 4-byte length header, so elementCount cannot exceed the + // remaining bytes / 4. This bounds the allocation in SetDimensions and the loop below against a + // malicious server claiming huge dimensions in a small message. + if maxElements := len(src[rp:]) / 4; elementCount > maxElements { + return fmt.Errorf("array claims %d elements but only %d bytes remain", elementCount, len(src[rp:])) + } + + err = array.SetDimensions(arrayHeader.Dimensions) + if err != nil { + return err + } + + if elementCount == 0 { + return nil + } + + elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0)) + if elementScanPlan == nil { + elementScanPlan = m.PlanScan(c.ElementType.OID, BinaryFormatCode, array.ScanIndex(0)) + } + + for i := range elementCount { + if len(src[rp:]) < 4 { + return fmt.Errorf("array body truncated at element %d", i) + } + elem := array.ScanIndex(i) + elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + var elemSrc []byte + if elemLen >= 0 { + if len(src[rp:]) < elemLen { + return fmt.Errorf("array element %d length %d exceeds remaining %d bytes", i, elemLen, len(src[rp:])) + } + elemSrc = src[rp : rp+elemLen] + rp += elemLen + } + err = elementScanPlan.Scan(elemSrc, elem) + if err != nil { + return fmt.Errorf("failed to scan array element %d: %w", i, err) + } + } + + return nil +} + +func (c *ArrayCodec) decodeText(m *Map, arrayOID uint32, src []byte, array ArraySetter) error { + uta, err := parseUntypedTextArray(string(src)) + if err != nil { + return err + } + + err = array.SetDimensions(uta.Dimensions) + if err != nil { + return err + } + + if len(uta.Elements) == 0 { + return nil + } + + elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, TextFormatCode, array.ScanIndex(0)) + if elementScanPlan == nil { + elementScanPlan = m.PlanScan(c.ElementType.OID, TextFormatCode, array.ScanIndex(0)) + } + + for i, s := range uta.Elements { + elem := array.ScanIndex(i) + var elemSrc []byte + if s != "NULL" || uta.Quoted[i] { + elemSrc = []byte(s) + } + + err = elementScanPlan.Scan(elemSrc, elem) + if err != nil { + return err + } + } + + return nil +} + +type scanPlanArrayCodec struct { + arrayCodec *ArrayCodec + m *Map + oid uint32 + formatCode int16 + elementScanPlan ScanPlan +} + +func (spac *scanPlanArrayCodec) Scan(src []byte, dst any) error { + c := spac.arrayCodec + m := spac.m + oid := spac.oid + formatCode := spac.formatCode + + array := dst.(ArraySetter) + + if src == nil { + return array.SetDimensions(nil) + } + + switch formatCode { + case BinaryFormatCode: + return c.decodeBinary(m, oid, src, array) + case TextFormatCode: + return c.decodeText(m, oid, src, array) + default: + return fmt.Errorf("unknown format code %d", formatCode) + } +} + +func (c *ArrayCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + return string(src), nil + case BinaryFormatCode: + buf := make([]byte, len(src)) + copy(buf, src) + return buf, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} + +func (c *ArrayCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var slice []any + err := m.PlanScan(oid, format, &slice).Scan(src, &slice) + return slice, err +} + +func isRagged(slice reflect.Value) bool { + if slice.Type().Elem().Kind() != reflect.Slice { + return false + } + + sliceLen := slice.Len() + innerLen := 0 + for i := range sliceLen { + if i == 0 { + innerLen = slice.Index(i).Len() + } else if slice.Index(i).Len() != innerLen { + return true + } + if isRagged(slice.Index(i)) { + return true + } + } + + return false +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bits.go b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go new file mode 100644 index 0000000..986fe23 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bits.go @@ -0,0 +1,208 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type BitsScanner interface { + ScanBits(v Bits) error +} + +type BitsValuer interface { + BitsValue() (Bits, error) +} + +// Bits represents the PostgreSQL bit and varbit types. +type Bits struct { + Bytes []byte + Len int32 // Number of bits + Valid bool +} + +// ScanBits implements the [BitsScanner] interface. +func (b *Bits) ScanBits(v Bits) error { + *b = v + return nil +} + +// BitsValue implements the [BitsValuer] interface. +func (b Bits) BitsValue() (Bits, error) { + return b, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Bits) Scan(src any) error { + if src == nil { + *dst = Bits{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToBitsScanner{}.Scan([]byte(src), dst) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Bits) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + buf, err := BitsCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type BitsCodec struct{} + +func (BitsCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (BitsCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (BitsCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(BitsValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanBitsCodecBinary{} + case TextFormatCode: + return encodePlanBitsCodecText{} + } + + return nil +} + +type encodePlanBitsCodecBinary struct{} + +func (encodePlanBitsCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + bits, err := value.(BitsValuer).BitsValue() + if err != nil { + return nil, err + } + + if !bits.Valid { + return nil, nil + } + + buf = pgio.AppendInt32(buf, bits.Len) + return append(buf, bits.Bytes...), nil +} + +type encodePlanBitsCodecText struct{} + +func (encodePlanBitsCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + bits, err := value.(BitsValuer).BitsValue() + if err != nil { + return nil, err + } + + if !bits.Valid { + return nil, nil + } + + for i := int32(0); i < bits.Len; i++ { + byteIdx := i / 8 + bitMask := byte(128 >> byte(i%8)) + char := byte('0') + if bits.Bytes[byteIdx]&bitMask > 0 { + char = '1' + } + buf = append(buf, char) + } + + return buf, nil +} + +func (BitsCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(BitsScanner); ok { + return scanPlanBinaryBitsToBitsScanner{} + } + case TextFormatCode: + if _, ok := target.(BitsScanner); ok { + return scanPlanTextAnyToBitsScanner{} + } + } + + return nil +} + +func (c BitsCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c BitsCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var box Bits + err := codecScan(c, m, oid, format, src, &box) + if err != nil { + return nil, err + } + return box, nil +} + +type scanPlanBinaryBitsToBitsScanner struct{} + +func (scanPlanBinaryBitsToBitsScanner) Scan(src []byte, dst any) error { + scanner := (dst).(BitsScanner) + + if src == nil { + return scanner.ScanBits(Bits{}) + } + + if len(src) < 4 { + return fmt.Errorf("invalid length for bit/varbit: %v", len(src)) + } + + bitLen := int32(binary.BigEndian.Uint32(src)) + rp := 4 + buf := make([]byte, len(src[rp:])) + copy(buf, src[rp:]) + + return scanner.ScanBits(Bits{Bytes: buf, Len: bitLen, Valid: true}) +} + +type scanPlanTextAnyToBitsScanner struct{} + +func (scanPlanTextAnyToBitsScanner) Scan(src []byte, dst any) error { + scanner := (dst).(BitsScanner) + + if src == nil { + return scanner.ScanBits(Bits{}) + } + + bitLen := len(src) + byteLen := bitLen / 8 + if bitLen%8 > 0 { + byteLen++ + } + buf := make([]byte, byteLen) + + for i, b := range src { + if b == '1' { + byteIdx := i / 8 + bitIdx := uint(i % 8) + buf[byteIdx] |= 128 >> bitIdx + } + } + + return scanner.ScanBits(Bits{Bytes: buf, Len: int32(bitLen), Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bool.go b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go new file mode 100644 index 0000000..077668e --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bool.go @@ -0,0 +1,346 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "encoding/json" + "fmt" + "strconv" + "strings" +) + +type BoolScanner interface { + ScanBool(v Bool) error +} + +type BoolValuer interface { + BoolValue() (Bool, error) +} + +type Bool struct { + Bool bool + Valid bool +} + +// ScanBool implements the [BoolScanner] interface. +func (b *Bool) ScanBool(v Bool) error { + *b = v + return nil +} + +// BoolValue implements the [BoolValuer] interface. +func (b Bool) BoolValue() (Bool, error) { + return b, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Bool) Scan(src any) error { + if src == nil { + *dst = Bool{} + return nil + } + + switch src := src.(type) { + case bool: + *dst = Bool{Bool: src, Valid: true} + return nil + case string: + b, err := strconv.ParseBool(src) + if err != nil { + return err + } + *dst = Bool{Bool: b, Valid: true} + return nil + case []byte: + b, err := strconv.ParseBool(string(src)) + if err != nil { + return err + } + *dst = Bool{Bool: b, Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Bool) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + return src.Bool, nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Bool) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + + if src.Bool { + return []byte("true"), nil + } else { + return []byte("false"), nil + } +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Bool) UnmarshalJSON(b []byte) error { + var v *bool + err := json.Unmarshal(b, &v) + if err != nil { + return err + } + + if v == nil { + *dst = Bool{} + } else { + *dst = Bool{Bool: *v, Valid: true} + } + + return nil +} + +type BoolCodec struct{} + +func (BoolCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (BoolCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (BoolCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case bool: + return encodePlanBoolCodecBinaryBool{} + case BoolValuer: + return encodePlanBoolCodecBinaryBoolValuer{} + } + case TextFormatCode: + switch value.(type) { + case bool: + return encodePlanBoolCodecTextBool{} + case BoolValuer: + return encodePlanBoolCodecTextBoolValuer{} + } + } + + return nil +} + +type encodePlanBoolCodecBinaryBool struct{} + +func (encodePlanBoolCodecBinaryBool) Encode(value any, buf []byte) (newBuf []byte, err error) { + v := value.(bool) + + if v { + buf = append(buf, 1) + } else { + buf = append(buf, 0) + } + + return buf, nil +} + +type encodePlanBoolCodecTextBoolValuer struct{} + +func (encodePlanBoolCodecTextBoolValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + b, err := value.(BoolValuer).BoolValue() + if err != nil { + return nil, err + } + + if !b.Valid { + return nil, nil + } + + if b.Bool { + buf = append(buf, 't') + } else { + buf = append(buf, 'f') + } + + return buf, nil +} + +type encodePlanBoolCodecBinaryBoolValuer struct{} + +func (encodePlanBoolCodecBinaryBoolValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + b, err := value.(BoolValuer).BoolValue() + if err != nil { + return nil, err + } + + if !b.Valid { + return nil, nil + } + + if b.Bool { + buf = append(buf, 1) + } else { + buf = append(buf, 0) + } + + return buf, nil +} + +type encodePlanBoolCodecTextBool struct{} + +func (encodePlanBoolCodecTextBool) Encode(value any, buf []byte) (newBuf []byte, err error) { + v := value.(bool) + + if v { + buf = append(buf, 't') + } else { + buf = append(buf, 'f') + } + + return buf, nil +} + +func (BoolCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *bool: + return scanPlanBinaryBoolToBool{} + case BoolScanner: + return scanPlanBinaryBoolToBoolScanner{} + } + case TextFormatCode: + switch target.(type) { + case *bool: + return scanPlanTextAnyToBool{} + case BoolScanner: + return scanPlanTextAnyToBoolScanner{} + } + } + + return nil +} + +func (c BoolCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return c.DecodeValue(m, oid, format, src) +} + +func (c BoolCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var b bool + err := codecScan(c, m, oid, format, src, &b) + if err != nil { + return nil, err + } + return b, nil +} + +type scanPlanBinaryBoolToBool struct{} + +func (scanPlanBinaryBoolToBool) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 1 { + return fmt.Errorf("invalid length for bool: %v", len(src)) + } + + p, ok := (dst).(*bool) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = src[0] == 1 + + return nil +} + +type scanPlanTextAnyToBool struct{} + +func (scanPlanTextAnyToBool) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) == 0 { + return fmt.Errorf("cannot scan empty string into %T", dst) + } + + p, ok := (dst).(*bool) + if !ok { + return ErrScanTargetTypeChanged + } + + v, err := planTextToBool(src) + if err != nil { + return err + } + + *p = v + + return nil +} + +type scanPlanBinaryBoolToBoolScanner struct{} + +func (scanPlanBinaryBoolToBoolScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(BoolScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanBool(Bool{}) + } + + if len(src) != 1 { + return fmt.Errorf("invalid length for bool: %v", len(src)) + } + + return s.ScanBool(Bool{Bool: src[0] == 1, Valid: true}) +} + +type scanPlanTextAnyToBoolScanner struct{} + +func (scanPlanTextAnyToBoolScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(BoolScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanBool(Bool{}) + } + + if len(src) == 0 { + return fmt.Errorf("cannot scan empty string into %T", dst) + } + + v, err := planTextToBool(src) + if err != nil { + return err + } + + return s.ScanBool(Bool{Bool: v, Valid: true}) +} + +// https://www.postgresql.org/docs/current/datatype-boolean.html +func planTextToBool(src []byte) (bool, error) { + s := string(bytes.ToLower(bytes.TrimSpace(src))) + + switch { + case strings.HasPrefix("true", s), strings.HasPrefix("yes", s), s == "on", s == "1": //nolint:gocritic // s is intentionally the prefix argument so partial inputs (t, tr, tru) also match. + return true, nil + case strings.HasPrefix("false", s), strings.HasPrefix("no", s), strings.HasPrefix("off", s), s == "0": //nolint:gocritic // s is intentionally the prefix argument so partial inputs (f, fa, fal) also match. + return false, nil + default: + return false, fmt.Errorf("unknown boolean string representation %q", src) + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/box.go b/vendor/github.com/jackc/pgx/v5/pgtype/box.go new file mode 100644 index 0000000..8270aaf --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/box.go @@ -0,0 +1,235 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type BoxScanner interface { + ScanBox(v Box) error +} + +type BoxValuer interface { + BoxValue() (Box, error) +} + +type Box struct { + P [2]Vec2 + Valid bool +} + +// ScanBox implements the [BoxScanner] interface. +func (b *Box) ScanBox(v Box) error { + *b = v + return nil +} + +// BoxValue implements the [BoxValuer] interface. +func (b Box) BoxValue() (Box, error) { + return b, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Box) Scan(src any) error { + if src == nil { + *dst = Box{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToBoxScanner{}.Scan([]byte(src), dst) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Box) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + buf, err := BoxCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type BoxCodec struct{} + +func (BoxCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (BoxCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (BoxCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(BoxValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanBoxCodecBinary{} + case TextFormatCode: + return encodePlanBoxCodecText{} + } + + return nil +} + +type encodePlanBoxCodecBinary struct{} + +func (encodePlanBoxCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + box, err := value.(BoxValuer).BoxValue() + if err != nil { + return nil, err + } + + if !box.Valid { + return nil, nil + } + + buf = pgio.AppendUint64(buf, math.Float64bits(box.P[0].X)) + buf = pgio.AppendUint64(buf, math.Float64bits(box.P[0].Y)) + buf = pgio.AppendUint64(buf, math.Float64bits(box.P[1].X)) + buf = pgio.AppendUint64(buf, math.Float64bits(box.P[1].Y)) + return buf, nil +} + +type encodePlanBoxCodecText struct{} + +func (encodePlanBoxCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + box, err := value.(BoxValuer).BoxValue() + if err != nil { + return nil, err + } + + if !box.Valid { + return nil, nil + } + + buf = append(buf, fmt.Sprintf(`(%s,%s),(%s,%s)`, + strconv.FormatFloat(box.P[0].X, 'f', -1, 64), + strconv.FormatFloat(box.P[0].Y, 'f', -1, 64), + strconv.FormatFloat(box.P[1].X, 'f', -1, 64), + strconv.FormatFloat(box.P[1].Y, 'f', -1, 64), + )...) + return buf, nil +} + +func (BoxCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(BoxScanner); ok { + return scanPlanBinaryBoxToBoxScanner{} + } + case TextFormatCode: + if _, ok := target.(BoxScanner); ok { + return scanPlanTextAnyToBoxScanner{} + } + } + + return nil +} + +type scanPlanBinaryBoxToBoxScanner struct{} + +func (scanPlanBinaryBoxToBoxScanner) Scan(src []byte, dst any) error { + scanner := (dst).(BoxScanner) + + if src == nil { + return scanner.ScanBox(Box{}) + } + + if len(src) != 32 { + return fmt.Errorf("invalid length for Box: %v", len(src)) + } + + x1 := binary.BigEndian.Uint64(src) + y1 := binary.BigEndian.Uint64(src[8:]) + x2 := binary.BigEndian.Uint64(src[16:]) + y2 := binary.BigEndian.Uint64(src[24:]) + + return scanner.ScanBox(Box{ + P: [2]Vec2{ + {math.Float64frombits(x1), math.Float64frombits(y1)}, + {math.Float64frombits(x2), math.Float64frombits(y2)}, + }, + Valid: true, + }) +} + +type scanPlanTextAnyToBoxScanner struct{} + +func (scanPlanTextAnyToBoxScanner) Scan(src []byte, dst any) error { + scanner := (dst).(BoxScanner) + + if src == nil { + return scanner.ScanBox(Box{}) + } + + if len(src) < 11 { + return fmt.Errorf("invalid length for Box: %v", len(src)) + } + + // Expected format: (x1,y1),(x2,y2) + sp1, sp2, found := strings.Cut(string(src[1:len(src)-1]), "),(") + if !found { + return fmt.Errorf("invalid format for Box") + } + + sx1, sy1, found := strings.Cut(sp1, ",") + if !found { + return fmt.Errorf("invalid format for Box") + } + sx2, sy2, found := strings.Cut(sp2, ",") + if !found { + return fmt.Errorf("invalid format for Box") + } + + x1, err := strconv.ParseFloat(sx1, 64) + if err != nil { + return err + } + y1, err := strconv.ParseFloat(sy1, 64) + if err != nil { + return err + } + x2, err := strconv.ParseFloat(sx2, 64) + if err != nil { + return err + } + y2, err := strconv.ParseFloat(sy2, 64) + if err != nil { + return err + } + + return scanner.ScanBox(Box{P: [2]Vec2{{x1, y1}, {x2, y2}}, Valid: true}) +} + +func (c BoxCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c BoxCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var box Box + err := codecScan(c, m, oid, format, src, &box) + if err != nil { + return nil, err + } + return box, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go new file mode 100644 index 0000000..a412763 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/builtin_wrappers.go @@ -0,0 +1,952 @@ +package pgtype + +import ( + "errors" + "fmt" + "math" + "math/big" + "net" + "net/netip" + "reflect" + "time" +) + +type int8Wrapper int8 + +func (w int8Wrapper) SkipUnderlyingTypePlan() {} + +func (w *int8Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *int8") + } + + if v.Int64 < math.MinInt8 { + return fmt.Errorf("%d is less than minimum value for int8", v.Int64) + } + if v.Int64 > math.MaxInt8 { + return fmt.Errorf("%d is greater than maximum value for int8", v.Int64) + } + *w = int8Wrapper(v.Int64) + + return nil +} + +func (w int8Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type int16Wrapper int16 + +func (w int16Wrapper) SkipUnderlyingTypePlan() {} + +func (w *int16Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *int16") + } + + if v.Int64 < math.MinInt16 { + return fmt.Errorf("%d is less than minimum value for int16", v.Int64) + } + if v.Int64 > math.MaxInt16 { + return fmt.Errorf("%d is greater than maximum value for int16", v.Int64) + } + *w = int16Wrapper(v.Int64) + + return nil +} + +func (w int16Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type int32Wrapper int32 + +func (w int32Wrapper) SkipUnderlyingTypePlan() {} + +func (w *int32Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *int32") + } + + if v.Int64 < math.MinInt32 { + return fmt.Errorf("%d is less than minimum value for int32", v.Int64) + } + if v.Int64 > math.MaxInt32 { + return fmt.Errorf("%d is greater than maximum value for int32", v.Int64) + } + *w = int32Wrapper(v.Int64) + + return nil +} + +func (w int32Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type int64Wrapper int64 + +func (w int64Wrapper) SkipUnderlyingTypePlan() {} + +func (w *int64Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *int64") + } + + *w = int64Wrapper(v.Int64) + + return nil +} + +func (w int64Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type intWrapper int + +func (w intWrapper) SkipUnderlyingTypePlan() {} + +func (w *intWrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *int") + } + + if v.Int64 < math.MinInt { + return fmt.Errorf("%d is less than minimum value for int", v.Int64) + } + if v.Int64 > math.MaxInt { + return fmt.Errorf("%d is greater than maximum value for int", v.Int64) + } + + *w = intWrapper(v.Int64) + + return nil +} + +func (w intWrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type uint8Wrapper uint8 + +func (w uint8Wrapper) SkipUnderlyingTypePlan() {} + +func (w *uint8Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint8") + } + + if v.Int64 < 0 { + return fmt.Errorf("%d is less than minimum value for uint8", v.Int64) + } + if v.Int64 > math.MaxUint8 { + return fmt.Errorf("%d is greater than maximum value for uint8", v.Int64) + } + *w = uint8Wrapper(v.Int64) + + return nil +} + +func (w uint8Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type uint16Wrapper uint16 + +func (w uint16Wrapper) SkipUnderlyingTypePlan() {} + +func (w *uint16Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint16") + } + + if v.Int64 < 0 { + return fmt.Errorf("%d is less than minimum value for uint16", v.Int64) + } + if v.Int64 > math.MaxUint16 { + return fmt.Errorf("%d is greater than maximum value for uint16", v.Int64) + } + *w = uint16Wrapper(v.Int64) + + return nil +} + +func (w uint16Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type uint32Wrapper uint32 + +func (w uint32Wrapper) SkipUnderlyingTypePlan() {} + +func (w *uint32Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint32") + } + + if v.Int64 < 0 { + return fmt.Errorf("%d is less than minimum value for uint32", v.Int64) + } + if v.Int64 > math.MaxUint32 { + return fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) + } + *w = uint32Wrapper(v.Int64) + + return nil +} + +func (w uint32Wrapper) Int64Value() (Int8, error) { + return Int8{Int64: int64(w), Valid: true}, nil +} + +type uint64Wrapper uint64 + +func (w uint64Wrapper) SkipUnderlyingTypePlan() {} + +func (w *uint64Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint64") + } + + if v.Int64 < 0 { + return fmt.Errorf("%d is less than minimum value for uint64", v.Int64) + } + + *w = uint64Wrapper(v.Int64) + + return nil +} + +func (w uint64Wrapper) Int64Value() (Int8, error) { + if uint64(w) > uint64(math.MaxInt64) { + return Int8{}, fmt.Errorf("%d is greater than maximum value for int64", w) + } + + return Int8{Int64: int64(w), Valid: true}, nil +} + +func (w *uint64Wrapper) ScanNumeric(v Numeric) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint64") + } + + bi, err := v.toBigInt() + if err != nil { + return fmt.Errorf("cannot scan into *uint64: %w", err) + } + + if !bi.IsUint64() { + return fmt.Errorf("cannot scan %v into *uint64", bi.String()) + } + + *w = uint64Wrapper(bi.Uint64()) + + return nil +} + +func (w uint64Wrapper) NumericValue() (Numeric, error) { + return Numeric{Int: new(big.Int).SetUint64(uint64(w)), Valid: true}, nil +} + +type uintWrapper uint + +func (w uintWrapper) SkipUnderlyingTypePlan() {} + +func (w *uintWrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint64") + } + + if v.Int64 < 0 { + return fmt.Errorf("%d is less than minimum value for uint64", v.Int64) + } + + if uint64(v.Int64) > math.MaxUint { + return fmt.Errorf("%d is greater than maximum value for uint", v.Int64) + } + + *w = uintWrapper(v.Int64) + + return nil +} + +func (w uintWrapper) Int64Value() (Int8, error) { + if uint64(w) > uint64(math.MaxInt64) { + return Int8{}, fmt.Errorf("%d is greater than maximum value for int64", w) + } + + return Int8{Int64: int64(w), Valid: true}, nil +} + +func (w *uintWrapper) ScanNumeric(v Numeric) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *uint") + } + + bi, err := v.toBigInt() + if err != nil { + return fmt.Errorf("cannot scan into *uint: %w", err) + } + + if !bi.IsUint64() { + return fmt.Errorf("cannot scan %v into *uint", bi.String()) + } + + ui := bi.Uint64() + + if math.MaxUint < ui { + return fmt.Errorf("cannot scan %v into *uint", ui) + } + + *w = uintWrapper(ui) + + return nil +} + +func (w uintWrapper) NumericValue() (Numeric, error) { + return Numeric{Int: new(big.Int).SetUint64(uint64(w)), Valid: true}, nil +} + +type float32Wrapper float32 + +func (w float32Wrapper) SkipUnderlyingTypePlan() {} + +func (w *float32Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *float32") + } + + *w = float32Wrapper(v.Int64) + + return nil +} + +func (w float32Wrapper) Int64Value() (Int8, error) { + if w > math.MaxInt64 { + return Int8{}, fmt.Errorf("%f is greater than maximum value for int64", w) + } + + return Int8{Int64: int64(w), Valid: true}, nil +} + +func (w *float32Wrapper) ScanFloat64(v Float8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *float32") + } + + *w = float32Wrapper(v.Float64) + + return nil +} + +func (w float32Wrapper) Float64Value() (Float8, error) { + return Float8{Float64: float64(w), Valid: true}, nil +} + +type float64Wrapper float64 + +func (w float64Wrapper) SkipUnderlyingTypePlan() {} + +func (w *float64Wrapper) ScanInt64(v Int8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *float64") + } + + *w = float64Wrapper(v.Int64) + + return nil +} + +func (w float64Wrapper) Int64Value() (Int8, error) { + if w > math.MaxInt64 { + return Int8{}, fmt.Errorf("%f is greater than maximum value for int64", w) + } + + return Int8{Int64: int64(w), Valid: true}, nil +} + +func (w *float64Wrapper) ScanFloat64(v Float8) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *float64") + } + + *w = float64Wrapper(v.Float64) + + return nil +} + +func (w float64Wrapper) Float64Value() (Float8, error) { + return Float8{Float64: float64(w), Valid: true}, nil +} + +type stringWrapper string + +func (w stringWrapper) SkipUnderlyingTypePlan() {} + +func (w *stringWrapper) ScanText(v Text) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *string") + } + + *w = stringWrapper(v.String) + return nil +} + +func (w stringWrapper) TextValue() (Text, error) { + return Text{String: string(w), Valid: true}, nil +} + +type timeWrapper time.Time + +func (w *timeWrapper) ScanDate(v Date) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Time") + } + + switch v.InfinityModifier { + case Finite: + *w = timeWrapper(v.Time) + return nil + case Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) + } +} + +func (w timeWrapper) DateValue() (Date, error) { + return Date{Time: time.Time(w), Valid: true}, nil +} + +func (w *timeWrapper) ScanTimestamp(v Timestamp) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Time") + } + + switch v.InfinityModifier { + case Finite: + *w = timeWrapper(v.Time) + return nil + case Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) + } +} + +func (w timeWrapper) TimestampValue() (Timestamp, error) { + return Timestamp{Time: time.Time(w), Valid: true}, nil +} + +func (w *timeWrapper) ScanTimestamptz(v Timestamptz) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Time") + } + + switch v.InfinityModifier { + case Finite: + *w = timeWrapper(v.Time) + return nil + case Infinity: + return fmt.Errorf("cannot scan Infinity into *time.Time") + case NegativeInfinity: + return fmt.Errorf("cannot scan -Infinity into *time.Time") + default: + return fmt.Errorf("invalid InfinityModifier: %v", v.InfinityModifier) + } +} + +func (w timeWrapper) TimestamptzValue() (Timestamptz, error) { + return Timestamptz{Time: time.Time(w), Valid: true}, nil +} + +func (w *timeWrapper) ScanTime(v Time) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Time") + } + + // 24:00:00 is max allowed time in PostgreSQL, but time.Time will normalize that to 00:00:00 the next day. + var maxRepresentableByTime int64 = 24*60*60*1000000 - 1 + if v.Microseconds > maxRepresentableByTime { + return fmt.Errorf("%d microseconds cannot be represented as time.Time", v.Microseconds) + } + + usec := v.Microseconds + hours := usec / microsecondsPerHour + usec -= hours * microsecondsPerHour + minutes := usec / microsecondsPerMinute + usec -= minutes * microsecondsPerMinute + seconds := usec / microsecondsPerSecond + usec -= seconds * microsecondsPerSecond + ns := usec * 1000 + *w = timeWrapper(time.Date(2000, 1, 1, int(hours), int(minutes), int(seconds), int(ns), time.UTC)) + return nil +} + +func (w timeWrapper) TimeValue() (Time, error) { + t := time.Time(w) + usec := int64(t.Hour())*microsecondsPerHour + + int64(t.Minute())*microsecondsPerMinute + + int64(t.Second())*microsecondsPerSecond + + int64(t.Nanosecond())/1000 + return Time{Microseconds: usec, Valid: true}, nil +} + +type durationWrapper time.Duration + +func (w durationWrapper) SkipUnderlyingTypePlan() {} + +func (w *durationWrapper) ScanInterval(v Interval) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *time.Interval") + } + + us := int64(v.Months)*microsecondsPerMonth + int64(v.Days)*microsecondsPerDay + v.Microseconds + *w = durationWrapper(time.Duration(us) * time.Microsecond) + return nil +} + +func (w durationWrapper) IntervalValue() (Interval, error) { + return Interval{Microseconds: int64(w) / 1000, Valid: true}, nil +} + +type netIPNetWrapper net.IPNet + +func (w *netIPNetWrapper) ScanNetipPrefix(v netip.Prefix) error { + if !v.IsValid() { + return fmt.Errorf("cannot scan NULL into *net.IPNet") + } + + *w = netIPNetWrapper{ + IP: v.Addr().AsSlice(), + Mask: net.CIDRMask(v.Bits(), v.Addr().BitLen()), + } + + return nil +} + +func (w netIPNetWrapper) NetipPrefixValue() (netip.Prefix, error) { + ip, ok := netip.AddrFromSlice(w.IP) + if !ok { + return netip.Prefix{}, errors.New("invalid net.IPNet") + } + + ones, _ := w.Mask.Size() + + return netip.PrefixFrom(ip, ones), nil +} + +type netIPWrapper net.IP + +func (w netIPWrapper) SkipUnderlyingTypePlan() {} + +func (w *netIPWrapper) ScanNetipPrefix(v netip.Prefix) error { + if !v.IsValid() { + *w = nil + return nil + } + + if v.Addr().BitLen() != v.Bits() { + return fmt.Errorf("cannot scan %v to *net.IP", v) + } + + *w = netIPWrapper(v.Addr().AsSlice()) + return nil +} + +func (w netIPWrapper) NetipPrefixValue() (netip.Prefix, error) { + if w == nil { + return netip.Prefix{}, nil + } + + addr, ok := netip.AddrFromSlice([]byte(w)) + if !ok { + return netip.Prefix{}, errors.New("invalid net.IP") + } + + return netip.PrefixFrom(addr, addr.BitLen()), nil +} + +type netipPrefixWrapper netip.Prefix + +func (w *netipPrefixWrapper) ScanNetipPrefix(v netip.Prefix) error { + *w = netipPrefixWrapper(v) + return nil +} + +func (w netipPrefixWrapper) NetipPrefixValue() (netip.Prefix, error) { + return netip.Prefix(w), nil +} + +type netipAddrWrapper netip.Addr + +func (w *netipAddrWrapper) ScanNetipPrefix(v netip.Prefix) error { + if !v.IsValid() { + *w = netipAddrWrapper(netip.Addr{}) + return nil + } + + if v.Addr().BitLen() != v.Bits() { + return fmt.Errorf("cannot scan %v to netip.Addr", v) + } + + *w = netipAddrWrapper(v.Addr()) + + return nil +} + +func (w netipAddrWrapper) NetipPrefixValue() (netip.Prefix, error) { + addr := (netip.Addr)(w) + if !addr.IsValid() { + return netip.Prefix{}, nil + } + + return netip.PrefixFrom(addr, addr.BitLen()), nil +} + +type mapStringToPointerStringWrapper map[string]*string + +func (w *mapStringToPointerStringWrapper) ScanHstore(v Hstore) error { + *w = mapStringToPointerStringWrapper(v) + return nil +} + +func (w mapStringToPointerStringWrapper) HstoreValue() (Hstore, error) { + return Hstore(w), nil +} + +type mapStringToStringWrapper map[string]string + +func (w *mapStringToStringWrapper) ScanHstore(v Hstore) error { + *w = make(mapStringToStringWrapper, len(v)) + for k, v := range v { + if v == nil { + return fmt.Errorf("cannot scan NULL to string") + } + (*w)[k] = *v + } + return nil +} + +func (w mapStringToStringWrapper) HstoreValue() (Hstore, error) { + if w == nil { + return nil, nil + } + + hstore := make(Hstore, len(w)) + for k, v := range w { + s := v + hstore[k] = &s + } + return hstore, nil +} + +type fmtStringerWrapper struct { + s fmt.Stringer +} + +func (w fmtStringerWrapper) TextValue() (Text, error) { + return Text{String: w.s.String(), Valid: true}, nil +} + +type byte16Wrapper [16]byte + +func (w *byte16Wrapper) ScanUUID(v UUID) error { + if !v.Valid { + return fmt.Errorf("cannot scan NULL into *[16]byte") + } + *w = byte16Wrapper(v.Bytes) + return nil +} + +func (w byte16Wrapper) UUIDValue() (UUID, error) { + return UUID{Bytes: [16]byte(w), Valid: true}, nil +} + +type byteSliceWrapper []byte + +func (w byteSliceWrapper) SkipUnderlyingTypePlan() {} + +func (w *byteSliceWrapper) ScanText(v Text) error { + if !v.Valid { + *w = nil + return nil + } + + *w = byteSliceWrapper(v.String) + return nil +} + +func (w byteSliceWrapper) TextValue() (Text, error) { + if w == nil { + return Text{}, nil + } + + return Text{String: string(w), Valid: true}, nil +} + +func (w *byteSliceWrapper) ScanUUID(v UUID) error { + if !v.Valid { + *w = nil + return nil + } + *w = make(byteSliceWrapper, 16) + copy(*w, v.Bytes[:]) + return nil +} + +func (w byteSliceWrapper) UUIDValue() (UUID, error) { + if w == nil { + return UUID{}, nil + } + + uuid := UUID{Valid: true} + copy(uuid.Bytes[:], w) + return uuid, nil +} + +// structWrapper implements CompositeIndexGetter for a struct. +type structWrapper struct { + s any + exportedFields []reflect.Value +} + +func (w structWrapper) IsNull() bool { + return w.s == nil +} + +func (w structWrapper) Index(i int) any { + if i >= len(w.exportedFields) { + return fmt.Errorf("%#v only has %d public fields - %d is out of bounds", w.s, len(w.exportedFields), i) + } + + return w.exportedFields[i].Interface() +} + +// ptrStructWrapper implements CompositeIndexScanner for a pointer to a struct. +type ptrStructWrapper struct { + s any + exportedFields []reflect.Value +} + +func (w *ptrStructWrapper) ScanNull() error { + return fmt.Errorf("cannot scan NULL into %#v", w.s) +} + +func (w *ptrStructWrapper) ScanIndex(i int) any { + if i >= len(w.exportedFields) { + return fmt.Errorf("%#v only has %d public fields - %d is out of bounds", w.s, len(w.exportedFields), i) + } + + return w.exportedFields[i].Addr().Interface() +} + +type anySliceArrayReflect struct { + slice reflect.Value +} + +func (a anySliceArrayReflect) Dimensions() []ArrayDimension { + if a.slice.IsNil() { + return nil + } + + return []ArrayDimension{{Length: int32(a.slice.Len()), LowerBound: 1}} +} + +func (a anySliceArrayReflect) Index(i int) any { + return a.slice.Index(i).Interface() +} + +func (a anySliceArrayReflect) IndexType() any { + return reflect.New(a.slice.Type().Elem()).Elem().Interface() +} + +func (a *anySliceArrayReflect) SetDimensions(dimensions []ArrayDimension) error { + sliceType := a.slice.Type() + + if dimensions == nil { + a.slice.Set(reflect.Zero(sliceType)) + return nil + } + + elementCount := cardinality(dimensions) + slice := reflect.MakeSlice(sliceType, elementCount, elementCount) + a.slice.Set(slice) + return nil +} + +func (a *anySliceArrayReflect) ScanIndex(i int) any { + return a.slice.Index(i).Addr().Interface() +} + +func (a *anySliceArrayReflect) ScanIndexType() any { + return reflect.New(a.slice.Type().Elem()).Interface() +} + +type anyMultiDimSliceArray struct { + slice reflect.Value + dims []ArrayDimension +} + +func (a *anyMultiDimSliceArray) Dimensions() []ArrayDimension { + if a.slice.IsNil() { + return nil + } + + s := a.slice + for { + a.dims = append(a.dims, ArrayDimension{Length: int32(s.Len()), LowerBound: 1}) + if s.Len() > 0 { + s = s.Index(0) + } else { + break + } + if s.Type().Kind() == reflect.Slice { + } else { + break + } + } + + return a.dims +} + +func (a *anyMultiDimSliceArray) Index(i int) any { + if len(a.dims) == 1 { + return a.slice.Index(i).Interface() + } + + indexes := make([]int, len(a.dims)) + for j := len(a.dims) - 1; j >= 0; j-- { + dimLen := int(a.dims[j].Length) + indexes[j] = i % dimLen + i /= dimLen + } + + v := a.slice + for _, si := range indexes { + v = v.Index(si) + } + + return v.Interface() +} + +func (a *anyMultiDimSliceArray) IndexType() any { + lowestSliceType := a.slice.Type() + for ; lowestSliceType.Elem().Kind() == reflect.Slice; lowestSliceType = lowestSliceType.Elem() { + } + return reflect.New(lowestSliceType.Elem()).Elem().Interface() +} + +func (a *anyMultiDimSliceArray) SetDimensions(dimensions []ArrayDimension) error { + sliceType := a.slice.Type() + + if dimensions == nil { + a.slice.Set(reflect.Zero(sliceType)) + return nil + } + + switch len(dimensions) { + case 0: + // Empty, but non-nil array + slice := reflect.MakeSlice(sliceType, 0, 0) + a.slice.Set(slice) + return nil + case 1: + elementCount := cardinality(dimensions) + slice := reflect.MakeSlice(sliceType, elementCount, elementCount) + a.slice.Set(slice) + return nil + default: + sliceDimensionCount := 1 + lowestSliceType := sliceType + for ; lowestSliceType.Elem().Kind() == reflect.Slice; lowestSliceType = lowestSliceType.Elem() { + sliceDimensionCount++ + } + + if sliceDimensionCount != len(dimensions) { + return fmt.Errorf("PostgreSQL array has %d dimensions but slice has %d dimensions", len(dimensions), sliceDimensionCount) + } + + elementCount := cardinality(dimensions) + flatSlice := reflect.MakeSlice(lowestSliceType, elementCount, elementCount) + + multiDimSlice := a.makeMultidimensionalSlice(sliceType, dimensions, flatSlice, 0) + a.slice.Set(multiDimSlice) + + // Now that a.slice is a multi-dimensional slice with the underlying data pointed at flatSlice change a.slice to + // flatSlice so ScanIndex only has to handle simple one dimensional slices. + a.slice = flatSlice + + return nil + } +} + +func (a *anyMultiDimSliceArray) makeMultidimensionalSlice(sliceType reflect.Type, dimensions []ArrayDimension, flatSlice reflect.Value, flatSliceIdx int) reflect.Value { + if len(dimensions) == 1 { + endIdx := flatSliceIdx + int(dimensions[0].Length) + return flatSlice.Slice3(flatSliceIdx, endIdx, endIdx) + } + + sliceLen := int(dimensions[0].Length) + slice := reflect.MakeSlice(sliceType, sliceLen, sliceLen) + for i := range sliceLen { + subSlice := a.makeMultidimensionalSlice(sliceType.Elem(), dimensions[1:], flatSlice, flatSliceIdx+(i*int(dimensions[1].Length))) + slice.Index(i).Set(subSlice) + } + + return slice +} + +func (a *anyMultiDimSliceArray) ScanIndex(i int) any { + return a.slice.Index(i).Addr().Interface() +} + +func (a *anyMultiDimSliceArray) ScanIndexType() any { + lowestSliceType := a.slice.Type() + for ; lowestSliceType.Elem().Kind() == reflect.Slice; lowestSliceType = lowestSliceType.Elem() { + } + return reflect.New(lowestSliceType.Elem()).Interface() +} + +type anyArrayArrayReflect struct { + array reflect.Value +} + +func (a anyArrayArrayReflect) Dimensions() []ArrayDimension { + return []ArrayDimension{{Length: int32(a.array.Len()), LowerBound: 1}} +} + +func (a anyArrayArrayReflect) Index(i int) any { + return a.array.Index(i).Interface() +} + +func (a anyArrayArrayReflect) IndexType() any { + return reflect.New(a.array.Type().Elem()).Elem().Interface() +} + +func (a *anyArrayArrayReflect) SetDimensions(dimensions []ArrayDimension) error { + if dimensions == nil { + return fmt.Errorf("anyArrayArrayReflect: cannot scan NULL into %v", a.array.Type().String()) + } + + if len(dimensions) != 1 { + return fmt.Errorf("anyArrayArrayReflect: cannot scan multi-dimensional array into %v", a.array.Type().String()) + } + + if int(dimensions[0].Length) != a.array.Len() { + return fmt.Errorf("anyArrayArrayReflect: cannot scan array with length %v into %v", dimensions[0].Length, a.array.Type().String()) + } + + return nil +} + +func (a *anyArrayArrayReflect) ScanIndex(i int) any { + return a.array.Index(i).Addr().Interface() +} + +func (a *anyArrayArrayReflect) ScanIndexType() any { + return reflect.New(a.array.Type().Elem()).Interface() +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go new file mode 100644 index 0000000..6c4f0c5 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/bytea.go @@ -0,0 +1,254 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/hex" + "fmt" +) + +type BytesScanner interface { + // ScanBytes receives a byte slice of driver memory that is only valid until the next database method call. + ScanBytes(v []byte) error +} + +type BytesValuer interface { + // BytesValue returns a byte slice of the byte data. The caller must not change the returned slice. + BytesValue() ([]byte, error) +} + +// DriverBytes is a byte slice that holds a reference to memory owned by the driver. It is only valid from the time it +// is scanned until Rows.Next or Rows.Close is called. It is never safe to use DriverBytes with QueryRow as Row.Scan +// internally calls Rows.Close before returning. +type DriverBytes []byte + +func (b *DriverBytes) ScanBytes(v []byte) error { + *b = v + return nil +} + +// PreallocBytes is a byte slice of preallocated memory that scanned bytes will be copied to. If it is too small a new +// slice will be allocated. +type PreallocBytes []byte + +func (b *PreallocBytes) ScanBytes(v []byte) error { + if v == nil { + *b = nil + return nil + } + + if len(v) <= len(*b) { + *b = (*b)[:len(v)] + } else { + *b = make(PreallocBytes, len(v)) + } + copy(*b, v) + return nil +} + +// UndecodedBytes can be used as a scan target to get the raw bytes from PostgreSQL without any decoding. +type UndecodedBytes []byte + +type scanPlanAnyToUndecodedBytes struct{} + +func (scanPlanAnyToUndecodedBytes) Scan(src []byte, dst any) error { + dstBuf := dst.(*UndecodedBytes) + if src == nil { + *dstBuf = nil + return nil + } + + *dstBuf = make([]byte, len(src)) + copy(*dstBuf, src) + return nil +} + +type ByteaCodec struct{} + +func (ByteaCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (ByteaCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (ByteaCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case []byte: + return encodePlanBytesCodecBinaryBytes{} + case BytesValuer: + return encodePlanBytesCodecBinaryBytesValuer{} + } + case TextFormatCode: + switch value.(type) { + case []byte: + return encodePlanBytesCodecTextBytes{} + case BytesValuer: + return encodePlanBytesCodecTextBytesValuer{} + } + } + + return nil +} + +type encodePlanBytesCodecBinaryBytes struct{} + +func (encodePlanBytesCodecBinaryBytes) Encode(value any, buf []byte) (newBuf []byte, err error) { + b := value.([]byte) + if b == nil { + return nil, nil + } + + return append(buf, b...), nil +} + +type encodePlanBytesCodecBinaryBytesValuer struct{} + +func (encodePlanBytesCodecBinaryBytesValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + b, err := value.(BytesValuer).BytesValue() + if err != nil { + return nil, err + } + if b == nil { + return nil, nil + } + + return append(buf, b...), nil +} + +type encodePlanBytesCodecTextBytes struct{} + +func (encodePlanBytesCodecTextBytes) Encode(value any, buf []byte) (newBuf []byte, err error) { + b := value.([]byte) + if b == nil { + return nil, nil + } + + buf = append(buf, `\x`...) + buf = append(buf, hex.EncodeToString(b)...) + return buf, nil +} + +type encodePlanBytesCodecTextBytesValuer struct{} + +func (encodePlanBytesCodecTextBytesValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + b, err := value.(BytesValuer).BytesValue() + if err != nil { + return nil, err + } + if b == nil { + return nil, nil + } + + buf = append(buf, `\x`...) + buf = append(buf, hex.EncodeToString(b)...) + return buf, nil +} + +func (ByteaCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *[]byte: + return scanPlanBinaryBytesToBytes{} + case BytesScanner: + return scanPlanBinaryBytesToBytesScanner{} + } + case TextFormatCode: + switch target.(type) { + case *[]byte: + return scanPlanTextByteaToBytes{} + case BytesScanner: + return scanPlanTextByteaToBytesScanner{} + } + } + + return nil +} + +type scanPlanBinaryBytesToBytes struct{} + +func (scanPlanBinaryBytesToBytes) Scan(src []byte, dst any) error { + dstBuf := dst.(*[]byte) + if src == nil { + *dstBuf = nil + return nil + } + + *dstBuf = make([]byte, len(src)) + copy(*dstBuf, src) + return nil +} + +type scanPlanBinaryBytesToBytesScanner struct{} + +func (scanPlanBinaryBytesToBytesScanner) Scan(src []byte, dst any) error { + scanner := (dst).(BytesScanner) + return scanner.ScanBytes(src) +} + +type scanPlanTextByteaToBytes struct{} + +func (scanPlanTextByteaToBytes) Scan(src []byte, dst any) error { + dstBuf := dst.(*[]byte) + if src == nil { + *dstBuf = nil + return nil + } + + buf, err := decodeHexBytea(src) + if err != nil { + return err + } + *dstBuf = buf + + return nil +} + +type scanPlanTextByteaToBytesScanner struct{} + +func (scanPlanTextByteaToBytesScanner) Scan(src []byte, dst any) error { + scanner := (dst).(BytesScanner) + buf, err := decodeHexBytea(src) + if err != nil { + return err + } + return scanner.ScanBytes(buf) +} + +func decodeHexBytea(src []byte) ([]byte, error) { + if src == nil { + return nil, nil + } + + if len(src) < 2 || src[0] != '\\' || src[1] != 'x' { + return nil, fmt.Errorf("invalid hex format") + } + + buf := make([]byte, (len(src)-2)/2) + _, err := hex.Decode(buf, src[2:]) + if err != nil { + return nil, err + } + + return buf, nil +} + +func (c ByteaCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return c.DecodeValue(m, oid, format, src) +} + +func (c ByteaCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var buf []byte + err := codecScan(c, m, oid, format, src, &buf) + if err != nil { + return nil, err + } + return buf, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/circle.go b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go new file mode 100644 index 0000000..ea1d629 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/circle.go @@ -0,0 +1,231 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type CircleScanner interface { + ScanCircle(v Circle) error +} + +type CircleValuer interface { + CircleValue() (Circle, error) +} + +type Circle struct { + P Vec2 + R float64 + Valid bool +} + +// ScanCircle implements the [CircleScanner] interface. +func (c *Circle) ScanCircle(v Circle) error { + *c = v + return nil +} + +// CircleValue implements the [CircleValuer] interface. +func (c Circle) CircleValue() (Circle, error) { + return c, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Circle) Scan(src any) error { + if src == nil { + *dst = Circle{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToCircleScanner{}.Scan([]byte(src), dst) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Circle) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + buf, err := CircleCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type CircleCodec struct{} + +func (CircleCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (CircleCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (CircleCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(CircleValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanCircleCodecBinary{} + case TextFormatCode: + return encodePlanCircleCodecText{} + } + + return nil +} + +type encodePlanCircleCodecBinary struct{} + +func (encodePlanCircleCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + circle, err := value.(CircleValuer).CircleValue() + if err != nil { + return nil, err + } + + if !circle.Valid { + return nil, nil + } + + buf = pgio.AppendUint64(buf, math.Float64bits(circle.P.X)) + buf = pgio.AppendUint64(buf, math.Float64bits(circle.P.Y)) + buf = pgio.AppendUint64(buf, math.Float64bits(circle.R)) + return buf, nil +} + +type encodePlanCircleCodecText struct{} + +func (encodePlanCircleCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + circle, err := value.(CircleValuer).CircleValue() + if err != nil { + return nil, err + } + + if !circle.Valid { + return nil, nil + } + + buf = append(buf, fmt.Sprintf(`<(%s,%s),%s>`, + strconv.FormatFloat(circle.P.X, 'f', -1, 64), + strconv.FormatFloat(circle.P.Y, 'f', -1, 64), + strconv.FormatFloat(circle.R, 'f', -1, 64), + )...) + return buf, nil +} + +func (CircleCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(CircleScanner); ok { + return scanPlanBinaryCircleToCircleScanner{} + } + case TextFormatCode: + if _, ok := target.(CircleScanner); ok { + return scanPlanTextAnyToCircleScanner{} + } + } + + return nil +} + +func (c CircleCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c CircleCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var circle Circle + err := codecScan(c, m, oid, format, src, &circle) + if err != nil { + return nil, err + } + return circle, nil +} + +type scanPlanBinaryCircleToCircleScanner struct{} + +func (scanPlanBinaryCircleToCircleScanner) Scan(src []byte, dst any) error { + scanner := (dst).(CircleScanner) + + if src == nil { + return scanner.ScanCircle(Circle{}) + } + + if len(src) != 24 { + return fmt.Errorf("invalid length for Circle: %v", len(src)) + } + + x := binary.BigEndian.Uint64(src) + y := binary.BigEndian.Uint64(src[8:]) + r := binary.BigEndian.Uint64(src[16:]) + + return scanner.ScanCircle(Circle{ + P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, + R: math.Float64frombits(r), + Valid: true, + }) +} + +type scanPlanTextAnyToCircleScanner struct{} + +func (scanPlanTextAnyToCircleScanner) Scan(src []byte, dst any) error { + scanner := (dst).(CircleScanner) + + if src == nil { + return scanner.ScanCircle(Circle{}) + } + + if len(src) < 9 { + return fmt.Errorf("invalid length for Circle: %v", len(src)) + } + + // Expected format: <(x,y),r> + str, ok := strings.CutPrefix(string(src), "<(") + if !ok { + return fmt.Errorf("invalid format for Circle") + } + str, ok = strings.CutSuffix(str, ">") + if !ok { + return fmt.Errorf("invalid format for Circle") + } + + sx, str, found := strings.Cut(str, ",") + if !found { + return fmt.Errorf("invalid format for Circle") + } + sy, sr, found := strings.Cut(str, "),") + if !found { + return fmt.Errorf("invalid format for Circle") + } + + x, err := strconv.ParseFloat(sx, 64) + if err != nil { + return err + } + y, err := strconv.ParseFloat(sy, 64) + if err != nil { + return err + } + r, err := strconv.ParseFloat(sr, 64) + if err != nil { + return err + } + + return scanner.ScanCircle(Circle{P: Vec2{x, y}, R: r, Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/composite.go b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go new file mode 100644 index 0000000..7f96ab4 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/composite.go @@ -0,0 +1,613 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "errors" + "fmt" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// CompositeIndexGetter is a type accessed by index that can be converted into a PostgreSQL composite. +type CompositeIndexGetter interface { + // IsNull returns true if the value is SQL NULL. + IsNull() bool + + // Index returns the element at i. + Index(i int) any +} + +// CompositeIndexScanner is a type accessed by index that can be scanned from a PostgreSQL composite. +type CompositeIndexScanner interface { + // ScanNull sets the value to SQL NULL. + ScanNull() error + + // ScanIndex returns a value usable as a scan target for i. + ScanIndex(i int) any +} + +type CompositeCodecField struct { + Name string + Type *Type +} + +type CompositeCodec struct { + Fields []CompositeCodecField +} + +func (c *CompositeCodec) FormatSupported(format int16) bool { + for _, f := range c.Fields { + if !f.Type.Codec.FormatSupported(format) { + return false + } + } + + return true +} + +func (c *CompositeCodec) PreferredFormat() int16 { + if c.FormatSupported(BinaryFormatCode) { + return BinaryFormatCode + } + return TextFormatCode +} + +func (c *CompositeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(CompositeIndexGetter); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return &encodePlanCompositeCodecCompositeIndexGetterToBinary{cc: c, m: m} + case TextFormatCode: + return &encodePlanCompositeCodecCompositeIndexGetterToText{cc: c, m: m} + } + + return nil +} + +type encodePlanCompositeCodecCompositeIndexGetterToBinary struct { + cc *CompositeCodec + m *Map +} + +func (plan *encodePlanCompositeCodecCompositeIndexGetterToBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + getter := value.(CompositeIndexGetter) + + if getter.IsNull() { + return nil, nil + } + + builder := NewCompositeBinaryBuilder(plan.m, buf) + for i, field := range plan.cc.Fields { + builder.AppendValue(field.Type.OID, getter.Index(i)) + } + + return builder.Finish() +} + +type encodePlanCompositeCodecCompositeIndexGetterToText struct { + cc *CompositeCodec + m *Map +} + +func (plan *encodePlanCompositeCodecCompositeIndexGetterToText) Encode(value any, buf []byte) (newBuf []byte, err error) { + getter := value.(CompositeIndexGetter) + + if getter.IsNull() { + return nil, nil + } + + b := NewCompositeTextBuilder(plan.m, buf) + for i, field := range plan.cc.Fields { + b.AppendValue(field.Type.OID, getter.Index(i)) + } + + return b.Finish() +} + +func (c *CompositeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(CompositeIndexScanner); ok { + return &scanPlanBinaryCompositeToCompositeIndexScanner{cc: c, m: m} + } + case TextFormatCode: + if _, ok := target.(CompositeIndexScanner); ok { + return &scanPlanTextCompositeToCompositeIndexScanner{cc: c, m: m} + } + } + + return nil +} + +type scanPlanBinaryCompositeToCompositeIndexScanner struct { + cc *CompositeCodec + m *Map +} + +func (plan *scanPlanBinaryCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { + targetScanner := (target).(CompositeIndexScanner) + + if src == nil { + return targetScanner.ScanNull() + } + + scanner := NewCompositeBinaryScanner(plan.m, src) + for i, field := range plan.cc.Fields { + if scanner.Next() { + fieldTarget := targetScanner.ScanIndex(i) + if fieldTarget != nil { + fieldPlan := plan.m.PlanScan(field.Type.OID, BinaryFormatCode, fieldTarget) + if fieldPlan == nil { + return fmt.Errorf("unable to encode %v into OID %d in binary format", field, field.Type.OID) + } + + err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + if err != nil { + return err + } + } + } else { + return errors.New("read past end of composite") + } + } + + if err := scanner.Err(); err != nil { + return err + } + + return nil +} + +type scanPlanTextCompositeToCompositeIndexScanner struct { + cc *CompositeCodec + m *Map +} + +func (plan *scanPlanTextCompositeToCompositeIndexScanner) Scan(src []byte, target any) error { + targetScanner := (target).(CompositeIndexScanner) + + if src == nil { + return targetScanner.ScanNull() + } + + scanner := NewCompositeTextScanner(plan.m, src) + for i, field := range plan.cc.Fields { + if scanner.Next() { + fieldTarget := targetScanner.ScanIndex(i) + if fieldTarget != nil { + fieldPlan := plan.m.PlanScan(field.Type.OID, TextFormatCode, fieldTarget) + if fieldPlan == nil { + return fmt.Errorf("unable to encode %v into OID %d in text format", field, field.Type.OID) + } + + err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + if err != nil { + return err + } + } + } else { + return errors.New("read past end of composite") + } + } + + if err := scanner.Err(); err != nil { + return err + } + + return nil +} + +func (c *CompositeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + return string(src), nil + case BinaryFormatCode: + buf := make([]byte, len(src)) + copy(buf, src) + return buf, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} + +func (c *CompositeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + scanner := NewCompositeTextScanner(m, src) + values := make(map[string]any, len(c.Fields)) + for i := 0; scanner.Next() && i < len(c.Fields); i++ { + var v any + fieldPlan := m.PlanScan(c.Fields[i].Type.OID, TextFormatCode, &v) + if fieldPlan == nil { + return nil, fmt.Errorf("unable to scan OID %d in text format into %v", c.Fields[i].Type.OID, v) + } + + err := fieldPlan.Scan(scanner.Bytes(), &v) + if err != nil { + return nil, err + } + + values[c.Fields[i].Name] = v + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + return values, nil + case BinaryFormatCode: + scanner := NewCompositeBinaryScanner(m, src) + values := make(map[string]any, len(c.Fields)) + for i := 0; scanner.Next() && i < len(c.Fields); i++ { + var v any + fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v) + if fieldPlan == nil { + return nil, fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), v) + } + + err := fieldPlan.Scan(scanner.Bytes(), &v) + if err != nil { + return nil, err + } + + values[c.Fields[i].Name] = v + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + return values, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} + +type CompositeBinaryScanner struct { + m *Map + rp int + src []byte + + fieldCount int32 + fieldBytes []byte + fieldOID uint32 + err error +} + +// NewCompositeBinaryScanner a scanner over a binary encoded composite value. +func NewCompositeBinaryScanner(m *Map, src []byte) *CompositeBinaryScanner { + rp := 0 + if len(src[rp:]) < 4 { + return &CompositeBinaryScanner{err: fmt.Errorf("Record incomplete %v", src)} + } + + fieldCount := int32(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + + return &CompositeBinaryScanner{ + m: m, + rp: rp, + src: src, + fieldCount: fieldCount, + } +} + +// Next advances the scanner to the next field. It returns false after the last field is read or an error occurs. After +// Next returns false, the Err method can be called to check if any errors occurred. +func (cfs *CompositeBinaryScanner) Next() bool { + if cfs.err != nil { + return false + } + + if cfs.rp == len(cfs.src) { + return false + } + + if len(cfs.src[cfs.rp:]) < 8 { + cfs.err = fmt.Errorf("Record incomplete %v", cfs.src) + return false + } + cfs.fieldOID = binary.BigEndian.Uint32(cfs.src[cfs.rp:]) + cfs.rp += 4 + + fieldLen := int(int32(binary.BigEndian.Uint32(cfs.src[cfs.rp:]))) + cfs.rp += 4 + + if fieldLen >= 0 { + if len(cfs.src[cfs.rp:]) < fieldLen { + cfs.err = fmt.Errorf("Record incomplete rp=%d src=%v", cfs.rp, cfs.src) + return false + } + cfs.fieldBytes = cfs.src[cfs.rp : cfs.rp+fieldLen] + cfs.rp += fieldLen + } else { + cfs.fieldBytes = nil + } + + return true +} + +func (cfs *CompositeBinaryScanner) FieldCount() int { + return int(cfs.fieldCount) +} + +// Bytes returns the bytes of the field most recently read by Scan(). +func (cfs *CompositeBinaryScanner) Bytes() []byte { + return cfs.fieldBytes +} + +// OID returns the OID of the field most recently read by Scan(). +func (cfs *CompositeBinaryScanner) OID() uint32 { + return cfs.fieldOID +} + +// Err returns any error encountered by the scanner. +func (cfs *CompositeBinaryScanner) Err() error { + return cfs.err +} + +type CompositeTextScanner struct { + m *Map + rp int + src []byte + + fieldBytes []byte + err error +} + +// NewCompositeTextScanner a scanner over a text encoded composite value. +func NewCompositeTextScanner(m *Map, src []byte) *CompositeTextScanner { + if len(src) < 2 { + return &CompositeTextScanner{err: fmt.Errorf("Record incomplete %v", src)} + } + + if src[0] != '(' { + return &CompositeTextScanner{err: fmt.Errorf("composite text format must start with '('")} + } + + if src[len(src)-1] != ')' { + return &CompositeTextScanner{err: fmt.Errorf("composite text format must end with ')'")} + } + + return &CompositeTextScanner{ + m: m, + rp: 1, + src: src, + } +} + +// Next advances the scanner to the next field. It returns false after the last field is read or an error occurs. After +// Next returns false, the Err method can be called to check if any errors occurred. +func (cfs *CompositeTextScanner) Next() bool { + if cfs.err != nil { + return false + } + + if cfs.rp == len(cfs.src) { + return false + } + + switch cfs.src[cfs.rp] { + case ',', ')': // null + cfs.rp++ + cfs.fieldBytes = nil + return true + case '"': // quoted value + cfs.rp++ + cfs.fieldBytes = make([]byte, 0, 16) + quotedValue: + for { + ch := cfs.src[cfs.rp] + + switch ch { + case '"': + cfs.rp++ + if cfs.src[cfs.rp] == '"' { + cfs.fieldBytes = append(cfs.fieldBytes, '"') + cfs.rp++ + } else { + break quotedValue + } + case '\\': + cfs.rp++ + cfs.fieldBytes = append(cfs.fieldBytes, cfs.src[cfs.rp]) + cfs.rp++ + default: + cfs.fieldBytes = append(cfs.fieldBytes, ch) + cfs.rp++ + } + } + cfs.rp++ + return true + default: // unquoted value + start := cfs.rp + for { + ch := cfs.src[cfs.rp] + if ch == ',' || ch == ')' { + break + } + cfs.rp++ + } + cfs.fieldBytes = cfs.src[start:cfs.rp] + cfs.rp++ + return true + } +} + +// Bytes returns the bytes of the field most recently read by Scan(). +func (cfs *CompositeTextScanner) Bytes() []byte { + return cfs.fieldBytes +} + +// Err returns any error encountered by the scanner. +func (cfs *CompositeTextScanner) Err() error { + return cfs.err +} + +type CompositeBinaryBuilder struct { + m *Map + buf []byte + startIdx int + fieldCount uint32 + err error +} + +func NewCompositeBinaryBuilder(m *Map, buf []byte) *CompositeBinaryBuilder { + startIdx := len(buf) + buf = append(buf, 0, 0, 0, 0) // allocate room for number of fields + return &CompositeBinaryBuilder{m: m, buf: buf, startIdx: startIdx} +} + +func (b *CompositeBinaryBuilder) AppendValue(oid uint32, field any) { + if b.err != nil { + return + } + + isNil, callNilDriverValuer := isNilDriverValuer(field) + if isNil && !callNilDriverValuer { + b.buf = pgio.AppendUint32(b.buf, oid) + b.buf = pgio.AppendInt32(b.buf, -1) + b.fieldCount++ + return + } + + var plan EncodePlan + if isNil { + plan = &encodePlanDriverValuer{m: b.m, oid: oid, formatCode: BinaryFormatCode} + } else { + plan = b.m.PlanEncode(oid, BinaryFormatCode, field) + if plan == nil { + b.err = fmt.Errorf("unable to encode %v into OID %d in binary format", field, oid) + return + } + } + + b.buf = pgio.AppendUint32(b.buf, oid) + lengthPos := len(b.buf) + b.buf = pgio.AppendInt32(b.buf, -1) + fieldBuf, err := plan.Encode(field, b.buf) + if err != nil { + b.err = err + return + } + if fieldBuf != nil { + binary.BigEndian.PutUint32(fieldBuf[lengthPos:], uint32(len(fieldBuf)-len(b.buf))) + b.buf = fieldBuf + } + + b.fieldCount++ +} + +func (b *CompositeBinaryBuilder) Finish() ([]byte, error) { + if b.err != nil { + return nil, b.err + } + + binary.BigEndian.PutUint32(b.buf[b.startIdx:], b.fieldCount) + return b.buf, nil +} + +type CompositeTextBuilder struct { + m *Map + buf []byte + startIdx int + fieldCount uint32 + err error + fieldBuf [32]byte +} + +func NewCompositeTextBuilder(m *Map, buf []byte) *CompositeTextBuilder { + buf = append(buf, '(') // allocate room for number of fields + return &CompositeTextBuilder{m: m, buf: buf} +} + +func (b *CompositeTextBuilder) AppendValue(oid uint32, field any) { + if b.err != nil { + return + } + + isNil, callNilDriverValuer := isNilDriverValuer(field) + if isNil && !callNilDriverValuer { + b.buf = append(b.buf, ',') + return + } + + var plan EncodePlan + if isNil { + plan = &encodePlanDriverValuer{m: b.m, oid: oid, formatCode: TextFormatCode} + } else { + plan = b.m.PlanEncode(oid, TextFormatCode, field) + if plan == nil { + b.err = fmt.Errorf("unable to encode %v into OID %d in text format", field, oid) + return + } + } + + fieldBuf, err := plan.Encode(field, b.fieldBuf[0:0]) + if err != nil { + b.err = err + return + } + if fieldBuf != nil { + b.buf = append(b.buf, quoteCompositeFieldIfNeeded(string(fieldBuf))...) + } + + b.buf = append(b.buf, ',') +} + +func (b *CompositeTextBuilder) Finish() ([]byte, error) { + if b.err != nil { + return nil, b.err + } + + b.buf[len(b.buf)-1] = ')' + return b.buf, nil +} + +var quoteCompositeReplacer = strings.NewReplacer(`\`, `\\`, `"`, `\"`) + +func quoteCompositeField(src string) string { + return `"` + quoteCompositeReplacer.Replace(src) + `"` +} + +func quoteCompositeFieldIfNeeded(src string) string { + if src == "" || src[0] == ' ' || src[len(src)-1] == ' ' || strings.ContainsAny(src, `(),"\`) { + return quoteCompositeField(src) + } + return src +} + +// CompositeFields represents the values of a composite value. It can be used as an encoding source or as a scan target. +// It cannot scan a NULL, but the composite fields can be NULL. +type CompositeFields []any + +func (cf CompositeFields) SkipUnderlyingTypePlan() {} + +func (cf CompositeFields) IsNull() bool { + return cf == nil +} + +func (cf CompositeFields) Index(i int) any { + return cf[i] +} + +func (cf CompositeFields) ScanNull() error { + return fmt.Errorf("cannot scan NULL into CompositeFields") +} + +func (cf CompositeFields) ScanIndex(i int) any { + return cf[i] +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/convert.go b/vendor/github.com/jackc/pgx/v5/pgtype/convert.go new file mode 100644 index 0000000..6693338 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/convert.go @@ -0,0 +1,108 @@ +package pgtype + +import ( + "reflect" +) + +func NullAssignTo(dst any) error { + dstPtr := reflect.ValueOf(dst) + + // AssignTo dst must always be a pointer + if dstPtr.Kind() != reflect.Pointer { + return &nullAssignmentError{dst: dst} + } + + dstVal := dstPtr.Elem() + + switch dstVal.Kind() { + case reflect.Pointer, reflect.Slice, reflect.Map: + dstVal.Set(reflect.Zero(dstVal.Type())) + return nil + } + + return &nullAssignmentError{dst: dst} +} + +var kindTypes map[reflect.Kind]reflect.Type + +func toInterface(dst reflect.Value, t reflect.Type) (any, bool) { + nextDst := dst.Convert(t) + return nextDst.Interface(), dst.Type() != nextDst.Type() +} + +// GetAssignToDstType attempts to convert dst to something AssignTo can assign +// to. If dst is a pointer to pointer it allocates a value and returns the +// dereferences pointer. If dst is a named type such as *Foo where Foo is type +// Foo int16, it converts dst to *int16. +// +// GetAssignToDstType returns the converted dst and a bool representing if any +// change was made. +func GetAssignToDstType(dst any) (any, bool) { + dstPtr := reflect.ValueOf(dst) + + // AssignTo dst must always be a pointer + if dstPtr.Kind() != reflect.Pointer { + return nil, false + } + + dstVal := dstPtr.Elem() + + // if dst is a pointer to pointer, allocate space try again with the dereferenced pointer + if dstVal.Kind() == reflect.Pointer { + dstVal.Set(reflect.New(dstVal.Type().Elem())) + return dstVal.Interface(), true + } + + // if dst is pointer to a base type that has been renamed + if baseValType, ok := kindTypes[dstVal.Kind()]; ok { + return toInterface(dstPtr, reflect.PointerTo(baseValType)) + } + + if dstVal.Kind() == reflect.Slice { + if baseElemType, ok := kindTypes[dstVal.Type().Elem().Kind()]; ok { + return toInterface(dstPtr, reflect.PointerTo(reflect.SliceOf(baseElemType))) + } + } + + if dstVal.Kind() == reflect.Array { + if baseElemType, ok := kindTypes[dstVal.Type().Elem().Kind()]; ok { + return toInterface(dstPtr, reflect.PointerTo(reflect.ArrayOf(dstVal.Len(), baseElemType))) + } + } + + if dstVal.Kind() == reflect.Struct { + if dstVal.Type().NumField() == 1 && dstVal.Type().Field(0).Anonymous { + dstPtr = dstVal.Field(0).Addr() + nested := dstVal.Type().Field(0).Type + if nested.Kind() == reflect.Array { + if baseElemType, ok := kindTypes[nested.Elem().Kind()]; ok { + return toInterface(dstPtr, reflect.PointerTo(reflect.ArrayOf(nested.Len(), baseElemType))) + } + } + if _, ok := kindTypes[nested.Kind()]; ok && dstPtr.CanInterface() { + return dstPtr.Interface(), true + } + } + } + + return nil, false +} + +func init() { + kindTypes = map[reflect.Kind]reflect.Type{ + reflect.Bool: reflect.TypeFor[bool](), + reflect.Float32: reflect.TypeFor[float32](), + reflect.Float64: reflect.TypeFor[float64](), + reflect.Int: reflect.TypeFor[int](), + reflect.Int8: reflect.TypeFor[int8](), + reflect.Int16: reflect.TypeFor[int16](), + reflect.Int32: reflect.TypeFor[int32](), + reflect.Int64: reflect.TypeFor[int64](), + reflect.Uint: reflect.TypeFor[uint](), + reflect.Uint8: reflect.TypeFor[uint8](), + reflect.Uint16: reflect.TypeFor[uint16](), + reflect.Uint32: reflect.TypeFor[uint32](), + reflect.Uint64: reflect.TypeFor[uint64](), + reflect.String: reflect.TypeFor[string](), + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/date.go b/vendor/github.com/jackc/pgx/v5/pgtype/date.go new file mode 100644 index 0000000..305d83c --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/date.go @@ -0,0 +1,412 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "strconv" + "time" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type DateScanner interface { + ScanDate(v Date) error +} + +type DateValuer interface { + DateValue() (Date, error) +} + +type Date struct { + Time time.Time + InfinityModifier InfinityModifier + Valid bool +} + +// ScanDate implements the [DateScanner] interface. +func (d *Date) ScanDate(v Date) error { + *d = v + return nil +} + +// DateValue implements the [DateValuer] interface. +func (d Date) DateValue() (Date, error) { + return d, nil +} + +const ( + negativeInfinityDayOffset = -2147483648 + infinityDayOffset = 2147483647 +) + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Date) Scan(src any) error { + if src == nil { + *dst = Date{} + return nil + } + + switch src := src.(type) { + case string: + return scanPlanTextAnyToDateScanner{}.Scan([]byte(src), dst) + case time.Time: + *dst = Date{Time: src, Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Date) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + if src.InfinityModifier != Finite { + return src.InfinityModifier.String(), nil + } + return src.Time, nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Date) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + + var s string + + switch src.InfinityModifier { + case Finite: + s = src.Time.Format("2006-01-02") + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + return json.Marshal(s) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Date) UnmarshalJSON(b []byte) error { + var s *string + err := json.Unmarshal(b, &s) + if err != nil { + return err + } + + if s == nil { + *dst = Date{} + return nil + } + + switch *s { + case "infinity": + *dst = Date{Valid: true, InfinityModifier: Infinity} + case "-infinity": + *dst = Date{Valid: true, InfinityModifier: -Infinity} + default: + t, err := time.ParseInLocation("2006-01-02", *s, time.UTC) + if err != nil { + return err + } + + *dst = Date{Time: t, Valid: true} + } + + return nil +} + +type DateCodec struct{} + +func (DateCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (DateCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (DateCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(DateValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanDateCodecBinary{} + case TextFormatCode: + return encodePlanDateCodecText{} + } + + return nil +} + +type encodePlanDateCodecBinary struct{} + +func (encodePlanDateCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + date, err := value.(DateValuer).DateValue() + if err != nil { + return nil, err + } + + if !date.Valid { + return nil, nil + } + + var daysSinceDateEpoch int32 + switch date.InfinityModifier { + case Finite: + tUnix := time.Date(date.Time.Year(), date.Time.Month(), date.Time.Day(), 0, 0, 0, 0, time.UTC).Unix() + dateEpoch := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC).Unix() + + secSinceDateEpoch := tUnix - dateEpoch + daysSinceDateEpoch = int32(secSinceDateEpoch / 86400) + case Infinity: + daysSinceDateEpoch = infinityDayOffset + case NegativeInfinity: + daysSinceDateEpoch = negativeInfinityDayOffset + } + + return pgio.AppendInt32(buf, daysSinceDateEpoch), nil +} + +type encodePlanDateCodecText struct{} + +func (encodePlanDateCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + date, err := value.(DateValuer).DateValue() + if err != nil { + return nil, err + } + + if !date.Valid { + return nil, nil + } + + switch date.InfinityModifier { + case Finite: + // Year 0000 is 1 BC + bc := false + year := date.Time.Year() + if year <= 0 { + year = -year + 1 + bc = true + } + + yearBytes := strconv.AppendInt(make([]byte, 0, 6), int64(year), 10) + for i := len(yearBytes); i < 4; i++ { + buf = append(buf, '0') + } + buf = append(buf, yearBytes...) + buf = append(buf, '-') + if date.Time.Month() < 10 { + buf = append(buf, '0') + } + buf = strconv.AppendInt(buf, int64(date.Time.Month()), 10) + buf = append(buf, '-') + if date.Time.Day() < 10 { + buf = append(buf, '0') + } + buf = strconv.AppendInt(buf, int64(date.Time.Day()), 10) + + if bc { + buf = append(buf, " BC"...) + } + case Infinity: + buf = append(buf, "infinity"...) + case NegativeInfinity: + buf = append(buf, "-infinity"...) + } + + return buf, nil +} + +func (DateCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(DateScanner); ok { + return scanPlanBinaryDateToDateScanner{} + } + case TextFormatCode: + if _, ok := target.(DateScanner); ok { + return scanPlanTextAnyToDateScanner{} + } + } + + return nil +} + +type scanPlanBinaryDateToDateScanner struct{} + +func (scanPlanBinaryDateToDateScanner) Scan(src []byte, dst any) error { + scanner := (dst).(DateScanner) + + if src == nil { + return scanner.ScanDate(Date{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for date: %v", len(src)) + } + + dayOffset := int32(binary.BigEndian.Uint32(src)) + + switch dayOffset { + case infinityDayOffset: + return scanner.ScanDate(Date{InfinityModifier: Infinity, Valid: true}) + case negativeInfinityDayOffset: + return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) + default: + t := time.Date(2000, 1, int(1+dayOffset), 0, 0, 0, 0, time.UTC) + return scanner.ScanDate(Date{Time: t, Valid: true}) + } +} + +type scanPlanTextAnyToDateScanner struct{} + +func (scanPlanTextAnyToDateScanner) Scan(src []byte, dst any) error { + scanner := (dst).(DateScanner) + + if src == nil { + return scanner.ScanDate(Date{}) + } + + // Check infinity cases first + if len(src) == 8 && string(src) == "infinity" { + return scanner.ScanDate(Date{InfinityModifier: Infinity, Valid: true}) + } + if len(src) == 9 && string(src) == "-infinity" { + return scanner.ScanDate(Date{InfinityModifier: -Infinity, Valid: true}) + } + + // Format: YYYY-MM-DD or YYYY...-MM-DD BC + // Minimum: 10 chars (2000-01-01), with BC: 13 chars + if len(src) < 10 { + return fmt.Errorf("invalid date format") + } + + // Check for BC suffix + bc := false + datePart := src + if len(src) >= 13 && string(src[len(src)-3:]) == " BC" { + bc = true + datePart = src[:len(src)-3] + } + + // Find year-month separator (first dash after at least 4 digits) + yearEnd := -1 + for i := 4; i < len(datePart); i++ { + if datePart[i] == '-' { + yearEnd = i + break + } + if datePart[i] < '0' || datePart[i] > '9' { + return fmt.Errorf("invalid date format") + } + } + if yearEnd == -1 || yearEnd+6 > len(datePart) { + return fmt.Errorf("invalid date format") + } + + // Validate: -MM-DD structure after year + if datePart[yearEnd+3] != '-' { + return fmt.Errorf("invalid date format") + } + + // Parse year + year, err := parseDigits(datePart[:yearEnd]) + if err != nil { + return fmt.Errorf("invalid date format") + } + + // Parse month (2 digits) + month, err := parse2Digits(datePart[yearEnd+1 : yearEnd+3]) + if err != nil { + return fmt.Errorf("invalid date format") + } + + // Parse day (2 digits) + day, err := parse2Digits(datePart[yearEnd+4 : yearEnd+6]) + if err != nil { + return fmt.Errorf("invalid date format") + } + + // Ensure nothing extra after day + if yearEnd+6 != len(datePart) { + return fmt.Errorf("invalid date format") + } + + if bc { + year = -year + 1 + } + + t := time.Date(int(year), time.Month(month), int(day), 0, 0, 0, 0, time.UTC) + return scanner.ScanDate(Date{Time: t, Valid: true}) +} + +// parse2Digits parses exactly 2 ASCII digits. +func parse2Digits(b []byte) (int64, error) { + if len(b) != 2 { + return 0, fmt.Errorf("expected 2 digits") + } + d1, d2 := b[0], b[1] + if d1 < '0' || d1 > '9' || d2 < '0' || d2 > '9' { + return 0, fmt.Errorf("expected digits") + } + return int64(d1-'0')*10 + int64(d2-'0'), nil +} + +// parseDigits parses a sequence of ASCII digits. +func parseDigits(b []byte) (int64, error) { + if len(b) == 0 { + return 0, fmt.Errorf("empty") + } + var n int64 + for _, c := range b { + if c < '0' || c > '9' { + return 0, fmt.Errorf("non-digit") + } + n = n*10 + int64(c-'0') + } + return n, nil +} + +func (c DateCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var date Date + err := codecScan(c, m, oid, format, src, &date) + if err != nil { + return nil, err + } + + if date.InfinityModifier != Finite { + return date.InfinityModifier.String(), nil + } + + return date.Time, nil +} + +func (c DateCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var date Date + err := codecScan(c, m, oid, format, src, &date) + if err != nil { + return nil, err + } + + if date.InfinityModifier != Finite { + return date.InfinityModifier, nil + } + + return date.Time, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/doc.go b/vendor/github.com/jackc/pgx/v5/pgtype/doc.go new file mode 100644 index 0000000..dbcdf69 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/doc.go @@ -0,0 +1,196 @@ +// Package pgtype converts between Go and PostgreSQL values. +/* +The primary type is the [Map] type. It is a map of PostgreSQL types identified by OID (object ID) to a [Codec]. A [Codec] is +responsible for converting between Go and PostgreSQL values. [NewMap] creates a [Map] with all supported standard PostgreSQL +types already registered. Additional types can be registered with [Map.RegisterType]. + +Use [Map.Scan] and [Map.Encode] to decode PostgreSQL values to Go and encode Go values to PostgreSQL respectively. + +Base Type Mapping + +pgtype maps between all common base types directly between Go and PostgreSQL. In particular: + + Go PostgreSQL + ----------------------- + string varchar + text + + // Integers are automatically be converted to any other integer type if + // it can be done without overflow or underflow. + int8 + int16 smallint + int32 int + int64 bigint + int + uint8 + uint16 + uint32 + uint64 + uint + + // Floats are strict and do not automatically convert like integers. + float32 float4 + float64 float8 + + time.Time date + timestamp + timestamptz + + netip.Addr inet + netip.Prefix cidr + + []byte bytea + +Null Values + +pgtype can map NULLs in two ways. The first is types that can directly represent NULL such as Int4. They work in a +similar fashion to database/sql. The second is to use a pointer to a pointer. + + var foo pgtype.Text + var bar *string + err := conn.QueryRow("select foo, bar from widgets where id=$1", 42).Scan(&foo, &bar) + if err != nil { + return err + } + +When using nullable pgtype types as parameters for queries, one has to remember to explicitly set their Valid field to +true, otherwise the parameter's value will be NULL. + +JSON Support + +pgtype automatically marshals and unmarshals data from json and jsonb PostgreSQL types. + +Extending Existing PostgreSQL Type Support + +Generally, all Codecs will support interfaces that can be implemented to enable scanning and encoding. For example, +[PointCodec] can use any Go type that implements the [PointScanner] and [PointValuer] interfaces. So rather than use +[Point] an application can directly use its own point type with pgtype as long as it implements those interfaces. + +See example_custom_type_test.go for an example of a custom type for the PostgreSQL point type. + +Sometimes pgx supports a PostgreSQL type such as numeric but the Go type is in an external package that does not have +pgx support such as github.com/shopspring/decimal. These types can be registered with pgtype with custom conversion +logic. See https://github.com/jackc/pgx-shopspring-decimal and https://github.com/jackc/pgx-gofrs-uuid for example +integrations. + +New PostgreSQL Type Support + +pgtype uses the PostgreSQL OID to determine how to encode or decode a value. pgtype supports array, composite, domain, +and enum types. However, any type created in PostgreSQL with CREATE TYPE will receive a new OID. This means that the OID +of each new PostgreSQL type must be registered for pgtype to handle values of that type with the correct [Codec]. + +The [github.com/jackc/pgx/v5.Conn.LoadType] method can return a [*Type] for array, composite, domain, and enum types by +inspecting the database metadata. This [*Type] can then be registered with [Map.RegisterType]. + +For example, the following function could be called after a connection is established: + + func RegisterDataTypes(ctx context.Context, conn *pgx.Conn) error { + dataTypeNames := []string{ + "foo", + "_foo", + "bar", + "_bar", + } + + for _, typeName := range dataTypeNames { + dataType, err := conn.LoadType(ctx, typeName) + if err != nil { + return err + } + conn.TypeMap().RegisterType(dataType) + } + + return nil + } + +A type cannot be registered unless all types it depends on are already registered. e.g. An array type cannot be +registered until its element type is registered. + +[ArrayCodec] implements support for arrays. If pgtype supports type T then it can easily support []T by registering an +[ArrayCodec] for the appropriate PostgreSQL OID. In addition, [Array] type can support multi-dimensional arrays. + +[CompositeCodec] implements support for PostgreSQL composite types. Go structs can be scanned into if the public fields of +the struct are in the exact order and type of the PostgreSQL type or by implementing [CompositeIndexScanner] and +[CompositeIndexGetter]. + +Domain types are treated as their underlying type if the underlying type and the domain type are registered. + +PostgreSQL enums can usually be treated as text. However, [EnumCodec] implements support for interning strings which can +reduce memory usage. + +While pgtype will often still work with unregistered types it is highly recommended that all types be registered due to +an improvement in performance and the elimination of certain edge cases. + +If an entirely new PostgreSQL type (e.g. PostGIS types) is used then the application or a library can create a new +[Codec]. Then the OID / [Codec] mapping can be registered with [Map.RegisterType]. There is no difference between a [Codec] +defined and registered by the application and a [Codec] built in to pgtype. See any of the [Codec]s in pgtype for [Codec] +examples and for examples of type registration. + +Encoding Unknown Types + +pgtype works best when the OID of the PostgreSQL type is known. But in some cases such as using the simple protocol the +OID is unknown. In this case [Map.RegisterDefaultPgType] can be used to register an assumed OID for a particular Go type. + +Renamed Types + +If pgtype does not recognize a type and that type is a renamed simple type simple (e.g. type MyInt32 int32) pgtype acts +as if it is the underlying type. It currently cannot automatically detect the underlying type of renamed structs (eg.g. +type MyTime time.Time). + +Compatibility with [database/sql] + +pgtype also includes support for custom types implementing the [database/sql.Scanner] and [database/sql/driver.Valuer] +interfaces. + +Encoding Typed Nils + +pgtype encodes untyped and typed nils (e.g. nil and []byte(nil)) to the SQL NULL value without going through the [Codec] +system. This means that [Codec]s and other encoding logic do not have to handle nil or *T(nil). + +However, [database/sql] compatibility requires Value to be called on T(nil) when T implements [database/sql/driver.Valuer]. Therefore, +[database/sql/driver.Valuer] values are only considered NULL when *T(nil) where [database/sql/driver.Valuer] is implemented on T not on *T. See +https://github.com/golang/go/issues/8415 and +https://github.com/golang/go/commit/0ce1d79a6a771f7449ec493b993ed2a720917870. + +Child Records + +pgtype's support for arrays and composite records can be used to load records and their children in a single query. See +example_child_records_test.go for an example. + +Overview of Scanning Implementation + +The first step is to use the OID to lookup the correct [Codec]. The [Map] will call the [Codec.PlanScan] method to get a +plan for scanning into the Go value. A [Codec] will support scanning into one or more Go types. Oftentime these Go types +are interfaces rather than explicit types. For example, [PointCodec] can use any Go type that implements the [PointScanner] +and [PointValuer] interfaces. + +If a Go value is not supported directly by a [Codec] then [Map] will try see if it is a [database/sql.Scanner]. If is then that +interface will be used to scan the value. Most [database/sql.Scanner]s require the input to be in the text format (e.g. UUIDs and +numeric). However, pgx will typically have received the value in the binary format. In this case the binary value will be +parsed, reencoded as text, and then passed to the [database/sql.Scanner]. This may incur additional overhead for query results with +a large number of affected values. + +If a Go value is not supported directly by a [Codec] then [Map] will try wrapping it with additional logic and try again. +For example, [Int8Codec] does not support scanning into a renamed type (e.g. type myInt64 int64). But [Map] will detect that +myInt64 is a renamed type and create a plan that converts the value to the underlying int64 type and then passes that to +the [Codec] (see [TryFindUnderlyingTypeScanPlan]). + +These plan wrappers are contained in [Map.TryWrapScanPlanFuncs]. By default these contain shared logic to handle renamed +types, pointers to pointers, slices, composite types, etc. Additional plan wrappers can be added to seamlessly integrate +types that do not support pgx directly. For example, the before mentioned +https://github.com/jackc/pgx-shopspring-decimal package detects decimal.Decimal values, wraps them in something +implementing [NumericScanner] and passes that to the [Codec]. + +[Map.Scan] and [Map.Encode] are convenience methods that wrap [Map.PlanScan] and [Map.PlanEncode]. Determining how to scan or +encode a particular type may be a time consuming operation. Hence the planning and execution steps of a conversion are +internally separated. + +Reducing Compiled Binary Size + +[github.com/jackc/pgx/v5.QueryExecModeExec] and [github.com/jackc/pgx/v5.QueryExecModeSimpleProtocol] require the default +PostgreSQL type to be registered for each Go type used as a query parameter. By default pgx does this for all supported +types and their array variants. If an application does not use those query execution modes or manually registers the default +PostgreSQL type for the types it uses as query parameters it can use the build tag nopgxregisterdefaulttypes. This omits +the default type registration and reduces the compiled binary size by ~2MB. +*/ +package pgtype diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go new file mode 100644 index 0000000..5e787c1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/enum_codec.go @@ -0,0 +1,109 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" +) + +// EnumCodec is a codec that caches the strings it decodes. If the same string is read multiple times only one copy is +// allocated. These strings are only garbage collected when the EnumCodec is garbage collected. EnumCodec can be used +// for any text type not only enums, but it should only be used when there are a small number of possible values. +type EnumCodec struct { + membersMap map[string]string // map to quickly lookup member and reuse string instead of allocating +} + +func (EnumCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (EnumCodec) PreferredFormat() int16 { + return TextFormatCode +} + +func (EnumCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case TextFormatCode, BinaryFormatCode: + switch value.(type) { + case string: + return encodePlanTextCodecString{} + case []byte: + return encodePlanTextCodecByteSlice{} + case TextValuer: + return encodePlanTextCodecTextValuer{} + } + } + + return nil +} + +func (c *EnumCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case TextFormatCode, BinaryFormatCode: + switch target.(type) { + case *string: + return &scanPlanTextAnyToEnumString{codec: c} + case *[]byte: + return scanPlanAnyToNewByteSlice{} + case TextScanner: + return &scanPlanTextAnyToEnumTextScanner{codec: c} + } + } + + return nil +} + +func (c *EnumCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return c.DecodeValue(m, oid, format, src) +} + +func (c *EnumCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + return c.lookupAndCacheString(src), nil +} + +// lookupAndCacheString looks for src in the members map. If it is not found it is added to the map. +func (c *EnumCodec) lookupAndCacheString(src []byte) string { + if c.membersMap == nil { + c.membersMap = make(map[string]string) + } + + if s, found := c.membersMap[string(src)]; found { + return s + } + + s := string(src) + c.membersMap[s] = s + return s +} + +type scanPlanTextAnyToEnumString struct { + codec *EnumCodec +} + +func (plan *scanPlanTextAnyToEnumString) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p := (dst).(*string) + *p = plan.codec.lookupAndCacheString(src) + + return nil +} + +type scanPlanTextAnyToEnumTextScanner struct { + codec *EnumCodec +} + +func (plan *scanPlanTextAnyToEnumTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + + return scanner.ScanText(Text{String: plan.codec.lookupAndCacheString(src), Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float4.go b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go new file mode 100644 index 0000000..a43553f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float4.go @@ -0,0 +1,323 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "math" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Float4 struct { + Float32 float32 + Valid bool +} + +// ScanFloat64 implements the [Float64Scanner] interface. +func (f *Float4) ScanFloat64(n Float8) error { + *f = Float4{Float32: float32(n.Float64), Valid: n.Valid} + return nil +} + +// Float64Value implements the [Float64Valuer] interface. +func (f Float4) Float64Value() (Float8, error) { + return Float8{Float64: float64(f.Float32), Valid: f.Valid}, nil +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (f *Float4) ScanInt64(n Int8) error { + *f = Float4{Float32: float32(n.Int64), Valid: n.Valid} + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (f Float4) Int64Value() (Int8, error) { + return Int8{Int64: int64(f.Float32), Valid: f.Valid}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (f *Float4) Scan(src any) error { + if src == nil { + *f = Float4{} + return nil + } + + switch src := src.(type) { + case float64: + *f = Float4{Float32: float32(src), Valid: true} + return nil + case string: + n, err := strconv.ParseFloat(src, 32) + if err != nil { + return err + } + *f = Float4{Float32: float32(n), Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (f Float4) Value() (driver.Value, error) { + if !f.Valid { + return nil, nil + } + return float64(f.Float32), nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (f Float4) MarshalJSON() ([]byte, error) { + if !f.Valid { + return []byte("null"), nil + } + return json.Marshal(f.Float32) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (f *Float4) UnmarshalJSON(b []byte) error { + var n *float32 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *f = Float4{} + } else { + *f = Float4{Float32: *n, Valid: true} + } + + return nil +} + +type Float4Codec struct{} + +func (Float4Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Float4Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Float4Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case float32: + return encodePlanFloat4CodecBinaryFloat32{} + case Float64Valuer: + return encodePlanFloat4CodecBinaryFloat64Valuer{} + case Int64Valuer: + return encodePlanFloat4CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case float32: + return encodePlanTextFloat32{} + case Float64Valuer: + return encodePlanTextFloat64Valuer{} + case Int64Valuer: + return encodePlanTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanFloat4CodecBinaryFloat32 struct{} + +func (encodePlanFloat4CodecBinaryFloat32) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(float32) + return pgio.AppendUint32(buf, math.Float32bits(n)), nil +} + +type encodePlanTextFloat32 struct{} + +func (encodePlanTextFloat32) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(float32) + return append(buf, strconv.FormatFloat(float64(n), 'f', -1, 32)...), nil +} + +type encodePlanFloat4CodecBinaryFloat64Valuer struct{} + +func (encodePlanFloat4CodecBinaryFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Float64Valuer).Float64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + return pgio.AppendUint32(buf, math.Float32bits(float32(n.Float64))), nil +} + +type encodePlanFloat4CodecBinaryInt64Valuer struct{} + +func (encodePlanFloat4CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + f := float32(n.Int64) + return pgio.AppendUint32(buf, math.Float32bits(f)), nil +} + +func (Float4Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *float32: + return scanPlanBinaryFloat4ToFloat32{} + case Float64Scanner: + return scanPlanBinaryFloat4ToFloat64Scanner{} + case Int64Scanner: + return scanPlanBinaryFloat4ToInt64Scanner{} + case TextScanner: + return scanPlanBinaryFloat4ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *float32: + return scanPlanTextAnyToFloat32{} + case Float64Scanner: + return scanPlanTextAnyToFloat64Scanner{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +type scanPlanBinaryFloat4ToFloat32 struct{} + +func (scanPlanBinaryFloat4ToFloat32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for float4: %v", len(src)) + } + + n := int32(binary.BigEndian.Uint32(src)) + f := (dst).(*float32) + *f = math.Float32frombits(uint32(n)) + + return nil +} + +type scanPlanBinaryFloat4ToFloat64Scanner struct{} + +func (scanPlanBinaryFloat4ToFloat64Scanner) Scan(src []byte, dst any) error { + s := (dst).(Float64Scanner) + + if src == nil { + return s.ScanFloat64(Float8{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for float4: %v", len(src)) + } + + n := int32(binary.BigEndian.Uint32(src)) + return s.ScanFloat64(Float8{Float64: float64(math.Float32frombits(uint32(n))), Valid: true}) +} + +type scanPlanBinaryFloat4ToInt64Scanner struct{} + +func (scanPlanBinaryFloat4ToInt64Scanner) Scan(src []byte, dst any) error { + s := (dst).(Int64Scanner) + + if src == nil { + return s.ScanInt64(Int8{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for float4: %v", len(src)) + } + + ui32 := int32(binary.BigEndian.Uint32(src)) + f32 := math.Float32frombits(uint32(ui32)) + i64 := int64(f32) + if f32 != float32(i64) { + return fmt.Errorf("cannot losslessly convert %v to int64", f32) + } + + return s.ScanInt64(Int8{Int64: i64, Valid: true}) +} + +type scanPlanBinaryFloat4ToTextScanner struct{} + +func (scanPlanBinaryFloat4ToTextScanner) Scan(src []byte, dst any) error { + s := (dst).(TextScanner) + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for float4: %v", len(src)) + } + + ui32 := int32(binary.BigEndian.Uint32(src)) + f32 := math.Float32frombits(uint32(ui32)) + + return s.ScanText(Text{String: strconv.FormatFloat(float64(f32), 'f', -1, 32), Valid: true}) +} + +type scanPlanTextAnyToFloat32 struct{} + +func (scanPlanTextAnyToFloat32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + n, err := strconv.ParseFloat(string(src), 32) + if err != nil { + return err + } + + f := (dst).(*float32) + *f = float32(n) + + return nil +} + +func (c Float4Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n float32 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return float64(n), nil +} + +func (c Float4Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n float32 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/float8.go b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go new file mode 100644 index 0000000..6234231 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/float8.go @@ -0,0 +1,369 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "math" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Float64Scanner interface { + ScanFloat64(Float8) error +} + +type Float64Valuer interface { + Float64Value() (Float8, error) +} + +type Float8 struct { + Float64 float64 + Valid bool +} + +// ScanFloat64 implements the [Float64Scanner] interface. +func (f *Float8) ScanFloat64(n Float8) error { + *f = n + return nil +} + +// Float64Value implements the [Float64Valuer] interface. +func (f Float8) Float64Value() (Float8, error) { + return f, nil +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (f *Float8) ScanInt64(n Int8) error { + *f = Float8{Float64: float64(n.Int64), Valid: n.Valid} + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (f Float8) Int64Value() (Int8, error) { + return Int8{Int64: int64(f.Float64), Valid: f.Valid}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (f *Float8) Scan(src any) error { + if src == nil { + *f = Float8{} + return nil + } + + switch src := src.(type) { + case float64: + *f = Float8{Float64: src, Valid: true} + return nil + case string: + n, err := strconv.ParseFloat(src, 64) + if err != nil { + return err + } + *f = Float8{Float64: n, Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (f Float8) Value() (driver.Value, error) { + if !f.Valid { + return nil, nil + } + return f.Float64, nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (f Float8) MarshalJSON() ([]byte, error) { + if !f.Valid { + return []byte("null"), nil + } + return json.Marshal(f.Float64) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (f *Float8) UnmarshalJSON(b []byte) error { + var n *float64 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *f = Float8{} + } else { + *f = Float8{Float64: *n, Valid: true} + } + + return nil +} + +type Float8Codec struct{} + +func (Float8Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Float8Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Float8Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case float64: + return encodePlanFloat8CodecBinaryFloat64{} + case Float64Valuer: + return encodePlanFloat8CodecBinaryFloat64Valuer{} + case Int64Valuer: + return encodePlanFloat8CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case float64: + return encodePlanTextFloat64{} + case Float64Valuer: + return encodePlanTextFloat64Valuer{} + case Int64Valuer: + return encodePlanTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanFloat8CodecBinaryFloat64 struct{} + +func (encodePlanFloat8CodecBinaryFloat64) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(float64) + return pgio.AppendUint64(buf, math.Float64bits(n)), nil +} + +type encodePlanTextFloat64 struct{} + +func (encodePlanTextFloat64) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(float64) + return append(buf, strconv.FormatFloat(n, 'f', -1, 64)...), nil +} + +type encodePlanFloat8CodecBinaryFloat64Valuer struct{} + +func (encodePlanFloat8CodecBinaryFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Float64Valuer).Float64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + return pgio.AppendUint64(buf, math.Float64bits(n.Float64)), nil +} + +type encodePlanTextFloat64Valuer struct{} + +func (encodePlanTextFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Float64Valuer).Float64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + return append(buf, strconv.FormatFloat(n.Float64, 'f', -1, 64)...), nil +} + +type encodePlanFloat8CodecBinaryInt64Valuer struct{} + +func (encodePlanFloat8CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + f := float64(n.Int64) + return pgio.AppendUint64(buf, math.Float64bits(f)), nil +} + +type encodePlanTextInt64Valuer struct{} + +func (encodePlanTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + return append(buf, strconv.FormatInt(n.Int64, 10)...), nil +} + +func (Float8Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *float64: + return scanPlanBinaryFloat8ToFloat64{} + case Float64Scanner: + return scanPlanBinaryFloat8ToFloat64Scanner{} + case Int64Scanner: + return scanPlanBinaryFloat8ToInt64Scanner{} + case TextScanner: + return scanPlanBinaryFloat8ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *float64: + return scanPlanTextAnyToFloat64{} + case Float64Scanner: + return scanPlanTextAnyToFloat64Scanner{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +type scanPlanBinaryFloat8ToFloat64 struct{} + +func (scanPlanBinaryFloat8ToFloat64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for float8: %v", len(src)) + } + + n := int64(binary.BigEndian.Uint64(src)) + f := (dst).(*float64) + *f = math.Float64frombits(uint64(n)) + + return nil +} + +type scanPlanBinaryFloat8ToFloat64Scanner struct{} + +func (scanPlanBinaryFloat8ToFloat64Scanner) Scan(src []byte, dst any) error { + s := (dst).(Float64Scanner) + + if src == nil { + return s.ScanFloat64(Float8{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for float8: %v", len(src)) + } + + n := int64(binary.BigEndian.Uint64(src)) + return s.ScanFloat64(Float8{Float64: math.Float64frombits(uint64(n)), Valid: true}) +} + +type scanPlanBinaryFloat8ToInt64Scanner struct{} + +func (scanPlanBinaryFloat8ToInt64Scanner) Scan(src []byte, dst any) error { + s := (dst).(Int64Scanner) + + if src == nil { + return s.ScanInt64(Int8{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for float8: %v", len(src)) + } + + ui64 := int64(binary.BigEndian.Uint64(src)) + f64 := math.Float64frombits(uint64(ui64)) + i64 := int64(f64) + if f64 != float64(i64) { + return fmt.Errorf("cannot losslessly convert %v to int64", f64) + } + + return s.ScanInt64(Int8{Int64: i64, Valid: true}) +} + +type scanPlanBinaryFloat8ToTextScanner struct{} + +func (scanPlanBinaryFloat8ToTextScanner) Scan(src []byte, dst any) error { + s := (dst).(TextScanner) + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for float8: %v", len(src)) + } + + ui64 := int64(binary.BigEndian.Uint64(src)) + f64 := math.Float64frombits(uint64(ui64)) + + return s.ScanText(Text{String: strconv.FormatFloat(f64, 'f', -1, 64), Valid: true}) +} + +type scanPlanTextAnyToFloat64 struct{} + +func (scanPlanTextAnyToFloat64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + n, err := strconv.ParseFloat(string(src), 64) + if err != nil { + return err + } + + f := (dst).(*float64) + *f = n + + return nil +} + +type scanPlanTextAnyToFloat64Scanner struct{} + +func (scanPlanTextAnyToFloat64Scanner) Scan(src []byte, dst any) error { + s := (dst).(Float64Scanner) + + if src == nil { + return s.ScanFloat64(Float8{}) + } + + n, err := strconv.ParseFloat(string(src), 64) + if err != nil { + return err + } + + return s.ScanFloat64(Float8{Float64: n, Valid: true}) +} + +func (c Float8Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return c.DecodeValue(m, oid, format, src) +} + +func (c Float8Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n float64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go new file mode 100644 index 0000000..4a2bb0a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/hstore.go @@ -0,0 +1,502 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "errors" + "fmt" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type HstoreScanner interface { + ScanHstore(v Hstore) error +} + +type HstoreValuer interface { + HstoreValue() (Hstore, error) +} + +// Hstore represents an hstore column that can be null or have null values +// associated with its keys. +type Hstore map[string]*string + +// ScanHstore implements the [HstoreScanner] interface. +func (h *Hstore) ScanHstore(v Hstore) error { + *h = v + return nil +} + +// HstoreValue implements the [HstoreValuer] interface. +func (h Hstore) HstoreValue() (Hstore, error) { + return h, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (h *Hstore) Scan(src any) error { + if src == nil { + *h = nil + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToHstoreScanner{}.scanString(src, h) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (h Hstore) Value() (driver.Value, error) { + if h == nil { + return nil, nil + } + + buf, err := HstoreCodec{}.PlanEncode(nil, 0, TextFormatCode, h).Encode(h, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type HstoreCodec struct{} + +func (HstoreCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (HstoreCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (HstoreCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(HstoreValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanHstoreCodecBinary{} + case TextFormatCode: + return encodePlanHstoreCodecText{} + } + + return nil +} + +type encodePlanHstoreCodecBinary struct{} + +func (encodePlanHstoreCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + hstore, err := value.(HstoreValuer).HstoreValue() + if err != nil { + return nil, err + } + + if hstore == nil { + return nil, nil + } + + buf = pgio.AppendInt32(buf, int32(len(hstore))) + + for k, v := range hstore { + buf = pgio.AppendInt32(buf, int32(len(k))) + buf = append(buf, k...) + + if v == nil { + buf = pgio.AppendInt32(buf, -1) + } else { + buf = pgio.AppendInt32(buf, int32(len(*v))) + buf = append(buf, (*v)...) + } + } + + return buf, nil +} + +type encodePlanHstoreCodecText struct{} + +func (encodePlanHstoreCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + hstore, err := value.(HstoreValuer).HstoreValue() + if err != nil { + return nil, err + } + + if len(hstore) == 0 { + // distinguish between empty and nil: Not strictly required by Postgres, since its protocol + // explicitly marks NULL column values separately. However, the Binary codec does this, and + // this means we can "round trip" Encode and Scan without data loss. + // nil: []byte(nil); empty: []byte{} + if hstore == nil { + return nil, nil + } + return []byte{}, nil + } + + firstPair := true + + for k, v := range hstore { + if firstPair { + firstPair = false + } else { + buf = append(buf, ',', ' ') + } + + // unconditionally quote hstore keys/values like Postgres does + // this avoids a Mac OS X Postgres hstore parsing bug: + // https://www.postgresql.org/message-id/CA%2BHWA9awUW0%2BRV_gO9r1ABZwGoZxPztcJxPy8vMFSTbTfi4jig%40mail.gmail.com + buf = append(buf, '"') + buf = append(buf, quoteArrayReplacer.Replace(k)...) + buf = append(buf, '"') + buf = append(buf, "=>"...) + + if v == nil { + buf = append(buf, "NULL"...) + } else { + buf = append(buf, '"') + buf = append(buf, quoteArrayReplacer.Replace(*v)...) + buf = append(buf, '"') + } + } + + return buf, nil +} + +func (HstoreCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(HstoreScanner); ok { + return scanPlanBinaryHstoreToHstoreScanner{} + } + case TextFormatCode: + if _, ok := target.(HstoreScanner); ok { + return scanPlanTextAnyToHstoreScanner{} + } + } + + return nil +} + +type scanPlanBinaryHstoreToHstoreScanner struct{} + +func (scanPlanBinaryHstoreToHstoreScanner) Scan(src []byte, dst any) error { + scanner := (dst).(HstoreScanner) + + if src == nil { + return scanner.ScanHstore(Hstore(nil)) + } + + rp := 0 + + const uint32Len = 4 + if len(src[rp:]) < uint32Len { + return fmt.Errorf("hstore incomplete %v", src) + } + pairCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += uint32Len + + if pairCount < 0 { + return fmt.Errorf("hstore invalid pair count: %d", pairCount) + } + // Each pair carries at minimum two int32 length headers (key, value), so pairCount cannot + // exceed the remaining bytes / 8. This bounds the up-front make() against a malicious server + // claiming a huge pair count in a small message. + if maxPairs := len(src[rp:]) / (2 * uint32Len); pairCount > maxPairs { + return fmt.Errorf("hstore invalid pair count %d for %d remaining bytes", pairCount, len(src[rp:])) + } + + hstore := make(Hstore, pairCount) + // one allocation for all *string, rather than one per string, just like text parsing + valueStrings := make([]string, pairCount) + + for i := range pairCount { + if len(src[rp:]) < uint32Len { + return fmt.Errorf("hstore incomplete %v", src) + } + keyLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += uint32Len + + if keyLen < 0 { + return fmt.Errorf("hstore invalid key length: %d", keyLen) + } + if len(src[rp:]) < keyLen { + return fmt.Errorf("hstore incomplete %v", src) + } + key := string(src[rp : rp+keyLen]) + rp += keyLen + + if len(src[rp:]) < uint32Len { + return fmt.Errorf("hstore incomplete %v", src) + } + valueLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + + if valueLen >= 0 { + if len(src[rp:]) < valueLen { + return fmt.Errorf("hstore incomplete %v", src) + } + valueStrings[i] = string(src[rp : rp+valueLen]) + rp += valueLen + + hstore[key] = &valueStrings[i] + } else { + hstore[key] = nil + } + } + + return scanner.ScanHstore(hstore) +} + +type scanPlanTextAnyToHstoreScanner struct{} + +func (s scanPlanTextAnyToHstoreScanner) Scan(src []byte, dst any) error { + scanner := (dst).(HstoreScanner) + + if src == nil { + return scanner.ScanHstore(Hstore(nil)) + } + return s.scanString(string(src), scanner) +} + +// scanString does not return nil hstore values because string cannot be nil. +func (scanPlanTextAnyToHstoreScanner) scanString(src string, scanner HstoreScanner) error { + hstore, err := parseHstore(src) + if err != nil { + return err + } + return scanner.ScanHstore(hstore) +} + +func (c HstoreCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c HstoreCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var hstore Hstore + err := codecScan(c, m, oid, format, src, &hstore) + if err != nil { + return nil, err + } + return hstore, nil +} + +type hstoreParser struct { + str string + pos int + nextBackslash int +} + +func newHSP(in string) *hstoreParser { + return &hstoreParser{ + pos: 0, + str: in, + nextBackslash: strings.IndexByte(in, '\\'), + } +} + +func (p *hstoreParser) atEnd() bool { + return p.pos >= len(p.str) +} + +// consume returns the next byte of the string, or end if the string is done. +func (p *hstoreParser) consume() (b byte, end bool) { + if p.pos >= len(p.str) { + return 0, true + } + b = p.str[p.pos] + p.pos++ + return b, false +} + +func unexpectedByteErr(actualB, expectedB byte) error { + return fmt.Errorf("expected '%c' ('%#v'); found '%c' ('%#v')", expectedB, expectedB, actualB, actualB) +} + +// consumeExpectedByte consumes expectedB from the string, or returns an error. +func (p *hstoreParser) consumeExpectedByte(expectedB byte) error { + nextB, end := p.consume() + if end { + return fmt.Errorf("expected '%c' ('%#v'); found end", expectedB, expectedB) + } + if nextB != expectedB { + return unexpectedByteErr(nextB, expectedB) + } + return nil +} + +// consumeExpected2 consumes two expected bytes or returns an error. +// This was a bit faster than using a string argument (better inlining? Not sure). +func (p *hstoreParser) consumeExpected2(one, two byte) error { + if p.pos+2 > len(p.str) { + return errors.New("unexpected end of string") + } + if p.str[p.pos] != one { + return unexpectedByteErr(p.str[p.pos], one) + } + if p.str[p.pos+1] != two { + return unexpectedByteErr(p.str[p.pos+1], two) + } + p.pos += 2 + return nil +} + +var errEOSInQuoted = errors.New(`found end before closing double-quote ('"')`) + +// consumeDoubleQuoted consumes a double-quoted string from p. The double quote must have been +// parsed already. This copies the string from the backing string so it can be garbage collected. +func (p *hstoreParser) consumeDoubleQuoted() (string, error) { + // fast path: assume most keys/values do not contain escapes + nextDoubleQuote := strings.IndexByte(p.str[p.pos:], '"') + if nextDoubleQuote == -1 { + return "", errEOSInQuoted + } + nextDoubleQuote += p.pos + if p.nextBackslash == -1 || p.nextBackslash > nextDoubleQuote { + // clone the string from the source string to ensure it can be garbage collected separately + // TODO: use strings.Clone on Go 1.20; this could get optimized away + s := strings.Clone(p.str[p.pos:nextDoubleQuote]) + p.pos = nextDoubleQuote + 1 + return s, nil + } + + // slow path: string contains escapes + s, err := p.consumeDoubleQuotedWithEscapes(p.nextBackslash) + p.nextBackslash = strings.IndexByte(p.str[p.pos:], '\\') + if p.nextBackslash != -1 { + p.nextBackslash += p.pos + } + return s, err +} + +// consumeDoubleQuotedWithEscapes consumes a double-quoted string containing escapes, starting +// at p.pos, and with the first backslash at firstBackslash. This copies the string so it can be +// garbage collected separately. +func (p *hstoreParser) consumeDoubleQuotedWithEscapes(firstBackslash int) (string, error) { + // copy the prefix that does not contain backslashes + var builder strings.Builder + builder.WriteString(p.str[p.pos:firstBackslash]) + + // skip to the backslash + p.pos = firstBackslash + + // copy bytes until the end, unescaping backslashes +quotedString: + for { + nextB, end := p.consume() + switch { + case end: + return "", errEOSInQuoted + case nextB == '"': + break quotedString + case nextB == '\\': + // escape: skip the backslash and copy the char + nextB, end = p.consume() + if end { + return "", errEOSInQuoted + } + if !(nextB == '\\' || nextB == '"') { + return "", fmt.Errorf("unexpected escape in quoted string: found '%#v'", nextB) + } + builder.WriteByte(nextB) + default: + // normal byte: copy it + builder.WriteByte(nextB) + } + } + return builder.String(), nil +} + +// consumePairSeparator consumes the Hstore pair separator ", " or returns an error. +func (p *hstoreParser) consumePairSeparator() error { + return p.consumeExpected2(',', ' ') +} + +// consumeKVSeparator consumes the Hstore key/value separator "=>" or returns an error. +func (p *hstoreParser) consumeKVSeparator() error { + return p.consumeExpected2('=', '>') +} + +// consumeDoubleQuotedOrNull consumes the Hstore key/value separator "=>" or returns an error. +func (p *hstoreParser) consumeDoubleQuotedOrNull() (Text, error) { + // peek at the next byte + if p.atEnd() { + return Text{}, errors.New("found end instead of value") + } + next := p.str[p.pos] + if next == 'N' { + // must be the exact string NULL: use consumeExpected2 twice + err := p.consumeExpected2('N', 'U') + if err != nil { + return Text{}, err + } + err = p.consumeExpected2('L', 'L') + if err != nil { + return Text{}, err + } + return Text{String: "", Valid: false}, nil + } else if next != '"' { + return Text{}, unexpectedByteErr(next, '"') + } + + // skip the double quote + p.pos += 1 + s, err := p.consumeDoubleQuoted() + if err != nil { + return Text{}, err + } + return Text{String: s, Valid: true}, nil +} + +func parseHstore(s string) (Hstore, error) { + p := newHSP(s) + + // This is an over-estimate of the number of key/value pairs. Use '>' because I am guessing it + // is less likely to occur in keys/values than '=' or ','. + numPairsEstimate := strings.Count(s, ">") + // makes one allocation of strings for the entire Hstore, rather than one allocation per value. + valueStrings := make([]string, 0, numPairsEstimate) + result := make(Hstore, numPairsEstimate) + first := true + for !p.atEnd() { + if !first { + err := p.consumePairSeparator() + if err != nil { + return nil, err + } + } else { + first = false + } + + err := p.consumeExpectedByte('"') + if err != nil { + return nil, err + } + + key, err := p.consumeDoubleQuoted() + if err != nil { + return nil, err + } + + err = p.consumeKVSeparator() + if err != nil { + return nil, err + } + + value, err := p.consumeDoubleQuotedOrNull() + if err != nil { + return nil, err + } + if value.Valid { + valueStrings = append(valueStrings, value.String) + result[key] = &valueStrings[len(valueStrings)-1] + } else { + result[key] = nil + } + } + + return result, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/inet.go b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go new file mode 100644 index 0000000..2592a5b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/inet.go @@ -0,0 +1,197 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "errors" + "fmt" + "net/netip" +) + +// Network address family is dependent on server socket.h value for AF_INET. +// In practice, all platforms appear to have the same value. See +// src/include/utils/inet.h for more information. +const ( + defaultAFInet = 2 + defaultAFInet6 = 3 +) + +type NetipPrefixScanner interface { + ScanNetipPrefix(v netip.Prefix) error +} + +type NetipPrefixValuer interface { + NetipPrefixValue() (netip.Prefix, error) +} + +// InetCodec handles both inet and cidr PostgreSQL types. The preferred Go types are [netip.Prefix] and [netip.Addr]. If +// IsValid() is false then they are treated as SQL NULL. +type InetCodec struct{} + +func (InetCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (InetCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (InetCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(NetipPrefixValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanInetCodecBinary{} + case TextFormatCode: + return encodePlanInetCodecText{} + } + + return nil +} + +type encodePlanInetCodecBinary struct{} + +func (encodePlanInetCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + prefix, err := value.(NetipPrefixValuer).NetipPrefixValue() + if err != nil { + return nil, err + } + + if !prefix.IsValid() { + return nil, nil + } + + var family byte + if prefix.Addr().Is4() { + family = defaultAFInet + } else { + family = defaultAFInet6 + } + + buf = append(buf, family) + + ones := prefix.Bits() + buf = append(buf, byte(ones)) + + // is_cidr is ignored on server + buf = append(buf, 0) + + if family == defaultAFInet { + buf = append(buf, byte(4)) + b := prefix.Addr().As4() + buf = append(buf, b[:]...) + } else { + buf = append(buf, byte(16)) + b := prefix.Addr().As16() + buf = append(buf, b[:]...) + } + + return buf, nil +} + +type encodePlanInetCodecText struct{} + +func (encodePlanInetCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + prefix, err := value.(NetipPrefixValuer).NetipPrefixValue() + if err != nil { + return nil, err + } + + if !prefix.IsValid() { + return nil, nil + } + + return append(buf, prefix.String()...), nil +} + +func (InetCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(NetipPrefixScanner); ok { + return scanPlanBinaryInetToNetipPrefixScanner{} + } + case TextFormatCode: + if _, ok := target.(NetipPrefixScanner); ok { + return scanPlanTextAnyToNetipPrefixScanner{} + } + } + + return nil +} + +func (c InetCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c InetCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var prefix netip.Prefix + err := codecScan(c, m, oid, format, src, (*netipPrefixWrapper)(&prefix)) + if err != nil { + return nil, err + } + + if !prefix.IsValid() { + return nil, nil + } + + return prefix, nil +} + +type scanPlanBinaryInetToNetipPrefixScanner struct{} + +func (scanPlanBinaryInetToNetipPrefixScanner) Scan(src []byte, dst any) error { + scanner := (dst).(NetipPrefixScanner) + + if src == nil { + return scanner.ScanNetipPrefix(netip.Prefix{}) + } + + if len(src) != 8 && len(src) != 20 { + return fmt.Errorf("Received an invalid size for an inet: %d", len(src)) + } + + // ignore family + bits := src[1] + // ignore is_cidr + // ignore addressLength - implicit in length of message + + addr, ok := netip.AddrFromSlice(src[4:]) + if !ok { + return errors.New("netip.AddrFromSlice failed") + } + + return scanner.ScanNetipPrefix(netip.PrefixFrom(addr, int(bits))) +} + +type scanPlanTextAnyToNetipPrefixScanner struct{} + +func (scanPlanTextAnyToNetipPrefixScanner) Scan(src []byte, dst any) error { + scanner := (dst).(NetipPrefixScanner) + + if src == nil { + return scanner.ScanNetipPrefix(netip.Prefix{}) + } + + var prefix netip.Prefix + if bytes.IndexByte(src, '/') == -1 { + addr, err := netip.ParseAddr(string(src)) + if err != nil { + return err + } + prefix = netip.PrefixFrom(addr, addr.BitLen()) + } else { + var err error + prefix, err = netip.ParsePrefix(string(src)) + if err != nil { + return err + } + } + + return scanner.ScanNetipPrefix(prefix) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go b/vendor/github.com/jackc/pgx/v5/pgtype/int.go new file mode 100644 index 0000000..95032e5 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int.go @@ -0,0 +1,1990 @@ +// Code generated from pgtype/int.go.erb. DO NOT EDIT. + +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "math" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Int64Scanner interface { + ScanInt64(Int8) error +} + +type Int64Valuer interface { + Int64Value() (Int8, error) +} + +type Int2 struct { + Int16 int16 + Valid bool +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (dst *Int2) ScanInt64(n Int8) error { + if !n.Valid { + *dst = Int2{} + return nil + } + + if n.Int64 < math.MinInt16 { + return fmt.Errorf("%d is less than minimum value for Int2", n.Int64) + } + if n.Int64 > math.MaxInt16 { + return fmt.Errorf("%d is greater than maximum value for Int2", n.Int64) + } + *dst = Int2{Int16: int16(n.Int64), Valid: true} + + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (n Int2) Int64Value() (Int8, error) { + return Int8{Int64: int64(n.Int16), Valid: n.Valid}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Int2) Scan(src any) error { + if src == nil { + *dst = Int2{} + return nil + } + + var n int64 + + switch src := src.(type) { + case int64: + n = src + case string: + var err error + n, err = strconv.ParseInt(src, 10, 16) + if err != nil { + return err + } + case []byte: + var err error + n, err = strconv.ParseInt(string(src), 10, 16) + if err != nil { + return err + } + default: + return fmt.Errorf("cannot scan %T", src) + } + + if n < math.MinInt16 { + return fmt.Errorf("%d is less than minimum value for Int2", n) + } + if n > math.MaxInt16 { + return fmt.Errorf("%d is greater than maximum value for Int2", n) + } + *dst = Int2{Int16: int16(n), Valid: true} + + return nil +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Int2) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + return int64(src.Int16), nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Int2) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + return []byte(strconv.FormatInt(int64(src.Int16), 10)), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Int2) UnmarshalJSON(b []byte) error { + var n *int16 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *dst = Int2{} + } else { + *dst = Int2{Int16: *n, Valid: true} + } + + return nil +} + +type Int2Codec struct{} + +func (Int2Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Int2Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Int2Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case int16: + return encodePlanInt2CodecBinaryInt16{} + case Int64Valuer: + return encodePlanInt2CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case int16: + return encodePlanInt2CodecTextInt16{} + case Int64Valuer: + return encodePlanInt2CodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanInt2CodecBinaryInt16 struct{} + +func (encodePlanInt2CodecBinaryInt16) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int16) + return pgio.AppendInt16(buf, int16(n)), nil +} + +type encodePlanInt2CodecTextInt16 struct{} + +func (encodePlanInt2CodecTextInt16) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int16) + return append(buf, strconv.FormatInt(int64(n), 10)...), nil +} + +type encodePlanInt2CodecBinaryInt64Valuer struct{} + +func (encodePlanInt2CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt16 { + return nil, fmt.Errorf("%d is greater than maximum value for int2", n.Int64) + } + if n.Int64 < math.MinInt16 { + return nil, fmt.Errorf("%d is less than minimum value for int2", n.Int64) + } + + return pgio.AppendInt16(buf, int16(n.Int64)), nil +} + +type encodePlanInt2CodecTextInt64Valuer struct{} + +func (encodePlanInt2CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt16 { + return nil, fmt.Errorf("%d is greater than maximum value for int2", n.Int64) + } + if n.Int64 < math.MinInt16 { + return nil, fmt.Errorf("%d is less than minimum value for int2", n.Int64) + } + + return append(buf, strconv.FormatInt(n.Int64, 10)...), nil +} + +func (Int2Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + + switch format { + case BinaryFormatCode: + switch target.(type) { + case *int8: + return scanPlanBinaryInt2ToInt8{} + case *int16: + return scanPlanBinaryInt2ToInt16{} + case *int32: + return scanPlanBinaryInt2ToInt32{} + case *int64: + return scanPlanBinaryInt2ToInt64{} + case *int: + return scanPlanBinaryInt2ToInt{} + case *uint8: + return scanPlanBinaryInt2ToUint8{} + case *uint16: + return scanPlanBinaryInt2ToUint16{} + case *uint32: + return scanPlanBinaryInt2ToUint32{} + case *uint64: + return scanPlanBinaryInt2ToUint64{} + case *uint: + return scanPlanBinaryInt2ToUint{} + case Int64Scanner: + return scanPlanBinaryInt2ToInt64Scanner{} + case TextScanner: + return scanPlanBinaryInt2ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *int8: + return scanPlanTextAnyToInt8{} + case *int16: + return scanPlanTextAnyToInt16{} + case *int32: + return scanPlanTextAnyToInt32{} + case *int64: + return scanPlanTextAnyToInt64{} + case *int: + return scanPlanTextAnyToInt{} + case *uint8: + return scanPlanTextAnyToUint8{} + case *uint16: + return scanPlanTextAnyToUint16{} + case *uint32: + return scanPlanTextAnyToUint32{} + case *uint64: + return scanPlanTextAnyToUint64{} + case *uint: + return scanPlanTextAnyToUint{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +func (c Int2Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n int64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +func (c Int2Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n int16 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +type scanPlanBinaryInt2ToInt8 struct{} + +func (scanPlanBinaryInt2ToInt8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + p, ok := (dst).(*int8) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int16(binary.BigEndian.Uint16(src)) + if n < math.MinInt8 { + return fmt.Errorf("%d is less than minimum value for int8", n) + } else if n > math.MaxInt8 { + return fmt.Errorf("%d is greater than maximum value for int8", n) + } + + *p = int8(n) + + return nil +} + +type scanPlanBinaryInt2ToUint8 struct{} + +func (scanPlanBinaryInt2ToUint8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for uint2: %v", len(src)) + } + + p, ok := (dst).(*uint8) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int16(binary.BigEndian.Uint16(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint8", n) + } + + if n > math.MaxUint8 { + return fmt.Errorf("%d is greater than maximum value for uint8", n) + } + + *p = uint8(n) + + return nil +} + +type scanPlanBinaryInt2ToInt16 struct{} + +func (scanPlanBinaryInt2ToInt16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + p, ok := (dst).(*int16) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int16(binary.BigEndian.Uint16(src)) + + return nil +} + +type scanPlanBinaryInt2ToUint16 struct{} + +func (scanPlanBinaryInt2ToUint16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for uint2: %v", len(src)) + } + + p, ok := (dst).(*uint16) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int16(binary.BigEndian.Uint16(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint16", n) + } + + *p = uint16(n) + + return nil +} + +type scanPlanBinaryInt2ToInt32 struct{} + +func (scanPlanBinaryInt2ToInt32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + p, ok := (dst).(*int32) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int32(int16(binary.BigEndian.Uint16(src))) + + return nil +} + +type scanPlanBinaryInt2ToUint32 struct{} + +func (scanPlanBinaryInt2ToUint32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for uint2: %v", len(src)) + } + + p, ok := (dst).(*uint32) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int16(binary.BigEndian.Uint16(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint32", n) + } + + *p = uint32(n) + + return nil +} + +type scanPlanBinaryInt2ToInt64 struct{} + +func (scanPlanBinaryInt2ToInt64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + p, ok := (dst).(*int64) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int64(int16(binary.BigEndian.Uint16(src))) + + return nil +} + +type scanPlanBinaryInt2ToUint64 struct{} + +func (scanPlanBinaryInt2ToUint64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for uint2: %v", len(src)) + } + + p, ok := (dst).(*uint64) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int16(binary.BigEndian.Uint16(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint64", n) + } + + *p = uint64(n) + + return nil +} + +type scanPlanBinaryInt2ToInt struct{} + +func (scanPlanBinaryInt2ToInt) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + p, ok := (dst).(*int) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int(int16(binary.BigEndian.Uint16(src))) + + return nil +} + +type scanPlanBinaryInt2ToUint struct{} + +func (scanPlanBinaryInt2ToUint) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for uint2: %v", len(src)) + } + + p, ok := (dst).(*uint) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(int16(binary.BigEndian.Uint16(src))) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint", n) + } + + *p = uint(n) + + return nil +} + +type scanPlanBinaryInt2ToInt64Scanner struct{} + +func (scanPlanBinaryInt2ToInt64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Int64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanInt64(Int8{}) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + n := int64(int16(binary.BigEndian.Uint16(src))) + + return s.ScanInt64(Int8{Int64: n, Valid: true}) +} + +type scanPlanBinaryInt2ToTextScanner struct{} + +func (scanPlanBinaryInt2ToTextScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 2 { + return fmt.Errorf("invalid length for int2: %v", len(src)) + } + + n := int64(int16(binary.BigEndian.Uint16(src))) + + return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) +} + +type Int4 struct { + Int32 int32 + Valid bool +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (dst *Int4) ScanInt64(n Int8) error { + if !n.Valid { + *dst = Int4{} + return nil + } + + if n.Int64 < math.MinInt32 { + return fmt.Errorf("%d is less than minimum value for Int4", n.Int64) + } + if n.Int64 > math.MaxInt32 { + return fmt.Errorf("%d is greater than maximum value for Int4", n.Int64) + } + *dst = Int4{Int32: int32(n.Int64), Valid: true} + + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (n Int4) Int64Value() (Int8, error) { + return Int8{Int64: int64(n.Int32), Valid: n.Valid}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Int4) Scan(src any) error { + if src == nil { + *dst = Int4{} + return nil + } + + var n int64 + + switch src := src.(type) { + case int64: + n = src + case string: + var err error + n, err = strconv.ParseInt(src, 10, 32) + if err != nil { + return err + } + case []byte: + var err error + n, err = strconv.ParseInt(string(src), 10, 32) + if err != nil { + return err + } + default: + return fmt.Errorf("cannot scan %T", src) + } + + if n < math.MinInt32 { + return fmt.Errorf("%d is less than minimum value for Int4", n) + } + if n > math.MaxInt32 { + return fmt.Errorf("%d is greater than maximum value for Int4", n) + } + *dst = Int4{Int32: int32(n), Valid: true} + + return nil +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Int4) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + return int64(src.Int32), nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Int4) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + return []byte(strconv.FormatInt(int64(src.Int32), 10)), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Int4) UnmarshalJSON(b []byte) error { + var n *int32 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *dst = Int4{} + } else { + *dst = Int4{Int32: *n, Valid: true} + } + + return nil +} + +type Int4Codec struct{} + +func (Int4Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Int4Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Int4Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case int32: + return encodePlanInt4CodecBinaryInt32{} + case Int64Valuer: + return encodePlanInt4CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case int32: + return encodePlanInt4CodecTextInt32{} + case Int64Valuer: + return encodePlanInt4CodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanInt4CodecBinaryInt32 struct{} + +func (encodePlanInt4CodecBinaryInt32) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int32) + return pgio.AppendInt32(buf, int32(n)), nil +} + +type encodePlanInt4CodecTextInt32 struct{} + +func (encodePlanInt4CodecTextInt32) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int32) + return append(buf, strconv.FormatInt(int64(n), 10)...), nil +} + +type encodePlanInt4CodecBinaryInt64Valuer struct{} + +func (encodePlanInt4CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt32 { + return nil, fmt.Errorf("%d is greater than maximum value for int4", n.Int64) + } + if n.Int64 < math.MinInt32 { + return nil, fmt.Errorf("%d is less than minimum value for int4", n.Int64) + } + + return pgio.AppendInt32(buf, int32(n.Int64)), nil +} + +type encodePlanInt4CodecTextInt64Valuer struct{} + +func (encodePlanInt4CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt32 { + return nil, fmt.Errorf("%d is greater than maximum value for int4", n.Int64) + } + if n.Int64 < math.MinInt32 { + return nil, fmt.Errorf("%d is less than minimum value for int4", n.Int64) + } + + return append(buf, strconv.FormatInt(n.Int64, 10)...), nil +} + +func (Int4Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + + switch format { + case BinaryFormatCode: + switch target.(type) { + case *int8: + return scanPlanBinaryInt4ToInt8{} + case *int16: + return scanPlanBinaryInt4ToInt16{} + case *int32: + return scanPlanBinaryInt4ToInt32{} + case *int64: + return scanPlanBinaryInt4ToInt64{} + case *int: + return scanPlanBinaryInt4ToInt{} + case *uint8: + return scanPlanBinaryInt4ToUint8{} + case *uint16: + return scanPlanBinaryInt4ToUint16{} + case *uint32: + return scanPlanBinaryInt4ToUint32{} + case *uint64: + return scanPlanBinaryInt4ToUint64{} + case *uint: + return scanPlanBinaryInt4ToUint{} + case Int64Scanner: + return scanPlanBinaryInt4ToInt64Scanner{} + case TextScanner: + return scanPlanBinaryInt4ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *int8: + return scanPlanTextAnyToInt8{} + case *int16: + return scanPlanTextAnyToInt16{} + case *int32: + return scanPlanTextAnyToInt32{} + case *int64: + return scanPlanTextAnyToInt64{} + case *int: + return scanPlanTextAnyToInt{} + case *uint8: + return scanPlanTextAnyToUint8{} + case *uint16: + return scanPlanTextAnyToUint16{} + case *uint32: + return scanPlanTextAnyToUint32{} + case *uint64: + return scanPlanTextAnyToUint64{} + case *uint: + return scanPlanTextAnyToUint{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +func (c Int4Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n int64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +func (c Int4Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n int32 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +type scanPlanBinaryInt4ToInt8 struct{} + +func (scanPlanBinaryInt4ToInt8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + p, ok := (dst).(*int8) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int32(binary.BigEndian.Uint32(src)) + if n < math.MinInt8 { + return fmt.Errorf("%d is less than minimum value for int8", n) + } else if n > math.MaxInt8 { + return fmt.Errorf("%d is greater than maximum value for int8", n) + } + + *p = int8(n) + + return nil +} + +type scanPlanBinaryInt4ToUint8 struct{} + +func (scanPlanBinaryInt4ToUint8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint4: %v", len(src)) + } + + p, ok := (dst).(*uint8) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int32(binary.BigEndian.Uint32(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint8", n) + } + + if n > math.MaxUint8 { + return fmt.Errorf("%d is greater than maximum value for uint8", n) + } + + *p = uint8(n) + + return nil +} + +type scanPlanBinaryInt4ToInt16 struct{} + +func (scanPlanBinaryInt4ToInt16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + p, ok := (dst).(*int16) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int32(binary.BigEndian.Uint32(src)) + if n < math.MinInt16 { + return fmt.Errorf("%d is less than minimum value for int16", n) + } else if n > math.MaxInt16 { + return fmt.Errorf("%d is greater than maximum value for int16", n) + } + + *p = int16(n) + + return nil +} + +type scanPlanBinaryInt4ToUint16 struct{} + +func (scanPlanBinaryInt4ToUint16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint4: %v", len(src)) + } + + p, ok := (dst).(*uint16) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int32(binary.BigEndian.Uint32(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint16", n) + } + + if n > math.MaxUint16 { + return fmt.Errorf("%d is greater than maximum value for uint16", n) + } + + *p = uint16(n) + + return nil +} + +type scanPlanBinaryInt4ToInt32 struct{} + +func (scanPlanBinaryInt4ToInt32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + p, ok := (dst).(*int32) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int32(binary.BigEndian.Uint32(src)) + + return nil +} + +type scanPlanBinaryInt4ToUint32 struct{} + +func (scanPlanBinaryInt4ToUint32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint4: %v", len(src)) + } + + p, ok := (dst).(*uint32) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int32(binary.BigEndian.Uint32(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint32", n) + } + + *p = uint32(n) + + return nil +} + +type scanPlanBinaryInt4ToInt64 struct{} + +func (scanPlanBinaryInt4ToInt64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + p, ok := (dst).(*int64) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int64(int32(binary.BigEndian.Uint32(src))) + + return nil +} + +type scanPlanBinaryInt4ToUint64 struct{} + +func (scanPlanBinaryInt4ToUint64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint4: %v", len(src)) + } + + p, ok := (dst).(*uint64) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int32(binary.BigEndian.Uint32(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint64", n) + } + + *p = uint64(n) + + return nil +} + +type scanPlanBinaryInt4ToInt struct{} + +func (scanPlanBinaryInt4ToInt) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + p, ok := (dst).(*int) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int(int32(binary.BigEndian.Uint32(src))) + + return nil +} + +type scanPlanBinaryInt4ToUint struct{} + +func (scanPlanBinaryInt4ToUint) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint4: %v", len(src)) + } + + p, ok := (dst).(*uint) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(int32(binary.BigEndian.Uint32(src))) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint", n) + } + + *p = uint(n) + + return nil +} + +type scanPlanBinaryInt4ToInt64Scanner struct{} + +func (scanPlanBinaryInt4ToInt64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Int64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanInt64(Int8{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + n := int64(int32(binary.BigEndian.Uint32(src))) + + return s.ScanInt64(Int8{Int64: n, Valid: true}) +} + +type scanPlanBinaryInt4ToTextScanner struct{} + +func (scanPlanBinaryInt4ToTextScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for int4: %v", len(src)) + } + + n := int64(int32(binary.BigEndian.Uint32(src))) + + return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) +} + +type Int8 struct { + Int64 int64 + Valid bool +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (dst *Int8) ScanInt64(n Int8) error { + if !n.Valid { + *dst = Int8{} + return nil + } + + if n.Int64 < math.MinInt64 { + return fmt.Errorf("%d is less than minimum value for Int8", n.Int64) + } + if n.Int64 > math.MaxInt64 { + return fmt.Errorf("%d is greater than maximum value for Int8", n.Int64) + } + *dst = Int8{Int64: int64(n.Int64), Valid: true} + + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (n Int8) Int64Value() (Int8, error) { + return Int8{Int64: int64(n.Int64), Valid: n.Valid}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Int8) Scan(src any) error { + if src == nil { + *dst = Int8{} + return nil + } + + var n int64 + + switch src := src.(type) { + case int64: + n = src + case string: + var err error + n, err = strconv.ParseInt(src, 10, 64) + if err != nil { + return err + } + case []byte: + var err error + n, err = strconv.ParseInt(string(src), 10, 64) + if err != nil { + return err + } + default: + return fmt.Errorf("cannot scan %T", src) + } + + if n < math.MinInt64 { + return fmt.Errorf("%d is greater than maximum value for Int8", n) + } + if n > math.MaxInt64 { + return fmt.Errorf("%d is greater than maximum value for Int8", n) + } + *dst = Int8{Int64: int64(n), Valid: true} + + return nil +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Int8) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + return int64(src.Int64), nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Int8) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + return []byte(strconv.FormatInt(int64(src.Int64), 10)), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Int8) UnmarshalJSON(b []byte) error { + var n *int64 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *dst = Int8{} + } else { + *dst = Int8{Int64: *n, Valid: true} + } + + return nil +} + +type Int8Codec struct{} + +func (Int8Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Int8Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Int8Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case int64: + return encodePlanInt8CodecBinaryInt64{} + case Int64Valuer: + return encodePlanInt8CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case int64: + return encodePlanInt8CodecTextInt64{} + case Int64Valuer: + return encodePlanInt8CodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanInt8CodecBinaryInt64 struct{} + +func (encodePlanInt8CodecBinaryInt64) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int64) + return pgio.AppendInt64(buf, int64(n)), nil +} + +type encodePlanInt8CodecTextInt64 struct{} + +func (encodePlanInt8CodecTextInt64) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int64) + return append(buf, strconv.FormatInt(int64(n), 10)...), nil +} + +type encodePlanInt8CodecBinaryInt64Valuer struct{} + +func (encodePlanInt8CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt64 { + return nil, fmt.Errorf("%d is greater than maximum value for int8", n.Int64) + } + if n.Int64 < math.MinInt64 { + return nil, fmt.Errorf("%d is less than minimum value for int8", n.Int64) + } + + return pgio.AppendInt64(buf, int64(n.Int64)), nil +} + +type encodePlanInt8CodecTextInt64Valuer struct{} + +func (encodePlanInt8CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt64 { + return nil, fmt.Errorf("%d is greater than maximum value for int8", n.Int64) + } + if n.Int64 < math.MinInt64 { + return nil, fmt.Errorf("%d is less than minimum value for int8", n.Int64) + } + + return append(buf, strconv.FormatInt(n.Int64, 10)...), nil +} + +func (Int8Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + + switch format { + case BinaryFormatCode: + switch target.(type) { + case *int8: + return scanPlanBinaryInt8ToInt8{} + case *int16: + return scanPlanBinaryInt8ToInt16{} + case *int32: + return scanPlanBinaryInt8ToInt32{} + case *int64: + return scanPlanBinaryInt8ToInt64{} + case *int: + return scanPlanBinaryInt8ToInt{} + case *uint8: + return scanPlanBinaryInt8ToUint8{} + case *uint16: + return scanPlanBinaryInt8ToUint16{} + case *uint32: + return scanPlanBinaryInt8ToUint32{} + case *uint64: + return scanPlanBinaryInt8ToUint64{} + case *uint: + return scanPlanBinaryInt8ToUint{} + case Int64Scanner: + return scanPlanBinaryInt8ToInt64Scanner{} + case TextScanner: + return scanPlanBinaryInt8ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *int8: + return scanPlanTextAnyToInt8{} + case *int16: + return scanPlanTextAnyToInt16{} + case *int32: + return scanPlanTextAnyToInt32{} + case *int64: + return scanPlanTextAnyToInt64{} + case *int: + return scanPlanTextAnyToInt{} + case *uint8: + return scanPlanTextAnyToUint8{} + case *uint16: + return scanPlanTextAnyToUint16{} + case *uint32: + return scanPlanTextAnyToUint32{} + case *uint64: + return scanPlanTextAnyToUint64{} + case *uint: + return scanPlanTextAnyToUint{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +func (c Int8Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n int64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +func (c Int8Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n int64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +type scanPlanBinaryInt8ToInt8 struct{} + +func (scanPlanBinaryInt8ToInt8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + p, ok := (dst).(*int8) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < math.MinInt8 { + return fmt.Errorf("%d is less than minimum value for int8", n) + } else if n > math.MaxInt8 { + return fmt.Errorf("%d is greater than maximum value for int8", n) + } + + *p = int8(n) + + return nil +} + +type scanPlanBinaryInt8ToUint8 struct{} + +func (scanPlanBinaryInt8ToUint8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint8: %v", len(src)) + } + + p, ok := (dst).(*uint8) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint8", n) + } + + if n > math.MaxUint8 { + return fmt.Errorf("%d is greater than maximum value for uint8", n) + } + + *p = uint8(n) + + return nil +} + +type scanPlanBinaryInt8ToInt16 struct{} + +func (scanPlanBinaryInt8ToInt16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + p, ok := (dst).(*int16) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < math.MinInt16 { + return fmt.Errorf("%d is less than minimum value for int16", n) + } else if n > math.MaxInt16 { + return fmt.Errorf("%d is greater than maximum value for int16", n) + } + + *p = int16(n) + + return nil +} + +type scanPlanBinaryInt8ToUint16 struct{} + +func (scanPlanBinaryInt8ToUint16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint8: %v", len(src)) + } + + p, ok := (dst).(*uint16) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint16", n) + } + + if n > math.MaxUint16 { + return fmt.Errorf("%d is greater than maximum value for uint16", n) + } + + *p = uint16(n) + + return nil +} + +type scanPlanBinaryInt8ToInt32 struct{} + +func (scanPlanBinaryInt8ToInt32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + p, ok := (dst).(*int32) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < math.MinInt32 { + return fmt.Errorf("%d is less than minimum value for int32", n) + } else if n > math.MaxInt32 { + return fmt.Errorf("%d is greater than maximum value for int32", n) + } + + *p = int32(n) + + return nil +} + +type scanPlanBinaryInt8ToUint32 struct{} + +func (scanPlanBinaryInt8ToUint32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint8: %v", len(src)) + } + + p, ok := (dst).(*uint32) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint32", n) + } + + if n > math.MaxUint32 { + return fmt.Errorf("%d is greater than maximum value for uint32", n) + } + + *p = uint32(n) + + return nil +} + +type scanPlanBinaryInt8ToInt64 struct{} + +func (scanPlanBinaryInt8ToInt64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + p, ok := (dst).(*int64) + if !ok { + return ErrScanTargetTypeChanged + } + + *p = int64(binary.BigEndian.Uint64(src)) + + return nil +} + +type scanPlanBinaryInt8ToUint64 struct{} + +func (scanPlanBinaryInt8ToUint64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint8: %v", len(src)) + } + + p, ok := (dst).(*uint64) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint64", n) + } + + *p = uint64(n) + + return nil +} + +type scanPlanBinaryInt8ToInt struct{} + +func (scanPlanBinaryInt8ToInt) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + p, ok := (dst).(*int) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(binary.BigEndian.Uint64(src)) + if n < math.MinInt { + return fmt.Errorf("%d is less than minimum value for int", n) + } else if n > math.MaxInt { + return fmt.Errorf("%d is greater than maximum value for int", n) + } + + *p = int(n) + + return nil +} + +type scanPlanBinaryInt8ToUint struct{} + +func (scanPlanBinaryInt8ToUint) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint8: %v", len(src)) + } + + p, ok := (dst).(*uint) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(int64(binary.BigEndian.Uint64(src))) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint", n) + } + + if uint64(n) > math.MaxUint { + return fmt.Errorf("%d is greater than maximum value for uint", n) + } + + *p = uint(n) + + return nil +} + +type scanPlanBinaryInt8ToInt64Scanner struct{} + +func (scanPlanBinaryInt8ToInt64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Int64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanInt64(Int8{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + n := int64(int64(binary.BigEndian.Uint64(src))) + + return s.ScanInt64(Int8{Int64: n, Valid: true}) +} + +type scanPlanBinaryInt8ToTextScanner struct{} + +func (scanPlanBinaryInt8ToTextScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for int8: %v", len(src)) + } + + n := int64(int64(binary.BigEndian.Uint64(src))) + + return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) +} + +type scanPlanTextAnyToInt8 struct{} + +func (scanPlanTextAnyToInt8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*int8) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseInt(string(src), 10, 8) + if err != nil { + return err + } + + *p = int8(n) + return nil +} + +type scanPlanTextAnyToUint8 struct{} + +func (scanPlanTextAnyToUint8) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*uint8) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseUint(string(src), 10, 8) + if err != nil { + return err + } + + *p = uint8(n) + return nil +} + +type scanPlanTextAnyToInt16 struct{} + +func (scanPlanTextAnyToInt16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*int16) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseInt(string(src), 10, 16) + if err != nil { + return err + } + + *p = int16(n) + return nil +} + +type scanPlanTextAnyToUint16 struct{} + +func (scanPlanTextAnyToUint16) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*uint16) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseUint(string(src), 10, 16) + if err != nil { + return err + } + + *p = uint16(n) + return nil +} + +type scanPlanTextAnyToInt32 struct{} + +func (scanPlanTextAnyToInt32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*int32) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseInt(string(src), 10, 32) + if err != nil { + return err + } + + *p = int32(n) + return nil +} + +type scanPlanTextAnyToUint32 struct{} + +func (scanPlanTextAnyToUint32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*uint32) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseUint(string(src), 10, 32) + if err != nil { + return err + } + + *p = uint32(n) + return nil +} + +type scanPlanTextAnyToInt64 struct{} + +func (scanPlanTextAnyToInt64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*int64) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseInt(string(src), 10, 64) + if err != nil { + return err + } + + *p = int64(n) + return nil +} + +type scanPlanTextAnyToUint64 struct{} + +func (scanPlanTextAnyToUint64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*uint64) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseUint(string(src), 10, 64) + if err != nil { + return err + } + + *p = uint64(n) + return nil +} + +type scanPlanTextAnyToInt struct{} + +func (scanPlanTextAnyToInt) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*int) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseInt(string(src), 10, 0) + if err != nil { + return err + } + + *p = int(n) + return nil +} + +type scanPlanTextAnyToUint struct{} + +func (scanPlanTextAnyToUint) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*uint) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseUint(string(src), 10, 0) + if err != nil { + return err + } + + *p = uint(n) + return nil +} + +type scanPlanTextAnyToInt64Scanner struct{} + +func (scanPlanTextAnyToInt64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Int64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanInt64(Int8{}) + } + + n, err := strconv.ParseInt(string(src), 10, 64) + if err != nil { + return err + } + + err = s.ScanInt64(Int8{Int64: n, Valid: true}) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb new file mode 100644 index 0000000..c2d40f6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int.go.erb @@ -0,0 +1,551 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "math" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Int64Scanner interface { + ScanInt64(Int8) error +} + +type Int64Valuer interface { + Int64Value() (Int8, error) +} + + +<% [2, 4, 8].each do |pg_byte_size| %> +<% pg_bit_size = pg_byte_size * 8 %> +type Int<%= pg_byte_size %> struct { + Int<%= pg_bit_size %> int<%= pg_bit_size %> + Valid bool +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (dst *Int<%= pg_byte_size %>) ScanInt64(n Int8) error { + if !n.Valid { + *dst = Int<%= pg_byte_size %>{} + return nil + } + + if n.Int64 < math.MinInt<%= pg_bit_size %> { + return fmt.Errorf("%d is less than minimum value for Int<%= pg_byte_size %>", n.Int64) + } + if n.Int64 > math.MaxInt<%= pg_bit_size %> { + return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n.Int64) + } + *dst = Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: int<%= pg_bit_size %>(n.Int64), Valid: true} + + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (n Int<%= pg_byte_size %>) Int64Value() (Int8, error) { + return Int8{Int64: int64(n.Int<%= pg_bit_size %>), Valid: n.Valid}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Int<%= pg_byte_size %>) Scan(src any) error { + if src == nil { + *dst = Int<%= pg_byte_size %>{} + return nil + } + + var n int64 + + switch src := src.(type) { + case int64: + n = src + case string: + var err error + n, err = strconv.ParseInt(src, 10, <%= pg_bit_size %>) + if err != nil { + return err + } + case []byte: + var err error + n, err = strconv.ParseInt(string(src), 10, <%= pg_bit_size %>) + if err != nil { + return err + } + default: + return fmt.Errorf("cannot scan %T", src) + } + + if n < math.MinInt<%= pg_bit_size %> { + return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) + } + if n > math.MaxInt<%= pg_bit_size %> { + return fmt.Errorf("%d is greater than maximum value for Int<%= pg_byte_size %>", n) + } + *dst = Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: int<%= pg_bit_size %>(n), Valid: true} + + return nil +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Int<%= pg_byte_size %>) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + return int64(src.Int<%= pg_bit_size %>), nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Int<%= pg_byte_size %>) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + return []byte(strconv.FormatInt(int64(src.Int<%= pg_bit_size %>), 10)), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Int<%= pg_byte_size %>) UnmarshalJSON(b []byte) error { + var n *int<%= pg_bit_size %> + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *dst = Int<%= pg_byte_size %>{} + } else { + *dst = Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: *n, Valid: true} + } + + return nil +} + +type Int<%= pg_byte_size %>Codec struct{} + +func (Int<%= pg_byte_size %>Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Int<%= pg_byte_size %>Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Int<%= pg_byte_size %>Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case int<%= pg_bit_size %>: + return encodePlanInt<%= pg_byte_size %>CodecBinaryInt<%= pg_bit_size %>{} + case Int64Valuer: + return encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case int<%= pg_bit_size %>: + return encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %>{} + case Int64Valuer: + return encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanInt<%= pg_byte_size %>CodecBinaryInt<%= pg_bit_size %> struct{} + +func (encodePlanInt<%= pg_byte_size %>CodecBinaryInt<%= pg_bit_size %>) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int<%= pg_bit_size %>) + return pgio.AppendInt<%= pg_bit_size %>(buf, int<%= pg_bit_size %>(n)), nil +} + +type encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %> struct{} + +func (encodePlanInt<%= pg_byte_size %>CodecTextInt<%= pg_bit_size %>) Encode(value any, buf []byte) (newBuf []byte, err error) { + n := value.(int<%= pg_bit_size %>) + return append(buf, strconv.FormatInt(int64(n), 10)...), nil +} + +type encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer struct{} + +func (encodePlanInt<%= pg_byte_size %>CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt<%= pg_bit_size %> { + return nil, fmt.Errorf("%d is greater than maximum value for int<%= pg_byte_size %>", n.Int64) + } + if n.Int64 < math.MinInt<%= pg_bit_size %> { + return nil, fmt.Errorf("%d is less than minimum value for int<%= pg_byte_size %>", n.Int64) + } + + return pgio.AppendInt<%= pg_bit_size %>(buf, int<%= pg_bit_size %>(n.Int64)), nil +} + +type encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer struct{} + +func (encodePlanInt<%= pg_byte_size %>CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + if n.Int64 > math.MaxInt<%= pg_bit_size %> { + return nil, fmt.Errorf("%d is greater than maximum value for int<%= pg_byte_size %>", n.Int64) + } + if n.Int64 < math.MinInt<%= pg_bit_size %> { + return nil, fmt.Errorf("%d is less than minimum value for int<%= pg_byte_size %>", n.Int64) + } + + return append(buf, strconv.FormatInt(n.Int64, 10)...), nil +} + +func (Int<%= pg_byte_size %>Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + + switch format { + case BinaryFormatCode: + switch target.(type) { + case *int8: + return scanPlanBinaryInt<%= pg_byte_size %>ToInt8{} + case *int16: + return scanPlanBinaryInt<%= pg_byte_size %>ToInt16{} + case *int32: + return scanPlanBinaryInt<%= pg_byte_size %>ToInt32{} + case *int64: + return scanPlanBinaryInt<%= pg_byte_size %>ToInt64{} + case *int: + return scanPlanBinaryInt<%= pg_byte_size %>ToInt{} + case *uint8: + return scanPlanBinaryInt<%= pg_byte_size %>ToUint8{} + case *uint16: + return scanPlanBinaryInt<%= pg_byte_size %>ToUint16{} + case *uint32: + return scanPlanBinaryInt<%= pg_byte_size %>ToUint32{} + case *uint64: + return scanPlanBinaryInt<%= pg_byte_size %>ToUint64{} + case *uint: + return scanPlanBinaryInt<%= pg_byte_size %>ToUint{} + case Int64Scanner: + return scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner{} + case TextScanner: + return scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *int8: + return scanPlanTextAnyToInt8{} + case *int16: + return scanPlanTextAnyToInt16{} + case *int32: + return scanPlanTextAnyToInt32{} + case *int64: + return scanPlanTextAnyToInt64{} + case *int: + return scanPlanTextAnyToInt{} + case *uint8: + return scanPlanTextAnyToUint8{} + case *uint16: + return scanPlanTextAnyToUint16{} + case *uint32: + return scanPlanTextAnyToUint32{} + case *uint64: + return scanPlanTextAnyToUint64{} + case *uint: + return scanPlanTextAnyToUint{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +func (c Int<%= pg_byte_size %>Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n int64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +func (c Int<%= pg_byte_size %>Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n int<%= pg_bit_size %> + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +<%# PostgreSQL binary format integer to fixed size Go integers %> +<% [8, 16, 32, 64].each do |dst_bit_size| %> +type scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %> struct{} + +func (scanPlanBinaryInt<%= pg_byte_size %>ToInt<%= dst_bit_size %>) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != <%= pg_byte_size %> { + return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + } + + p, ok := (dst).(*int<%= dst_bit_size %>) + if !ok { + return ErrScanTargetTypeChanged + } + + <% if dst_bit_size < pg_bit_size %> + n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + if n < math.MinInt<%= dst_bit_size %> { + return fmt.Errorf("%d is less than minimum value for int<%= dst_bit_size %>", n) + } else if n > math.MaxInt<%= dst_bit_size %> { + return fmt.Errorf("%d is greater than maximum value for int<%= dst_bit_size %>", n) + } + + *p = int<%= dst_bit_size %>(n) + <% elsif dst_bit_size == pg_bit_size %> + *p = int<%= dst_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + <% else %> + *p = int<%= dst_bit_size %>(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + <% end %> + + return nil +} + +type scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %> struct{} + +func (scanPlanBinaryInt<%= pg_byte_size %>ToUint<%= dst_bit_size %>) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != <%= pg_byte_size %> { + return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) + } + + p, ok := (dst).(*uint<%= dst_bit_size %>) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint<%= dst_bit_size %>", n) + } + <% if dst_bit_size < pg_bit_size %> + if n > math.MaxUint<%= dst_bit_size %> { + return fmt.Errorf("%d is greater than maximum value for uint<%= dst_bit_size %>", n) + } + <% end %> + *p = uint<%= dst_bit_size %>(n) + + return nil +} +<% end %> + +<%# PostgreSQL binary format integer to Go machine integers %> +type scanPlanBinaryInt<%= pg_byte_size %>ToInt struct{} + +func (scanPlanBinaryInt<%= pg_byte_size %>ToInt) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != <%= pg_byte_size %> { + return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + } + + p, ok := (dst).(*int) + if !ok { + return ErrScanTargetTypeChanged + } + + <% if 32 < pg_bit_size %> + n := int64(binary.BigEndian.Uint<%= pg_bit_size %>(src)) + if n < math.MinInt { + return fmt.Errorf("%d is less than minimum value for int", n) + } else if n > math.MaxInt { + return fmt.Errorf("%d is greater than maximum value for int", n) + } + + *p = int(n) + <% else %> + *p = int(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + <% end %> + + return nil +} + +type scanPlanBinaryInt<%= pg_byte_size %>ToUint struct{} + +func (scanPlanBinaryInt<%= pg_byte_size %>ToUint) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != <%= pg_byte_size %> { + return fmt.Errorf("invalid length for uint<%= pg_byte_size %>: %v", len(src)) + } + + p, ok := (dst).(*uint) + if !ok { + return ErrScanTargetTypeChanged + } + + n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + if n < 0 { + return fmt.Errorf("%d is less than minimum value for uint", n) + } + <% if 32 < pg_bit_size %> + if uint64(n) > math.MaxUint { + return fmt.Errorf("%d is greater than maximum value for uint", n) + } + <% end %> + *p = uint(n) + + return nil +} + +<%# PostgreSQL binary format integer to Go Int64Scanner %> +type scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner struct{} + +func (scanPlanBinaryInt<%= pg_byte_size %>ToInt64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Int64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanInt64(Int8{}) + } + + if len(src) != <%= pg_byte_size %> { + return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + } + + + n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + + return s.ScanInt64(Int8{Int64: n, Valid: true}) +} + +<%# PostgreSQL binary format integer to Go TextScanner %> +type scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner struct{} + +func (scanPlanBinaryInt<%= pg_byte_size %>ToTextScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != <%= pg_byte_size %> { + return fmt.Errorf("invalid length for int<%= pg_byte_size %>: %v", len(src)) + } + + + n := int64(int<%= pg_bit_size %>(binary.BigEndian.Uint<%= pg_bit_size %>(src))) + + return s.ScanText(Text{String: strconv.FormatInt(n, 10), Valid: true}) +} +<% end %> + +<%# Any text to all integer types %> +<% [ + ["8", 8], + ["16", 16], + ["32", 32], + ["64", 64], + ["", 0] +].each do |type_suffix, bit_size| %> +type scanPlanTextAnyToInt<%= type_suffix %> struct{} + +func (scanPlanTextAnyToInt<%= type_suffix %>) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*int<%= type_suffix %>) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseInt(string(src), 10, <%= bit_size %>) + if err != nil { + return err + } + + *p = int<%= type_suffix %>(n) + return nil +} + +type scanPlanTextAnyToUint<%= type_suffix %> struct{} + +func (scanPlanTextAnyToUint<%= type_suffix %>) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p, ok := (dst).(*uint<%= type_suffix %>) + if !ok { + return ErrScanTargetTypeChanged + } + + n, err := strconv.ParseUint(string(src), 10, <%= bit_size %>) + if err != nil { + return err + } + + *p = uint<%= type_suffix %>(n) + return nil +} +<% end %> + +type scanPlanTextAnyToInt64Scanner struct{} + +func (scanPlanTextAnyToInt64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Int64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanInt64(Int8{}) + } + + n, err := strconv.ParseInt(string(src), 10, 64) + if err != nil { + return err + } + + err = s.ScanInt64(Int8{Int64: n, Valid: true}) + if err != nil { + return err + } + + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb new file mode 100644 index 0000000..ac9a3f1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/int_test.go.erb @@ -0,0 +1,93 @@ +package pgtype_test + +import ( + "math" + "testing" + + "github.com/jackc/pgx/v5/pgtype" +) + +<% [2, 4, 8].each do |pg_byte_size| %> +<% pg_bit_size = pg_byte_size * 8 %> +func TestInt<%= pg_byte_size %>Codec(t *testing.T) { + pgxtest.RunValueRoundTripTests(context.Background(), t, defaultConnTestRunner, nil, "int<%= pg_byte_size %>", []pgxtest.ValueRoundTripTest{ + {int8(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {int16(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {int32(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {int64(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {uint8(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {uint16(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {uint32(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {uint64(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {int(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {uint(1), new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true}, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {int32(-1), new(pgtype.Int<%= pg_byte_size %>), isExpectedEq(pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: -1, Valid: true})}, + {1, new(int8), isExpectedEq(int8(1))}, + {1, new(int16), isExpectedEq(int16(1))}, + {1, new(int32), isExpectedEq(int32(1))}, + {1, new(int64), isExpectedEq(int64(1))}, + {1, new(uint8), isExpectedEq(uint8(1))}, + {1, new(uint16), isExpectedEq(uint16(1))}, + {1, new(uint32), isExpectedEq(uint32(1))}, + {1, new(uint64), isExpectedEq(uint64(1))}, + {1, new(int), isExpectedEq(int(1))}, + {1, new(uint), isExpectedEq(uint(1))}, + {-1, new(int8), isExpectedEq(int8(-1))}, + {-1, new(int16), isExpectedEq(int16(-1))}, + {-1, new(int32), isExpectedEq(int32(-1))}, + {-1, new(int64), isExpectedEq(int64(-1))}, + {-1, new(int), isExpectedEq(int(-1))}, + {math.MinInt<%= pg_bit_size %>, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(math.MinInt<%= pg_bit_size %>))}, + {-1, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(-1))}, + {0, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(0))}, + {1, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(1))}, + {math.MaxInt<%= pg_bit_size %>, new(int<%= pg_bit_size %>), isExpectedEq(int<%= pg_bit_size %>(math.MaxInt<%= pg_bit_size %>))}, + {1, new(pgtype.Int<%= pg_byte_size %>), isExpectedEq(pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true})}, + {"1", new(string), isExpectedEq("1")}, + {pgtype.Int<%= pg_byte_size %>{}, new(pgtype.Int<%= pg_byte_size %>), isExpectedEq(pgtype.Int<%= pg_byte_size %>{})}, + {nil, new(*int<%= pg_bit_size %>), isExpectedEq((*int<%= pg_bit_size %>)(nil))}, + }) +} + +func TestInt<%= pg_byte_size %>MarshalJSON(t *testing.T) { + successfulTests := []struct { + source pgtype.Int<%= pg_byte_size %> + result string + }{ + {source: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 0}, result: "null"}, + {source: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true}, result: "1"}, + } + for i, tt := range successfulTests { + r, err := tt.source.MarshalJSON() + if err != nil { + t.Errorf("%d: %v", i, err) + } + + if string(r) != tt.result { + t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, string(r)) + } + } +} + +func TestInt<%= pg_byte_size %>UnmarshalJSON(t *testing.T) { + successfulTests := []struct { + source string + result pgtype.Int<%= pg_byte_size %> + }{ + {source: "null", result: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 0}}, + {source: "1", result: pgtype.Int<%= pg_byte_size %>{Int<%= pg_bit_size %>: 1, Valid: true}}, + } + for i, tt := range successfulTests { + var r pgtype.Int<%= pg_byte_size %> + err := r.UnmarshalJSON([]byte(tt.source)) + if err != nil { + t.Errorf("%d: %v", i, err) + } + + if r != tt.result { + t.Errorf("%d: expected %v to convert to %v, but it was %v", i, tt.source, tt.result, r) + } + } +} +<% end %> diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb b/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb new file mode 100644 index 0000000..6f40115 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test.go.erb @@ -0,0 +1,62 @@ +package pgtype_test + +import ( + "context" + "testing" + + "github.com/jackc/pgx/v5/pgtype/testutil" + "github.com/jackc/pgx/v5" +) + +<% + [ + ["int4", ["int16", "int32", "int64", "uint64", "pgtype.Int4"], [[1, 1], [1, 10], [10, 1], [100, 10]]], + ["numeric", ["int64", "float64", "pgtype.Numeric"], [[1, 1], [1, 10], [10, 1], [100, 10]]], + ].each do |pg_type, go_types, rows_columns| +%> +<% go_types.each do |go_type| %> +<% rows_columns.each do |rows, columns| %> +<% [["Text", "pgx.TextFormatCode"], ["Binary", "pgx.BinaryFormatCode"]].each do |format_name, format_code| %> +func BenchmarkQuery<%= format_name %>FormatDecode_PG_<%= pg_type %>_to_Go_<%= go_type.gsub(/\W/, "_") %>_<%= rows %>_rows_<%= columns %>_columns(b *testing.B) { + defaultConnTestRunner.RunTest(context.Background(), b, func(ctx context.Context, _ testing.TB, conn *pgx.Conn) { + b.ResetTimer() + var v [<%= columns %>]<%= go_type %> + for i := 0; i < b.N; i++ { + rows, _ := conn.Query( + ctx, + `select <% columns.times do |col_idx| %><% if col_idx != 0 %>, <% end %>n::<%= pg_type %> + <%= col_idx%><% end %> from generate_series(1, <%= rows %>) n`, + pgx.QueryResultFormats{<%= format_code %>}, + ) + _, err := pgx.ForEachRow(rows, []any{<% columns.times do |col_idx| %><% if col_idx != 0 %>, <% end %>&v[<%= col_idx%>]<% end %>}, func() error { return nil }) + if err != nil { + b.Fatal(err) + } + } + }) +} +<% end %> +<% end %> +<% end %> +<% end %> + +<% [10, 100, 1000].each do |array_size| %> +<% [["Text", "pgx.TextFormatCode"], ["Binary", "pgx.BinaryFormatCode"]].each do |format_name, format_code| %> +func BenchmarkQuery<%= format_name %>FormatDecode_PG_Int4Array_With_Go_Int4Array_<%= array_size %>(b *testing.B) { + defaultConnTestRunner.RunTest(context.Background(), b, func(ctx context.Context, _ testing.TB, conn *pgx.Conn) { + b.ResetTimer() + var v []int32 + for i := 0; i < b.N; i++ { + rows, _ := conn.Query( + ctx, + `select array_agg(n) from generate_series(1, <%= array_size %>) n`, + pgx.QueryResultFormats{<%= format_code %>}, + ) + _, err := pgx.ForEachRow(rows, []any{&v}, func() error { return nil }) + if err != nil { + b.Fatal(err) + } + } + }) +} +<% end %> +<% end %> diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh b/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh new file mode 100644 index 0000000..22ac01a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/integration_benchmark_test_gen.sh @@ -0,0 +1,2 @@ +erb integration_benchmark_test.go.erb > integration_benchmark_test.go +goimports -w integration_benchmark_test.go diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/interval.go b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go new file mode 100644 index 0000000..be8decd --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/interval.go @@ -0,0 +1,297 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const ( + microsecondsPerSecond = 1_000_000 + microsecondsPerMinute = 60 * microsecondsPerSecond + microsecondsPerHour = 60 * microsecondsPerMinute + microsecondsPerDay = 24 * microsecondsPerHour + microsecondsPerMonth = 30 * microsecondsPerDay +) + +type IntervalScanner interface { + ScanInterval(v Interval) error +} + +type IntervalValuer interface { + IntervalValue() (Interval, error) +} + +type Interval struct { + Microseconds int64 + Days int32 + Months int32 + Valid bool +} + +// ScanInterval implements the [IntervalScanner] interface. +func (interval *Interval) ScanInterval(v Interval) error { + *interval = v + return nil +} + +// IntervalValue implements the [IntervalValuer] interface. +func (interval Interval) IntervalValue() (Interval, error) { + return interval, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (interval *Interval) Scan(src any) error { + if src == nil { + *interval = Interval{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToIntervalScanner{}.Scan([]byte(src), interval) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (interval Interval) Value() (driver.Value, error) { + if !interval.Valid { + return nil, nil + } + + buf, err := IntervalCodec{}.PlanEncode(nil, 0, TextFormatCode, interval).Encode(interval, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type IntervalCodec struct{} + +func (IntervalCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (IntervalCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (IntervalCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(IntervalValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanIntervalCodecBinary{} + case TextFormatCode: + return encodePlanIntervalCodecText{} + } + + return nil +} + +type encodePlanIntervalCodecBinary struct{} + +func (encodePlanIntervalCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + interval, err := value.(IntervalValuer).IntervalValue() + if err != nil { + return nil, err + } + + if !interval.Valid { + return nil, nil + } + + buf = pgio.AppendInt64(buf, interval.Microseconds) + buf = pgio.AppendInt32(buf, interval.Days) + buf = pgio.AppendInt32(buf, interval.Months) + return buf, nil +} + +type encodePlanIntervalCodecText struct{} + +func (encodePlanIntervalCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + interval, err := value.(IntervalValuer).IntervalValue() + if err != nil { + return nil, err + } + + if !interval.Valid { + return nil, nil + } + + if interval.Months != 0 { + buf = append(buf, strconv.FormatInt(int64(interval.Months), 10)...) + buf = append(buf, " mon "...) + } + + if interval.Days != 0 { + buf = append(buf, strconv.FormatInt(int64(interval.Days), 10)...) + buf = append(buf, " day "...) + } + + absMicroseconds := interval.Microseconds + if absMicroseconds < 0 { + absMicroseconds = -absMicroseconds + buf = append(buf, '-') + } + + hours := absMicroseconds / microsecondsPerHour + minutes := (absMicroseconds % microsecondsPerHour) / microsecondsPerMinute + seconds := (absMicroseconds % microsecondsPerMinute) / microsecondsPerSecond + + timeStr := fmt.Sprintf("%02d:%02d:%02d", hours, minutes, seconds) + buf = append(buf, timeStr...) + + microseconds := absMicroseconds % microsecondsPerSecond + if microseconds != 0 { + buf = append(buf, fmt.Sprintf(".%06d", microseconds)...) + } + + return buf, nil +} + +func (IntervalCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(IntervalScanner); ok { + return scanPlanBinaryIntervalToIntervalScanner{} + } + case TextFormatCode: + if _, ok := target.(IntervalScanner); ok { + return scanPlanTextAnyToIntervalScanner{} + } + } + + return nil +} + +type scanPlanBinaryIntervalToIntervalScanner struct{} + +func (scanPlanBinaryIntervalToIntervalScanner) Scan(src []byte, dst any) error { + scanner := (dst).(IntervalScanner) + + if src == nil { + return scanner.ScanInterval(Interval{}) + } + + if len(src) != 16 { + return fmt.Errorf("Received an invalid size for an interval: %d", len(src)) + } + + microseconds := int64(binary.BigEndian.Uint64(src)) + days := int32(binary.BigEndian.Uint32(src[8:])) + months := int32(binary.BigEndian.Uint32(src[12:])) + + return scanner.ScanInterval(Interval{Microseconds: microseconds, Days: days, Months: months, Valid: true}) +} + +type scanPlanTextAnyToIntervalScanner struct{} + +func (scanPlanTextAnyToIntervalScanner) Scan(src []byte, dst any) error { + scanner := (dst).(IntervalScanner) + + if src == nil { + return scanner.ScanInterval(Interval{}) + } + + var microseconds int64 + var days int32 + var months int32 + + parts := strings.Split(string(src), " ") + + for i := 0; i < len(parts)-1; i += 2 { + scalar, err := strconv.ParseInt(parts[i], 10, 64) + if err != nil { + return fmt.Errorf("bad interval format") + } + + switch parts[i+1] { + case "year", "years": + months += int32(scalar * 12) + case "mon", "mons": + months += int32(scalar) + case "day", "days": + days = int32(scalar) + default: + return fmt.Errorf("bad interval format: %q", parts[i+1]) + } + } + + if len(parts)%2 == 1 { + timeParts := strings.SplitN(parts[len(parts)-1], ":", 3) + if len(timeParts) != 3 { + return fmt.Errorf("bad interval format") + } + + var negative bool + if timeParts[0][0] == '-' { + negative = true + timeParts[0] = timeParts[0][1:] + } + + hours, err := strconv.ParseInt(timeParts[0], 10, 64) + if err != nil { + return fmt.Errorf("bad interval hour format: %s", timeParts[0]) + } + + minutes, err := strconv.ParseInt(timeParts[1], 10, 64) + if err != nil { + return fmt.Errorf("bad interval minute format: %s", timeParts[1]) + } + + sec, secFrac, secFracFound := strings.Cut(timeParts[2], ".") + + seconds, err := strconv.ParseInt(sec, 10, 64) + if err != nil { + return fmt.Errorf("bad interval second format: %s", sec) + } + + var uSeconds int64 + if secFracFound { + uSeconds, err = strconv.ParseInt(secFrac, 10, 64) + if err != nil { + return fmt.Errorf("bad interval decimal format: %s", secFrac) + } + + for i := 0; i < 6-len(secFrac); i++ { + uSeconds *= 10 + } + } + + microseconds = hours * microsecondsPerHour + microseconds += minutes * microsecondsPerMinute + microseconds += seconds * microsecondsPerSecond + microseconds += uSeconds + + if negative { + microseconds = -microseconds + } + } + + return scanner.ScanInterval(Interval{Months: months, Days: days, Microseconds: microseconds, Valid: true}) +} + +func (c IntervalCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c IntervalCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var interval Interval + err := codecScan(c, m, oid, format, src, &interval) + if err != nil { + return nil, err + } + return interval, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/json.go b/vendor/github.com/jackc/pgx/v5/pgtype/json.go new file mode 100644 index 0000000..a5f74ea --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/json.go @@ -0,0 +1,243 @@ +package pgtype + +import ( + "database/sql" + "database/sql/driver" + "encoding/json" + "fmt" + "reflect" +) + +type JSONCodec struct { + Marshal func(v any) ([]byte, error) + Unmarshal func(data []byte, v any) error +} + +func (*JSONCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (*JSONCodec) PreferredFormat() int16 { + return TextFormatCode +} + +func (c *JSONCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch value.(type) { + case string: + return encodePlanJSONCodecEitherFormatString{} + case []byte: + return encodePlanJSONCodecEitherFormatByteSlice{} + + // Handle json.RawMessage specifically because if it is run through json.Marshal it may be mutated. + // e.g. `{"foo": "bar"}` -> `{"foo":"bar"}`. + case json.RawMessage: + return encodePlanJSONCodecEitherFormatJSONRawMessage{} + + // Cannot rely on driver.Valuer being handled later because anything can be marshalled. + // + // https://github.com/jackc/pgx/issues/1430 + // + // Check for driver.Valuer must come before json.Marshaler so that it is guaranteed to be used + // when both are implemented https://github.com/jackc/pgx/issues/1805 + case driver.Valuer: + return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} + + // Must come before trying wrap encode plans because a pointer to a struct may be unwrapped to a struct that can be + // marshalled. + // + // https://github.com/jackc/pgx/issues/1681 + case json.Marshaler: + return &encodePlanJSONCodecEitherFormatMarshal{ + marshal: c.Marshal, + } + } + + // Because anything can be marshalled the normal wrapping in Map.PlanScan doesn't get a chance to run. So try the + // appropriate wrappers here. + for _, f := range []TryWrapEncodePlanFunc{ + TryWrapDerefPointerEncodePlan, + TryWrapFindUnderlyingTypeEncodePlan, + } { + if wrapperPlan, nextValue, ok := f(value); ok { + if nextPlan := c.PlanEncode(m, oid, format, nextValue); nextPlan != nil { + wrapperPlan.SetNext(nextPlan) + return wrapperPlan + } + } + } + + return &encodePlanJSONCodecEitherFormatMarshal{ + marshal: c.Marshal, + } +} + +// JSON needs its on scan plan for pointers to handle 'null'::json(b). +// Consider making pointerPointerScanPlan more flexible in the future. +type jsonPointerScanPlan struct { + next ScanPlan +} + +func (p jsonPointerScanPlan) Scan(src []byte, dst any) error { + el := reflect.ValueOf(dst).Elem() + if src == nil || string(src) == "null" { + el.SetZero() + return nil + } + + el.Set(reflect.New(el.Type().Elem())) + if p.next != nil { + return p.next.Scan(src, el.Interface()) + } + + return nil +} + +type encodePlanJSONCodecEitherFormatString struct{} + +func (encodePlanJSONCodecEitherFormatString) Encode(value any, buf []byte) (newBuf []byte, err error) { + jsonString := value.(string) + buf = append(buf, jsonString...) + return buf, nil +} + +type encodePlanJSONCodecEitherFormatByteSlice struct{} + +func (encodePlanJSONCodecEitherFormatByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { + jsonBytes := value.([]byte) + if jsonBytes == nil { + return nil, nil + } + + buf = append(buf, jsonBytes...) + return buf, nil +} + +type encodePlanJSONCodecEitherFormatJSONRawMessage struct{} + +func (encodePlanJSONCodecEitherFormatJSONRawMessage) Encode(value any, buf []byte) (newBuf []byte, err error) { + jsonBytes := value.(json.RawMessage) + if jsonBytes == nil { + return nil, nil + } + + buf = append(buf, jsonBytes...) + return buf, nil +} + +type encodePlanJSONCodecEitherFormatMarshal struct { + marshal func(v any) ([]byte, error) +} + +func (e *encodePlanJSONCodecEitherFormatMarshal) Encode(value any, buf []byte) (newBuf []byte, err error) { + jsonBytes, err := e.marshal(value) + if err != nil { + return nil, err + } + + buf = append(buf, jsonBytes...) + return buf, nil +} + +func (c *JSONCodec) PlanScan(m *Map, oid uint32, formatCode int16, target any) ScanPlan { + return c.planScan(m, oid, formatCode, target, 0) +} + +// JSON cannot fallback to pointerPointerScanPlan because of 'null'::json(b), +// so we need to duplicate the logic here. +func (c *JSONCodec) planScan(m *Map, oid uint32, formatCode int16, target any, depth int) ScanPlan { + if depth > 8 { + return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} + } + + switch target.(type) { + case *string: + return &scanPlanAnyToString{} + case *[]byte: + return &scanPlanJSONToByteSlice{} + case BytesScanner: + return &scanPlanBinaryBytesToBytesScanner{} + case sql.Scanner: + return &scanPlanCodecSQLScanner{c: c, m: m, oid: oid, formatCode: formatCode} + } + + rv := reflect.ValueOf(target) + if rv.Kind() == reflect.Pointer && rv.Elem().Kind() == reflect.Pointer { + var plan jsonPointerScanPlan + plan.next = c.planScan(m, oid, formatCode, rv.Elem().Interface(), depth+1) + return plan + } else { + return &scanPlanJSONToJSONUnmarshal{unmarshal: c.Unmarshal} + } +} + +type scanPlanAnyToString struct{} + +func (scanPlanAnyToString) Scan(src []byte, dst any) error { + p := dst.(*string) + *p = string(src) + return nil +} + +type scanPlanJSONToByteSlice struct{} + +func (scanPlanJSONToByteSlice) Scan(src []byte, dst any) error { + dstBuf := dst.(*[]byte) + if src == nil { + *dstBuf = nil + return nil + } + + *dstBuf = make([]byte, len(src)) + copy(*dstBuf, src) + return nil +} + +type scanPlanJSONToJSONUnmarshal struct { + unmarshal func(data []byte, v any) error +} + +func (s *scanPlanJSONToJSONUnmarshal) Scan(src []byte, dst any) error { + if src == nil { + dstValue := reflect.ValueOf(dst) + if dstValue.Kind() == reflect.Pointer { + el := dstValue.Elem() + switch el.Kind() { + case reflect.Pointer, reflect.Slice, reflect.Map, reflect.Interface: + el.Set(reflect.Zero(el.Type())) + return nil + } + } + + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + v := reflect.ValueOf(dst) + if v.Kind() != reflect.Pointer || v.IsNil() { + return fmt.Errorf("cannot scan into non-pointer or nil destinations %T", dst) + } + + elem := v.Elem() + elem.Set(reflect.Zero(elem.Type())) + + return s.unmarshal(src, dst) +} + +func (c *JSONCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + dstBuf := make([]byte, len(src)) + copy(dstBuf, src) + return dstBuf, nil +} + +func (c *JSONCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var dst any + err := c.Unmarshal(src, &dst) + return dst, err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go b/vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go new file mode 100644 index 0000000..4d4eb58 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/jsonb.go @@ -0,0 +1,129 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" +) + +type JSONBCodec struct { + Marshal func(v any) ([]byte, error) + Unmarshal func(data []byte, v any) error +} + +func (*JSONBCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (*JSONBCodec) PreferredFormat() int16 { + return TextFormatCode +} + +func (c *JSONBCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + plan := (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanEncode(m, oid, TextFormatCode, value) + if plan != nil { + return &encodePlanJSONBCodecBinaryWrapper{textPlan: plan} + } + case TextFormatCode: + return (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanEncode(m, oid, format, value) + } + + return nil +} + +type encodePlanJSONBCodecBinaryWrapper struct { + textPlan EncodePlan +} + +func (plan *encodePlanJSONBCodecBinaryWrapper) Encode(value any, buf []byte) (newBuf []byte, err error) { + buf = append(buf, 1) + return plan.textPlan.Encode(value, buf) +} + +func (c *JSONBCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + plan := (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanScan(m, oid, TextFormatCode, target) + if plan != nil { + return &scanPlanJSONBCodecBinaryUnwrapper{textPlan: plan} + } + case TextFormatCode: + return (&JSONCodec{Marshal: c.Marshal, Unmarshal: c.Unmarshal}).PlanScan(m, oid, format, target) + } + + return nil +} + +type scanPlanJSONBCodecBinaryUnwrapper struct { + textPlan ScanPlan +} + +func (plan *scanPlanJSONBCodecBinaryUnwrapper) Scan(src []byte, dst any) error { + if src == nil { + return plan.textPlan.Scan(src, dst) + } + + if len(src) == 0 { + return fmt.Errorf("jsonb too short") + } + + if src[0] != 1 { + return fmt.Errorf("unknown jsonb version number %d", src[0]) + } + + return plan.textPlan.Scan(src[1:], dst) +} + +func (c *JSONBCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + switch format { + case BinaryFormatCode: + if len(src) == 0 { + return nil, fmt.Errorf("jsonb too short") + } + + if src[0] != 1 { + return nil, fmt.Errorf("unknown jsonb version number %d", src[0]) + } + + dstBuf := make([]byte, len(src)-1) + copy(dstBuf, src[1:]) + return dstBuf, nil + case TextFormatCode: + dstBuf := make([]byte, len(src)) + copy(dstBuf, src) + return dstBuf, nil + default: + return nil, fmt.Errorf("unknown format code: %v", format) + } +} + +func (c *JSONBCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + switch format { + case BinaryFormatCode: + if len(src) == 0 { + return nil, fmt.Errorf("jsonb too short") + } + + if src[0] != 1 { + return nil, fmt.Errorf("unknown jsonb version number %d", src[0]) + } + + src = src[1:] + case TextFormatCode: + default: + return nil, fmt.Errorf("unknown format code: %v", format) + } + + var dst any + err := c.Unmarshal(src, &dst) + return dst, err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/line.go b/vendor/github.com/jackc/pgx/v5/pgtype/line.go new file mode 100644 index 0000000..73b0636 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/line.go @@ -0,0 +1,223 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type LineScanner interface { + ScanLine(v Line) error +} + +type LineValuer interface { + LineValue() (Line, error) +} + +type Line struct { + A, B, C float64 + Valid bool +} + +// ScanLine implements the [LineScanner] interface. +func (line *Line) ScanLine(v Line) error { + *line = v + return nil +} + +// LineValue implements the [LineValuer] interface. +func (line Line) LineValue() (Line, error) { + return line, nil +} + +func (line *Line) Set(src any) error { + return fmt.Errorf("cannot convert %v to Line", src) +} + +// Scan implements the [database/sql.Scanner] interface. +func (line *Line) Scan(src any) error { + if src == nil { + *line = Line{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToLineScanner{}.Scan([]byte(src), line) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (line Line) Value() (driver.Value, error) { + if !line.Valid { + return nil, nil + } + + buf, err := LineCodec{}.PlanEncode(nil, 0, TextFormatCode, line).Encode(line, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type LineCodec struct{} + +func (LineCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (LineCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (LineCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(LineValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanLineCodecBinary{} + case TextFormatCode: + return encodePlanLineCodecText{} + } + + return nil +} + +type encodePlanLineCodecBinary struct{} + +func (encodePlanLineCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + line, err := value.(LineValuer).LineValue() + if err != nil { + return nil, err + } + + if !line.Valid { + return nil, nil + } + + buf = pgio.AppendUint64(buf, math.Float64bits(line.A)) + buf = pgio.AppendUint64(buf, math.Float64bits(line.B)) + buf = pgio.AppendUint64(buf, math.Float64bits(line.C)) + return buf, nil +} + +type encodePlanLineCodecText struct{} + +func (encodePlanLineCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + line, err := value.(LineValuer).LineValue() + if err != nil { + return nil, err + } + + if !line.Valid { + return nil, nil + } + + buf = append(buf, fmt.Sprintf(`{%s,%s,%s}`, + strconv.FormatFloat(line.A, 'f', -1, 64), + strconv.FormatFloat(line.B, 'f', -1, 64), + strconv.FormatFloat(line.C, 'f', -1, 64), + )...) + return buf, nil +} + +func (LineCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(LineScanner); ok { + return scanPlanBinaryLineToLineScanner{} + } + case TextFormatCode: + if _, ok := target.(LineScanner); ok { + return scanPlanTextAnyToLineScanner{} + } + } + + return nil +} + +type scanPlanBinaryLineToLineScanner struct{} + +func (scanPlanBinaryLineToLineScanner) Scan(src []byte, dst any) error { + scanner := (dst).(LineScanner) + + if src == nil { + return scanner.ScanLine(Line{}) + } + + if len(src) != 24 { + return fmt.Errorf("invalid length for line: %v", len(src)) + } + + a := binary.BigEndian.Uint64(src) + b := binary.BigEndian.Uint64(src[8:]) + c := binary.BigEndian.Uint64(src[16:]) + + return scanner.ScanLine(Line{ + A: math.Float64frombits(a), + B: math.Float64frombits(b), + C: math.Float64frombits(c), + Valid: true, + }) +} + +type scanPlanTextAnyToLineScanner struct{} + +func (scanPlanTextAnyToLineScanner) Scan(src []byte, dst any) error { + scanner := (dst).(LineScanner) + + if src == nil { + return scanner.ScanLine(Line{}) + } + + if len(src) < 7 { + return fmt.Errorf("invalid length for line: %v", len(src)) + } + + parts := strings.SplitN(string(src[1:len(src)-1]), ",", 3) + if len(parts) < 3 { + return fmt.Errorf("invalid format for line") + } + + a, err := strconv.ParseFloat(parts[0], 64) + if err != nil { + return err + } + + b, err := strconv.ParseFloat(parts[1], 64) + if err != nil { + return err + } + + c, err := strconv.ParseFloat(parts[2], 64) + if err != nil { + return err + } + + return scanner.ScanLine(Line{A: a, B: b, C: c, Valid: true}) +} + +func (c LineCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c LineCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var line Line + err := codecScan(c, m, oid, format, src, &line) + if err != nil { + return nil, err + } + return line, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go new file mode 100644 index 0000000..438b45b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/lseg.go @@ -0,0 +1,235 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type LsegScanner interface { + ScanLseg(v Lseg) error +} + +type LsegValuer interface { + LsegValue() (Lseg, error) +} + +type Lseg struct { + P [2]Vec2 + Valid bool +} + +// ScanLseg implements the [LsegScanner] interface. +func (lseg *Lseg) ScanLseg(v Lseg) error { + *lseg = v + return nil +} + +// LsegValue implements the [LsegValuer] interface. +func (lseg Lseg) LsegValue() (Lseg, error) { + return lseg, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (lseg *Lseg) Scan(src any) error { + if src == nil { + *lseg = Lseg{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToLsegScanner{}.Scan([]byte(src), lseg) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (lseg Lseg) Value() (driver.Value, error) { + if !lseg.Valid { + return nil, nil + } + + buf, err := LsegCodec{}.PlanEncode(nil, 0, TextFormatCode, lseg).Encode(lseg, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type LsegCodec struct{} + +func (LsegCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (LsegCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (LsegCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(LsegValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanLsegCodecBinary{} + case TextFormatCode: + return encodePlanLsegCodecText{} + } + + return nil +} + +type encodePlanLsegCodecBinary struct{} + +func (encodePlanLsegCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + lseg, err := value.(LsegValuer).LsegValue() + if err != nil { + return nil, err + } + + if !lseg.Valid { + return nil, nil + } + + buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[0].X)) + buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[0].Y)) + buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[1].X)) + buf = pgio.AppendUint64(buf, math.Float64bits(lseg.P[1].Y)) + return buf, nil +} + +type encodePlanLsegCodecText struct{} + +func (encodePlanLsegCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + lseg, err := value.(LsegValuer).LsegValue() + if err != nil { + return nil, err + } + + if !lseg.Valid { + return nil, nil + } + + buf = append(buf, fmt.Sprintf(`[(%s,%s),(%s,%s)]`, + strconv.FormatFloat(lseg.P[0].X, 'f', -1, 64), + strconv.FormatFloat(lseg.P[0].Y, 'f', -1, 64), + strconv.FormatFloat(lseg.P[1].X, 'f', -1, 64), + strconv.FormatFloat(lseg.P[1].Y, 'f', -1, 64), + )...) + return buf, nil +} + +func (LsegCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(LsegScanner); ok { + return scanPlanBinaryLsegToLsegScanner{} + } + case TextFormatCode: + if _, ok := target.(LsegScanner); ok { + return scanPlanTextAnyToLsegScanner{} + } + } + + return nil +} + +type scanPlanBinaryLsegToLsegScanner struct{} + +func (scanPlanBinaryLsegToLsegScanner) Scan(src []byte, dst any) error { + scanner := (dst).(LsegScanner) + + if src == nil { + return scanner.ScanLseg(Lseg{}) + } + + if len(src) != 32 { + return fmt.Errorf("invalid length for lseg: %v", len(src)) + } + + x1 := binary.BigEndian.Uint64(src) + y1 := binary.BigEndian.Uint64(src[8:]) + x2 := binary.BigEndian.Uint64(src[16:]) + y2 := binary.BigEndian.Uint64(src[24:]) + + return scanner.ScanLseg(Lseg{ + P: [2]Vec2{ + {math.Float64frombits(x1), math.Float64frombits(y1)}, + {math.Float64frombits(x2), math.Float64frombits(y2)}, + }, + Valid: true, + }) +} + +type scanPlanTextAnyToLsegScanner struct{} + +func (scanPlanTextAnyToLsegScanner) Scan(src []byte, dst any) error { + scanner := (dst).(LsegScanner) + + if src == nil { + return scanner.ScanLseg(Lseg{}) + } + + if len(src) < 11 { + return fmt.Errorf("invalid length for lseg: %v", len(src)) + } + + // Expected format: [(x1,y1),(x2,y2)] + sp1, sp2, found := strings.Cut(string(src[2:len(src)-2]), "),(") + if !found { + return fmt.Errorf("invalid format for lseg") + } + + sx1, sy1, found := strings.Cut(sp1, ",") + if !found { + return fmt.Errorf("invalid format for lseg") + } + sx2, sy2, found := strings.Cut(sp2, ",") + if !found { + return fmt.Errorf("invalid format for lseg") + } + + x1, err := strconv.ParseFloat(sx1, 64) + if err != nil { + return err + } + y1, err := strconv.ParseFloat(sy1, 64) + if err != nil { + return err + } + x2, err := strconv.ParseFloat(sx2, 64) + if err != nil { + return err + } + y2, err := strconv.ParseFloat(sy2, 64) + if err != nil { + return err + } + + return scanner.ScanLseg(Lseg{P: [2]Vec2{{x1, y1}, {x2, y2}}, Valid: true}) +} + +func (c LsegCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c LsegCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var lseg Lseg + err := codecScan(c, m, oid, format, src, &lseg) + if err != nil { + return nil, err + } + return lseg, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go new file mode 100644 index 0000000..6af3177 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/ltree.go @@ -0,0 +1,122 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" +) + +type LtreeCodec struct{} + +func (l LtreeCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +// PreferredFormat returns the preferred format. +func (l LtreeCodec) PreferredFormat() int16 { + return TextFormatCode +} + +// PlanEncode returns an EncodePlan for encoding value into PostgreSQL format for oid and format. If no plan can be +// found then nil is returned. +func (l LtreeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case TextFormatCode: + return (TextCodec)(l).PlanEncode(m, oid, format, value) + case BinaryFormatCode: + switch value.(type) { + case string: + return encodeLtreeCodecBinaryString{} + case []byte: + return encodeLtreeCodecBinaryByteSlice{} + case TextValuer: + return encodeLtreeCodecBinaryTextValuer{} + } + } + + return nil +} + +type encodeLtreeCodecBinaryString struct{} + +func (encodeLtreeCodecBinaryString) Encode(value any, buf []byte) (newBuf []byte, err error) { + ltree := value.(string) + buf = append(buf, 1) + return append(buf, ltree...), nil +} + +type encodeLtreeCodecBinaryByteSlice struct{} + +func (encodeLtreeCodecBinaryByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { + ltree := value.([]byte) + buf = append(buf, 1) + return append(buf, ltree...), nil +} + +type encodeLtreeCodecBinaryTextValuer struct{} + +func (encodeLtreeCodecBinaryTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + t, err := value.(TextValuer).TextValue() + if err != nil { + return nil, err + } + if !t.Valid { + return nil, nil + } + + buf = append(buf, 1) + return append(buf, t.String...), nil +} + +// PlanScan returns a ScanPlan for scanning a PostgreSQL value into a destination with the same type as target. If +// no plan can be found then nil is returned. +func (l LtreeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case TextFormatCode: + return (TextCodec)(l).PlanScan(m, oid, format, target) + case BinaryFormatCode: + switch target.(type) { + case *string: + return scanPlanBinaryLtreeToString{} + case TextScanner: + return scanPlanBinaryLtreeToTextScanner{} + } + } + + return nil +} + +type scanPlanBinaryLtreeToString struct{} + +func (scanPlanBinaryLtreeToString) Scan(src []byte, target any) error { + version := src[0] + if version != 1 { + return fmt.Errorf("unsupported ltree version %d", version) + } + + p := (target).(*string) + *p = string(src[1:]) + + return nil +} + +type scanPlanBinaryLtreeToTextScanner struct{} + +func (scanPlanBinaryLtreeToTextScanner) Scan(src []byte, target any) error { + version := src[0] + if version != 1 { + return fmt.Errorf("unsupported ltree version %d", version) + } + + scanner := (target).(TextScanner) + return scanner.ScanText(Text{String: string(src[1:]), Valid: true}) +} + +// DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. +func (l LtreeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return (TextCodec)(l).DecodeDatabaseSQLValue(m, oid, format, src) +} + +// DecodeValue returns src decoded into its default format. +func (l LtreeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + return (TextCodec)(l).DecodeValue(m, oid, format, src) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go new file mode 100644 index 0000000..e913ec9 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/macaddr.go @@ -0,0 +1,162 @@ +package pgtype + +import ( + "database/sql/driver" + "net" +) + +type MacaddrCodec struct{} + +func (MacaddrCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (MacaddrCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (MacaddrCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case net.HardwareAddr: + return encodePlanMacaddrCodecBinaryHardwareAddr{} + case TextValuer: + return encodePlanMacAddrCodecTextValuer{} + + } + case TextFormatCode: + switch value.(type) { + case net.HardwareAddr: + return encodePlanMacaddrCodecTextHardwareAddr{} + case TextValuer: + return encodePlanTextCodecTextValuer{} + } + } + + return nil +} + +type encodePlanMacaddrCodecBinaryHardwareAddr struct{} + +func (encodePlanMacaddrCodecBinaryHardwareAddr) Encode(value any, buf []byte) (newBuf []byte, err error) { + addr := value.(net.HardwareAddr) + if addr == nil { + return nil, nil + } + + return append(buf, addr...), nil +} + +type encodePlanMacAddrCodecTextValuer struct{} + +func (encodePlanMacAddrCodecTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + t, err := value.(TextValuer).TextValue() + if err != nil { + return nil, err + } + if !t.Valid { + return nil, nil + } + + addr, err := net.ParseMAC(t.String) + if err != nil { + return nil, err + } + + return append(buf, addr...), nil +} + +type encodePlanMacaddrCodecTextHardwareAddr struct{} + +func (encodePlanMacaddrCodecTextHardwareAddr) Encode(value any, buf []byte) (newBuf []byte, err error) { + addr := value.(net.HardwareAddr) + if addr == nil { + return nil, nil + } + + return append(buf, addr.String()...), nil +} + +func (MacaddrCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *net.HardwareAddr: + return scanPlanBinaryMacaddrToHardwareAddr{} + case TextScanner: + return scanPlanBinaryMacaddrToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *net.HardwareAddr: + return scanPlanTextMacaddrToHardwareAddr{} + case TextScanner: + return scanPlanTextAnyToTextScanner{} + } + } + + return nil +} + +type scanPlanBinaryMacaddrToHardwareAddr struct{} + +func (scanPlanBinaryMacaddrToHardwareAddr) Scan(src []byte, dst any) error { + dstBuf := dst.(*net.HardwareAddr) + if src == nil { + *dstBuf = nil + return nil + } + + *dstBuf = make([]byte, len(src)) + copy(*dstBuf, src) + return nil +} + +type scanPlanBinaryMacaddrToTextScanner struct{} + +func (scanPlanBinaryMacaddrToTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + if src == nil { + return scanner.ScanText(Text{}) + } + + return scanner.ScanText(Text{String: net.HardwareAddr(src).String(), Valid: true}) +} + +type scanPlanTextMacaddrToHardwareAddr struct{} + +func (scanPlanTextMacaddrToHardwareAddr) Scan(src []byte, dst any) error { + p := dst.(*net.HardwareAddr) + + if src == nil { + *p = nil + return nil + } + + addr, err := net.ParseMAC(string(src)) + if err != nil { + return err + } + + *p = addr + + return nil +} + +func (c MacaddrCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c MacaddrCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var addr net.HardwareAddr + err := codecScan(c, m, oid, format, src, &addr) + if err != nil { + return nil, err + } + return addr, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go new file mode 100644 index 0000000..11f30b4 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/multirange.go @@ -0,0 +1,453 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "encoding/binary" + "fmt" + "reflect" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// MultirangeGetter is a type that can be converted into a PostgreSQL multirange. +type MultirangeGetter interface { + // IsNull returns true if the value is SQL NULL. + IsNull() bool + + // Len returns the number of elements in the multirange. + Len() int + + // Index returns the element at i. + Index(i int) any + + // IndexType returns a non-nil scan target of the type Index will return. This is used by MultirangeCodec.PlanEncode. + IndexType() any +} + +// MultirangeSetter is a type can be set from a PostgreSQL multirange. +type MultirangeSetter interface { + // ScanNull sets the value to SQL NULL. + ScanNull() error + + // SetLen prepares the value such that ScanIndex can be called for each element. This will remove any existing + // elements. + SetLen(n int) error + + // ScanIndex returns a value usable as a scan target for i. SetLen must be called before ScanIndex. + ScanIndex(i int) any + + // ScanIndexType returns a non-nil scan target of the type ScanIndex will return. This is used by + // MultirangeCodec.PlanScan. + ScanIndexType() any +} + +// MultirangeCodec is a codec for any multirange type. +type MultirangeCodec struct { + ElementType *Type +} + +func (c *MultirangeCodec) FormatSupported(format int16) bool { + return c.ElementType.Codec.FormatSupported(format) +} + +func (c *MultirangeCodec) PreferredFormat() int16 { + return c.ElementType.Codec.PreferredFormat() +} + +func (c *MultirangeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + multirangeValuer, ok := value.(MultirangeGetter) + if !ok { + return nil + } + + elementType := multirangeValuer.IndexType() + + elementEncodePlan := m.PlanEncode(c.ElementType.OID, format, elementType) + if elementEncodePlan == nil { + return nil + } + + switch format { + case BinaryFormatCode: + return &encodePlanMultirangeCodecBinary{ac: c, m: m, oid: oid} + case TextFormatCode: + return &encodePlanMultirangeCodecText{ac: c, m: m, oid: oid} + } + + return nil +} + +type encodePlanMultirangeCodecText struct { + ac *MultirangeCodec + m *Map + oid uint32 +} + +func (p *encodePlanMultirangeCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + multirange := value.(MultirangeGetter) + + if multirange.IsNull() { + return nil, nil + } + + elementCount := multirange.Len() + + buf = append(buf, '{') + + var encodePlan EncodePlan + var lastElemType reflect.Type + inElemBuf := make([]byte, 0, 32) + for i := range elementCount { + if i > 0 { + buf = append(buf, ',') + } + + elem := multirange.Index(i) + var elemBuf []byte + if elem != nil { + elemType := reflect.TypeOf(elem) + if lastElemType != elemType { + lastElemType = elemType + encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, TextFormatCode, elem) + if encodePlan == nil { + return nil, fmt.Errorf("unable to encode %v", multirange.Index(i)) + } + } + elemBuf, err = encodePlan.Encode(elem, inElemBuf) + if err != nil { + return nil, err + } + } + + if elemBuf == nil { + return nil, fmt.Errorf("multirange cannot contain NULL element") + } else { + buf = append(buf, elemBuf...) + } + } + + buf = append(buf, '}') + + return buf, nil +} + +type encodePlanMultirangeCodecBinary struct { + ac *MultirangeCodec + m *Map + oid uint32 +} + +func (p *encodePlanMultirangeCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + multirange := value.(MultirangeGetter) + + if multirange.IsNull() { + return nil, nil + } + + elementCount := multirange.Len() + + buf = pgio.AppendInt32(buf, int32(elementCount)) + + var encodePlan EncodePlan + var lastElemType reflect.Type + for i := range elementCount { + sp := len(buf) + buf = pgio.AppendInt32(buf, -1) + + elem := multirange.Index(i) + var elemBuf []byte + if elem != nil { + elemType := reflect.TypeOf(elem) + if lastElemType != elemType { + lastElemType = elemType + encodePlan = p.m.PlanEncode(p.ac.ElementType.OID, BinaryFormatCode, elem) + if encodePlan == nil { + return nil, fmt.Errorf("unable to encode %v", multirange.Index(i)) + } + } + elemBuf, err = encodePlan.Encode(elem, buf) + if err != nil { + return nil, err + } + } + + if elemBuf == nil { + return nil, fmt.Errorf("multirange cannot contain NULL element") + } else { + buf = elemBuf + pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) + } + } + + return buf, nil +} + +func (c *MultirangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + multirangeScanner, ok := target.(MultirangeSetter) + if !ok { + return nil + } + + elementType := multirangeScanner.ScanIndexType() + + elementScanPlan := m.PlanScan(c.ElementType.OID, format, elementType) + if _, ok := elementScanPlan.(*scanPlanFail); ok { + return nil + } + + return &scanPlanMultirangeCodec{ + multirangeCodec: c, + m: m, + oid: oid, + formatCode: format, + } +} + +func (c *MultirangeCodec) decodeBinary(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { + rp := 0 + + elementCount := int(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + + // Each element requires at least 4 bytes for its length prefix. + if elementCount > len(src)/4 { + return fmt.Errorf("multirange element count %d exceeds available data", elementCount) + } + + err := multirange.SetLen(elementCount) + if err != nil { + return err + } + + if elementCount == 0 { + return nil + } + + elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, BinaryFormatCode, multirange.ScanIndex(0)) + if elementScanPlan == nil { + elementScanPlan = m.PlanScan(c.ElementType.OID, BinaryFormatCode, multirange.ScanIndex(0)) + } + + for i := range elementCount { + elem := multirange.ScanIndex(i) + if len(src[rp:]) < 4 { + return fmt.Errorf("multirange body truncated at element %d", i) + } + elemLen := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += 4 + var elemSrc []byte + if elemLen >= 0 { + if len(src[rp:]) < elemLen { + return fmt.Errorf("multirange element %d length %d exceeds remaining %d bytes", i, elemLen, len(src[rp:])) + } + elemSrc = src[rp : rp+elemLen] + rp += elemLen + } + err = elementScanPlan.Scan(elemSrc, elem) + if err != nil { + return fmt.Errorf("failed to scan multirange element %d: %w", i, err) + } + } + + return nil +} + +func (c *MultirangeCodec) decodeText(m *Map, multirangeOID uint32, src []byte, multirange MultirangeSetter) error { + elements, err := parseUntypedTextMultirange(src) + if err != nil { + return err + } + + err = multirange.SetLen(len(elements)) + if err != nil { + return err + } + + if len(elements) == 0 { + return nil + } + + elementScanPlan := c.ElementType.Codec.PlanScan(m, c.ElementType.OID, TextFormatCode, multirange.ScanIndex(0)) + if elementScanPlan == nil { + elementScanPlan = m.PlanScan(c.ElementType.OID, TextFormatCode, multirange.ScanIndex(0)) + } + + for i, s := range elements { + elem := multirange.ScanIndex(i) + err = elementScanPlan.Scan([]byte(s), elem) + if err != nil { + return err + } + } + + return nil +} + +type scanPlanMultirangeCodec struct { + multirangeCodec *MultirangeCodec + m *Map + oid uint32 + formatCode int16 + elementScanPlan ScanPlan +} + +func (spac *scanPlanMultirangeCodec) Scan(src []byte, dst any) error { + c := spac.multirangeCodec + m := spac.m + oid := spac.oid + formatCode := spac.formatCode + + multirange := dst.(MultirangeSetter) + + if src == nil { + return multirange.ScanNull() + } + + switch formatCode { + case BinaryFormatCode: + return c.decodeBinary(m, oid, src, multirange) + case TextFormatCode: + return c.decodeText(m, oid, src, multirange) + default: + return fmt.Errorf("unknown format code %d", formatCode) + } +} + +func (c *MultirangeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + return string(src), nil + case BinaryFormatCode: + buf := make([]byte, len(src)) + copy(buf, src) + return buf, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} + +func (c *MultirangeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var multirange Multirange[Range[any]] + err := m.PlanScan(oid, format, &multirange).Scan(src, &multirange) + return multirange, err +} + +func parseUntypedTextMultirange(src []byte) ([]string, error) { + elements := make([]string, 0) + + buf := bytes.NewBuffer(src) + + skipWhitespace(buf) + + r, _, err := buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid array: %w", err) + } + + if r != '{' { + return nil, fmt.Errorf("invalid multirange, expected '{' got %v", r) + } + +parseValueLoop: + for { + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid multirange: %w", err) + } + + switch r { + case ',': // skip range separator + case '}': + break parseValueLoop + default: + buf.UnreadRune() + value, err := parseRange(buf) + if err != nil { + return nil, fmt.Errorf("invalid multirange value: %w", err) + } + elements = append(elements, value) + } + } + + skipWhitespace(buf) + + if buf.Len() > 0 { + return nil, fmt.Errorf("unexpected trailing data: %v", buf.String()) + } + + return elements, nil +} + +func parseRange(buf *bytes.Buffer) (string, error) { + s := &bytes.Buffer{} + + boundSepRead := false + for { + r, _, err := buf.ReadRune() + if err != nil { + return "", err + } + + switch r { + case ',', '}': + if r == ',' && !boundSepRead { + boundSepRead = true + break + } + buf.UnreadRune() + return s.String(), nil + } + + s.WriteRune(r) + } +} + +// Multirange is a generic multirange type. +// +// T should implement [RangeValuer] and *T should implement [RangeScanner]. However, there does not appear to be a way to +// enforce the [RangeScanner] constraint. +type Multirange[T RangeValuer] []T + +func (r Multirange[T]) IsNull() bool { + return r == nil +} + +func (r Multirange[T]) Len() int { + return len(r) +} + +func (r Multirange[T]) Index(i int) any { + return r[i] +} + +func (r Multirange[T]) IndexType() any { + var zero T + return zero +} + +func (r *Multirange[T]) ScanNull() error { + *r = nil + return nil +} + +func (r *Multirange[T]) SetLen(n int) error { + *r = make([]T, n) + return nil +} + +func (r Multirange[T]) ScanIndex(i int) any { + return &r[i] +} + +func (r Multirange[T]) ScanIndexType() any { + return new(T) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go new file mode 100644 index 0000000..caf5ff1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/numeric.go @@ -0,0 +1,843 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "math/big" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// PostgreSQL internal numeric storage uses 16-bit "digits" with base of 10,000 +const nbase = 10_000 + +const ( + pgNumericNaN = 0x00000000c0000000 + pgNumericNaNSign = 0xc000 + + pgNumericPosInf = 0x00000000d0000000 + pgNumericPosInfSign = 0xd000 + + pgNumericNegInf = 0x00000000f0000000 + pgNumericNegInfSign = 0xf000 +) + +var ( + big1 *big.Int = big.NewInt(1) + big10 *big.Int = big.NewInt(10) + big100 *big.Int = big.NewInt(100) + big1000 *big.Int = big.NewInt(1000) +) + +var ( + bigNBase *big.Int = big.NewInt(nbase) + bigNBaseX2 *big.Int = big.NewInt(nbase * nbase) + bigNBaseX3 *big.Int = big.NewInt(nbase * nbase * nbase) + bigNBaseX4 *big.Int = big.NewInt(nbase * nbase * nbase * nbase) +) + +type NumericScanner interface { + ScanNumeric(v Numeric) error +} + +type NumericValuer interface { + NumericValue() (Numeric, error) +} + +type Numeric struct { + Int *big.Int + Exp int32 + NaN bool + InfinityModifier InfinityModifier + Valid bool +} + +// ScanNumeric implements the [NumericScanner] interface. +func (n *Numeric) ScanNumeric(v Numeric) error { + *n = v + return nil +} + +// NumericValue implements the [NumericValuer] interface. +func (n Numeric) NumericValue() (Numeric, error) { + return n, nil +} + +// Float64Value implements the [Float64Valuer] interface. +func (n Numeric) Float64Value() (Float8, error) { + switch { + case !n.Valid: + return Float8{}, nil + case n.NaN: + return Float8{Float64: math.NaN(), Valid: true}, nil + case n.InfinityModifier == Infinity: + return Float8{Float64: math.Inf(1), Valid: true}, nil + case n.InfinityModifier == NegativeInfinity: + return Float8{Float64: math.Inf(-1), Valid: true}, nil + } + + buf := make([]byte, 0, 32) + + if n.Int == nil { + buf = append(buf, '0') + } else { + buf = append(buf, n.Int.String()...) + } + buf = append(buf, 'e') + buf = append(buf, strconv.FormatInt(int64(n.Exp), 10)...) + + f, err := strconv.ParseFloat(string(buf), 64) + if err != nil { + return Float8{}, err + } + + return Float8{Float64: f, Valid: true}, nil +} + +// ScanInt64 implements the [Int64Scanner] interface. +func (n *Numeric) ScanInt64(v Int8) error { + if !v.Valid { + *n = Numeric{} + return nil + } + + *n = Numeric{Int: big.NewInt(v.Int64), Valid: true} + return nil +} + +// Int64Value implements the [Int64Valuer] interface. +func (n Numeric) Int64Value() (Int8, error) { + if !n.Valid { + return Int8{}, nil + } + + bi, err := n.toBigInt() + if err != nil { + return Int8{}, err + } + + if !bi.IsInt64() { + return Int8{}, fmt.Errorf("cannot convert %v to int64", n) + } + + return Int8{Int64: bi.Int64(), Valid: true}, nil +} + +func (n *Numeric) ScanScientific(src string) error { + if !strings.ContainsAny(src, "eE") { + return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) + } + + if bigF, ok := new(big.Float).SetString(src); ok { + smallF, _ := bigF.Float64() + src = strconv.FormatFloat(smallF, 'f', -1, 64) + } + + num, exp, err := parseNumericString(src) + if err != nil { + return err + } + + *n = Numeric{Int: num, Exp: exp, Valid: true} + + return nil +} + +func (n *Numeric) toBigInt() (*big.Int, error) { + if n.Exp == 0 { + return n.Int, nil + } + + num := &big.Int{} + num.Set(n.Int) + if n.Exp > 0 { + mul := &big.Int{} + mul.Exp(big10, big.NewInt(int64(n.Exp)), nil) + num.Mul(num, mul) + return num, nil + } + + div := &big.Int{} + div.Exp(big10, big.NewInt(int64(-n.Exp)), nil) + remainder := &big.Int{} + num.DivMod(num, div, remainder) + if remainder.Sign() != 0 { + return nil, fmt.Errorf("cannot convert %v to integer", n) + } + return num, nil +} + +func parseNumericString(str string) (n *big.Int, exp int32, err error) { + idx := strings.IndexByte(str, '.') + + if idx == -1 { + for len(str) > 1 && str[len(str)-1] == '0' && str[len(str)-2] != '-' { + str = str[:len(str)-1] + exp++ + } + } else { + exp = int32(-(len(str) - idx - 1)) + str = str[:idx] + str[idx+1:] + } + + accum := &big.Int{} + if _, ok := accum.SetString(str, 10); !ok { + return nil, 0, fmt.Errorf("%s is not a number", str) + } + + return accum, exp, nil +} + +func nbaseDigitsToInt64(src []byte) (accum int64, bytesRead, digitsRead int) { + digits := min(len(src)/2, 4) + + rp := 0 + + for i := range digits { + if i > 0 { + accum *= nbase + } + accum += int64(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + } + + return accum, rp, digits +} + +// Scan implements the [database/sql.Scanner] interface. +func (n *Numeric) Scan(src any) error { + if src == nil { + *n = Numeric{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToNumericScanner{}.Scan([]byte(src), n) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (n Numeric) Value() (driver.Value, error) { + if !n.Valid { + return nil, nil + } + + buf, err := NumericCodec{}.PlanEncode(nil, 0, TextFormatCode, n).Encode(n, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (n Numeric) MarshalJSON() ([]byte, error) { + if !n.Valid { + return []byte("null"), nil + } + + if n.NaN { + return []byte(`"NaN"`), nil + } + + return n.numberTextBytes(), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (n *Numeric) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte(`null`)) { + *n = Numeric{} + return nil + } + if bytes.Equal(src, []byte(`"NaN"`)) { + *n = Numeric{NaN: true, Valid: true} + return nil + } + return scanPlanTextAnyToNumericScanner{}.Scan(src, n) +} + +// numberString returns a string of the number. undefined if NaN, infinite, or NULL +func (n Numeric) numberTextBytes() []byte { + if n.Int == nil { + return []byte("0") + } + + intStr := n.Int.String() + + buf := &bytes.Buffer{} + + if len(intStr) > 0 && intStr[:1] == "-" { + intStr = intStr[1:] + buf.WriteByte('-') + } + + exp := int(n.Exp) + switch { + case exp > 0: + buf.WriteString(intStr) + for range exp { + buf.WriteByte('0') + } + case exp < 0: + if len(intStr) <= -exp { + buf.WriteString("0.") + leadingZeros := -exp - len(intStr) + for range leadingZeros { + buf.WriteByte('0') + } + buf.WriteString(intStr) + } else if len(intStr) > -exp { + dpPos := len(intStr) + exp + buf.WriteString(intStr[:dpPos]) + buf.WriteByte('.') + buf.WriteString(intStr[dpPos:]) + } + default: + buf.WriteString(intStr) + } + + return buf.Bytes() +} + +type NumericCodec struct{} + +func (NumericCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (NumericCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (NumericCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case NumericValuer: + return encodePlanNumericCodecBinaryNumericValuer{} + case Float64Valuer: + return encodePlanNumericCodecBinaryFloat64Valuer{} + case Int64Valuer: + return encodePlanNumericCodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case NumericValuer: + return encodePlanNumericCodecTextNumericValuer{} + case Float64Valuer: + return encodePlanNumericCodecTextFloat64Valuer{} + case Int64Valuer: + return encodePlanNumericCodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanNumericCodecBinaryNumericValuer struct{} + +func (encodePlanNumericCodecBinaryNumericValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(NumericValuer).NumericValue() + if err != nil { + return nil, err + } + + return encodeNumericBinary(n, buf) +} + +type encodePlanNumericCodecBinaryFloat64Valuer struct{} + +func (encodePlanNumericCodecBinaryFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Float64Valuer).Float64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + switch { + case math.IsNaN(n.Float64): + return encodeNumericBinary(Numeric{NaN: true, Valid: true}, buf) + case math.IsInf(n.Float64, 1): + return encodeNumericBinary(Numeric{InfinityModifier: Infinity, Valid: true}, buf) + case math.IsInf(n.Float64, -1): + return encodeNumericBinary(Numeric{InfinityModifier: NegativeInfinity, Valid: true}, buf) + } + num, exp, err := parseNumericString(strconv.FormatFloat(n.Float64, 'f', -1, 64)) + if err != nil { + return nil, err + } + + return encodeNumericBinary(Numeric{Int: num, Exp: exp, Valid: true}, buf) +} + +type encodePlanNumericCodecBinaryInt64Valuer struct{} + +func (encodePlanNumericCodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + return encodeNumericBinary(Numeric{Int: big.NewInt(n.Int64), Valid: true}, buf) +} + +func encodeNumericBinary(n Numeric, buf []byte) (newBuf []byte, err error) { + if !n.Valid { + return nil, nil + } + + switch { + case n.NaN: + buf = pgio.AppendUint64(buf, pgNumericNaN) + return buf, nil + case n.InfinityModifier == Infinity: + buf = pgio.AppendUint64(buf, pgNumericPosInf) + return buf, nil + case n.InfinityModifier == NegativeInfinity: + buf = pgio.AppendUint64(buf, pgNumericNegInf) + return buf, nil + } + + var sign int16 + if n.Int != nil && n.Int.Sign() < 0 { + sign = 16384 + } + + absInt := &big.Int{} + wholePart := &big.Int{} + fracPart := &big.Int{} + remainder := &big.Int{} + if n.Int != nil { + absInt.Abs(n.Int) + } + + // Normalize absInt and exp to where exp is always a multiple of 4. This makes + // converting to 16-bit base 10,000 digits easier. + var exp int32 + switch n.Exp % 4 { + case 1, -3: + exp = n.Exp - 1 + absInt.Mul(absInt, big10) + case 2, -2: + exp = n.Exp - 2 + absInt.Mul(absInt, big100) + case 3, -1: + exp = n.Exp - 3 + absInt.Mul(absInt, big1000) + default: + exp = n.Exp + } + + if exp < 0 { + divisor := &big.Int{} + divisor.Exp(big10, big.NewInt(int64(-exp)), nil) + wholePart.DivMod(absInt, divisor, fracPart) + fracPart.Add(fracPart, divisor) + } else { + wholePart = absInt + } + + var wholeDigits, fracDigits []int16 + + for wholePart.Sign() != 0 { + wholePart.DivMod(wholePart, bigNBase, remainder) + wholeDigits = append(wholeDigits, int16(remainder.Int64())) + } + + if fracPart.Sign() != 0 { + for fracPart.Cmp(big1) != 0 { + fracPart.DivMod(fracPart, bigNBase, remainder) + fracDigits = append(fracDigits, int16(remainder.Int64())) + } + } + + buf = pgio.AppendInt16(buf, int16(len(wholeDigits)+len(fracDigits))) + + var weight int16 + if len(wholeDigits) > 0 { + weight = int16(len(wholeDigits) - 1) + if exp > 0 { + weight += int16(exp / 4) + } + } else { + weight = int16(exp/4) - 1 + int16(len(fracDigits)) + } + buf = pgio.AppendInt16(buf, weight) + + buf = pgio.AppendInt16(buf, sign) + + var dscale int16 + if n.Exp < 0 { + dscale = int16(-n.Exp) + } + buf = pgio.AppendInt16(buf, dscale) + + for i := len(wholeDigits) - 1; i >= 0; i-- { + buf = pgio.AppendInt16(buf, wholeDigits[i]) + } + + for i := len(fracDigits) - 1; i >= 0; i-- { + buf = pgio.AppendInt16(buf, fracDigits[i]) + } + + return buf, nil +} + +type encodePlanNumericCodecTextNumericValuer struct{} + +func (encodePlanNumericCodecTextNumericValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(NumericValuer).NumericValue() + if err != nil { + return nil, err + } + + return encodeNumericText(n, buf) +} + +type encodePlanNumericCodecTextFloat64Valuer struct{} + +func (encodePlanNumericCodecTextFloat64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Float64Valuer).Float64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + switch { + case math.IsNaN(n.Float64): + buf = append(buf, "NaN"...) + case math.IsInf(n.Float64, 1): + buf = append(buf, "Infinity"...) + case math.IsInf(n.Float64, -1): + buf = append(buf, "-Infinity"...) + default: + buf = append(buf, strconv.FormatFloat(n.Float64, 'f', -1, 64)...) + } + return buf, nil +} + +type encodePlanNumericCodecTextInt64Valuer struct{} + +func (encodePlanNumericCodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + n, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !n.Valid { + return nil, nil + } + + buf = append(buf, strconv.FormatInt(n.Int64, 10)...) + return buf, nil +} + +func encodeNumericText(n Numeric, buf []byte) (newBuf []byte, err error) { + if !n.Valid { + return nil, nil + } + + switch { + case n.NaN: + buf = append(buf, "NaN"...) + return buf, nil + case n.InfinityModifier == Infinity: + buf = append(buf, "Infinity"...) + return buf, nil + case n.InfinityModifier == NegativeInfinity: + buf = append(buf, "-Infinity"...) + return buf, nil + } + + buf = append(buf, n.numberTextBytes()...) + + return buf, nil +} + +func (NumericCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case NumericScanner: + return scanPlanBinaryNumericToNumericScanner{} + case Float64Scanner: + return scanPlanBinaryNumericToFloat64Scanner{} + case Int64Scanner: + return scanPlanBinaryNumericToInt64Scanner{} + case TextScanner: + return scanPlanBinaryNumericToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case NumericScanner: + return scanPlanTextAnyToNumericScanner{} + case Float64Scanner: + return scanPlanTextAnyToFloat64Scanner{} + case Int64Scanner: + return scanPlanTextAnyToInt64Scanner{} + } + } + + return nil +} + +type scanPlanBinaryNumericToNumericScanner struct{} + +func (scanPlanBinaryNumericToNumericScanner) Scan(src []byte, dst any) error { + scanner := (dst).(NumericScanner) + + if src == nil { + return scanner.ScanNumeric(Numeric{}) + } + + if len(src) < 8 { + return fmt.Errorf("numeric incomplete %v", src) + } + + rp := 0 + ndigits := binary.BigEndian.Uint16(src[rp:]) + rp += 2 + weight := int16(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + sign := binary.BigEndian.Uint16(src[rp:]) + rp += 2 + dscale := int16(binary.BigEndian.Uint16(src[rp:])) + rp += 2 + + switch sign { + case pgNumericNaNSign: + return scanner.ScanNumeric(Numeric{NaN: true, Valid: true}) + case pgNumericPosInfSign: + return scanner.ScanNumeric(Numeric{InfinityModifier: Infinity, Valid: true}) + case pgNumericNegInfSign: + return scanner.ScanNumeric(Numeric{InfinityModifier: NegativeInfinity, Valid: true}) + } + + if ndigits == 0 { + return scanner.ScanNumeric(Numeric{Int: big.NewInt(0), Valid: true}) + } + + if len(src[rp:]) < int(ndigits)*2 { + return fmt.Errorf("numeric incomplete %v", src) + } + + accum := &big.Int{} + + for i := 0; i < int(ndigits+3)/4; i++ { + int64accum, bytesRead, digitsRead := nbaseDigitsToInt64(src[rp:]) + rp += bytesRead + + if i > 0 { + var mul *big.Int + switch digitsRead { + case 1: + mul = bigNBase + case 2: + mul = bigNBaseX2 + case 3: + mul = bigNBaseX3 + case 4: + mul = bigNBaseX4 + default: + return fmt.Errorf("invalid digitsRead: %d (this can't happen)", digitsRead) + } + accum.Mul(accum, mul) + } + + accum.Add(accum, big.NewInt(int64accum)) + } + + exp := (int32(weight) - int32(ndigits) + 1) * 4 + + if dscale > 0 { + fracNBaseDigits := int(ndigits) - int(weight) - 1 + fracDecimalDigits := fracNBaseDigits * 4 + dscaleInt := int(dscale) + + if dscaleInt > fracDecimalDigits { + multCount := dscaleInt - fracDecimalDigits + for range multCount { + accum.Mul(accum, big10) + exp-- + } + } else if dscaleInt < fracDecimalDigits { + divCount := fracDecimalDigits - dscaleInt + for range divCount { + accum.Div(accum, big10) + exp++ + } + } + } + + reduced := &big.Int{} + remainder := &big.Int{} + if exp >= 0 { + for { + reduced.DivMod(accum, big10, remainder) + if remainder.Sign() != 0 { + break + } + accum.Set(reduced) + exp++ + } + } + + if sign != 0 { + accum.Neg(accum) + } + + return scanner.ScanNumeric(Numeric{Int: accum, Exp: exp, Valid: true}) +} + +type scanPlanBinaryNumericToFloat64Scanner struct{} + +func (scanPlanBinaryNumericToFloat64Scanner) Scan(src []byte, dst any) error { + scanner := (dst).(Float64Scanner) + + if src == nil { + return scanner.ScanFloat64(Float8{}) + } + + var n Numeric + + err := scanPlanBinaryNumericToNumericScanner{}.Scan(src, &n) + if err != nil { + return err + } + + f8, err := n.Float64Value() + if err != nil { + return err + } + + return scanner.ScanFloat64(f8) +} + +type scanPlanBinaryNumericToInt64Scanner struct{} + +func (scanPlanBinaryNumericToInt64Scanner) Scan(src []byte, dst any) error { + scanner := (dst).(Int64Scanner) + + if src == nil { + return scanner.ScanInt64(Int8{}) + } + + var n Numeric + + err := scanPlanBinaryNumericToNumericScanner{}.Scan(src, &n) + if err != nil { + return err + } + + bigInt, err := n.toBigInt() + if err != nil { + return err + } + + if !bigInt.IsInt64() { + return fmt.Errorf("%v is out of range for int64", bigInt) + } + + return scanner.ScanInt64(Int8{Int64: bigInt.Int64(), Valid: true}) +} + +type scanPlanBinaryNumericToTextScanner struct{} + +func (scanPlanBinaryNumericToTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + + var n Numeric + + err := scanPlanBinaryNumericToNumericScanner{}.Scan(src, &n) + if err != nil { + return err + } + + sbuf, err := encodeNumericText(n, nil) + if err != nil { + return err + } + + return scanner.ScanText(Text{String: string(sbuf), Valid: true}) +} + +type scanPlanTextAnyToNumericScanner struct{} + +func (scanPlanTextAnyToNumericScanner) Scan(src []byte, dst any) error { + scanner := (dst).(NumericScanner) + + if src == nil { + return scanner.ScanNumeric(Numeric{}) + } + + switch string(src) { + case "NaN": + return scanner.ScanNumeric(Numeric{NaN: true, Valid: true}) + case "Infinity": + return scanner.ScanNumeric(Numeric{InfinityModifier: Infinity, Valid: true}) + case "-Infinity": + return scanner.ScanNumeric(Numeric{InfinityModifier: NegativeInfinity, Valid: true}) + } + + num, exp, err := parseNumericString(string(src)) + if err != nil { + return err + } + + return scanner.ScanNumeric(Numeric{Int: num, Exp: exp, Valid: true}) +} + +func (c NumericCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + if format == TextFormatCode { + return string(src), nil + } + + var n Numeric + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + + buf, err := m.Encode(oid, TextFormatCode, n, nil) + if err != nil { + return nil, err + } + return string(buf), nil +} + +func (c NumericCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n Numeric + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/path.go b/vendor/github.com/jackc/pgx/v5/pgtype/path.go new file mode 100644 index 0000000..6398b58 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/path.go @@ -0,0 +1,280 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type PathScanner interface { + ScanPath(v Path) error +} + +type PathValuer interface { + PathValue() (Path, error) +} + +type Path struct { + P []Vec2 + Closed bool + Valid bool +} + +// ScanPath implements the [PathScanner] interface. +func (path *Path) ScanPath(v Path) error { + *path = v + return nil +} + +// PathValue implements the [PathValuer] interface. +func (path Path) PathValue() (Path, error) { + return path, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (path *Path) Scan(src any) error { + if src == nil { + *path = Path{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToPathScanner{}.Scan([]byte(src), path) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (path Path) Value() (driver.Value, error) { + if !path.Valid { + return nil, nil + } + + buf, err := PathCodec{}.PlanEncode(nil, 0, TextFormatCode, path).Encode(path, nil) + if err != nil { + return nil, err + } + + return string(buf), err +} + +type PathCodec struct{} + +func (PathCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (PathCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (PathCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(PathValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanPathCodecBinary{} + case TextFormatCode: + return encodePlanPathCodecText{} + } + + return nil +} + +type encodePlanPathCodecBinary struct{} + +func (encodePlanPathCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + path, err := value.(PathValuer).PathValue() + if err != nil { + return nil, err + } + + if !path.Valid { + return nil, nil + } + + var closeByte byte + if path.Closed { + closeByte = 1 + } + buf = append(buf, closeByte) + + buf = pgio.AppendInt32(buf, int32(len(path.P))) + + for _, p := range path.P { + buf = pgio.AppendUint64(buf, math.Float64bits(p.X)) + buf = pgio.AppendUint64(buf, math.Float64bits(p.Y)) + } + + return buf, nil +} + +type encodePlanPathCodecText struct{} + +func (encodePlanPathCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + path, err := value.(PathValuer).PathValue() + if err != nil { + return nil, err + } + + if !path.Valid { + return nil, nil + } + + var startByte, endByte byte + if path.Closed { + startByte = '(' + endByte = ')' + } else { + startByte = '[' + endByte = ']' + } + buf = append(buf, startByte) + + for i, p := range path.P { + if i > 0 { + buf = append(buf, ',') + } + buf = append(buf, fmt.Sprintf(`(%s,%s)`, + strconv.FormatFloat(p.X, 'f', -1, 64), + strconv.FormatFloat(p.Y, 'f', -1, 64), + )...) + } + + buf = append(buf, endByte) + + return buf, nil +} + +func (PathCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(PathScanner); ok { + return scanPlanBinaryPathToPathScanner{} + } + case TextFormatCode: + if _, ok := target.(PathScanner); ok { + return scanPlanTextAnyToPathScanner{} + } + } + + return nil +} + +type scanPlanBinaryPathToPathScanner struct{} + +func (scanPlanBinaryPathToPathScanner) Scan(src []byte, dst any) error { + scanner := (dst).(PathScanner) + + if src == nil { + return scanner.ScanPath(Path{}) + } + + if len(src) < 5 { + return fmt.Errorf("invalid length for Path: %v", len(src)) + } + + closed := src[0] == 1 + pointCount := int(binary.BigEndian.Uint32(src[1:])) + + rp := 5 + + if 5+pointCount*16 != len(src) { + return fmt.Errorf("invalid length for Path with %d points: %v", pointCount, len(src)) + } + + points := make([]Vec2, pointCount) + for i := range points { + x := binary.BigEndian.Uint64(src[rp:]) + rp += 8 + y := binary.BigEndian.Uint64(src[rp:]) + rp += 8 + points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} + } + + return scanner.ScanPath(Path{ + P: points, + Closed: closed, + Valid: true, + }) +} + +type scanPlanTextAnyToPathScanner struct{} + +func (scanPlanTextAnyToPathScanner) Scan(src []byte, dst any) error { + scanner := (dst).(PathScanner) + + if src == nil { + return scanner.ScanPath(Path{}) + } + + if len(src) < 7 { + return fmt.Errorf("invalid length for Path: %v", len(src)) + } + + closed := src[0] == '(' + points := make([]Vec2, 0) + + // Expected format: ((x1,y1),...,(xn,yn)) or [(x1,y1),...,(xn,yn)] + str := string(src[1 : len(src)-1]) + + for { + if len(str) == 0 || str[0] != '(' { + return fmt.Errorf("invalid format for Path") + } + body, rest, found := strings.Cut(str[1:], ")") + if !found { + return fmt.Errorf("invalid format for Path") + } + + sx, sy, found := strings.Cut(body, ",") + if !found { + return fmt.Errorf("invalid format for Path") + } + x, err := strconv.ParseFloat(sx, 64) + if err != nil { + return err + } + y, err := strconv.ParseFloat(sy, 64) + if err != nil { + return err + } + + points = append(points, Vec2{x, y}) + + if rest == "" { + break + } + str, found = strings.CutPrefix(rest, ",") + if !found { + return fmt.Errorf("invalid format for Path") + } + } + + return scanner.ScanPath(Path{P: points, Closed: closed, Valid: true}) +} + +func (c PathCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c PathCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var path Path + err := codecScan(c, m, oid, format, src, &path) + if err != nil { + return nil, err + } + return path, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go new file mode 100644 index 0000000..46b892b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype.go @@ -0,0 +1,2067 @@ +package pgtype + +import ( + "database/sql" + "database/sql/driver" + "errors" + "fmt" + "net" + "net/netip" + "reflect" + "time" +) + +// PostgreSQL oids for common types +const ( + BoolOID = 16 + ByteaOID = 17 + QCharOID = 18 + NameOID = 19 + Int8OID = 20 + Int2OID = 21 + Int4OID = 23 + TextOID = 25 + OIDOID = 26 + TIDOID = 27 + XIDOID = 28 + CIDOID = 29 + JSONOID = 114 + XMLOID = 142 + XMLArrayOID = 143 + JSONArrayOID = 199 + XID8ArrayOID = 271 + PointOID = 600 + LsegOID = 601 + PathOID = 602 + BoxOID = 603 + PolygonOID = 604 + LineOID = 628 + LineArrayOID = 629 + CIDROID = 650 + CIDRArrayOID = 651 + Float4OID = 700 + Float8OID = 701 + CircleOID = 718 + CircleArrayOID = 719 + UnknownOID = 705 + Macaddr8OID = 774 + MacaddrOID = 829 + InetOID = 869 + BoolArrayOID = 1000 + QCharArrayOID = 1002 + NameArrayOID = 1003 + Int2ArrayOID = 1005 + Int4ArrayOID = 1007 + TextArrayOID = 1009 + TIDArrayOID = 1010 + ByteaArrayOID = 1001 + XIDArrayOID = 1011 + CIDArrayOID = 1012 + BPCharArrayOID = 1014 + VarcharArrayOID = 1015 + Int8ArrayOID = 1016 + PointArrayOID = 1017 + LsegArrayOID = 1018 + PathArrayOID = 1019 + BoxArrayOID = 1020 + Float4ArrayOID = 1021 + Float8ArrayOID = 1022 + PolygonArrayOID = 1027 + OIDArrayOID = 1028 + ACLItemOID = 1033 + ACLItemArrayOID = 1034 + MacaddrArrayOID = 1040 + InetArrayOID = 1041 + BPCharOID = 1042 + VarcharOID = 1043 + DateOID = 1082 + TimeOID = 1083 + TimestampOID = 1114 + TimestampArrayOID = 1115 + DateArrayOID = 1182 + TimeArrayOID = 1183 + TimestamptzOID = 1184 + TimestamptzArrayOID = 1185 + IntervalOID = 1186 + IntervalArrayOID = 1187 + NumericArrayOID = 1231 + TimetzOID = 1266 + TimetzArrayOID = 1270 + BitOID = 1560 + BitArrayOID = 1561 + VarbitOID = 1562 + VarbitArrayOID = 1563 + NumericOID = 1700 + RecordOID = 2249 + RecordArrayOID = 2287 + UUIDOID = 2950 + UUIDArrayOID = 2951 + TSVectorOID = 3614 + TSVectorArrayOID = 3643 + JSONBOID = 3802 + JSONBArrayOID = 3807 + DaterangeOID = 3912 + DaterangeArrayOID = 3913 + Int4rangeOID = 3904 + Int4rangeArrayOID = 3905 + NumrangeOID = 3906 + NumrangeArrayOID = 3907 + TsrangeOID = 3908 + TsrangeArrayOID = 3909 + TstzrangeOID = 3910 + TstzrangeArrayOID = 3911 + Int8rangeOID = 3926 + Int8rangeArrayOID = 3927 + JSONPathOID = 4072 + JSONPathArrayOID = 4073 + Int4multirangeOID = 4451 + NummultirangeOID = 4532 + TsmultirangeOID = 4533 + TstzmultirangeOID = 4534 + DatemultirangeOID = 4535 + Int8multirangeOID = 4536 + XID8OID = 5069 + Int4multirangeArrayOID = 6150 + NummultirangeArrayOID = 6151 + TsmultirangeArrayOID = 6152 + TstzmultirangeArrayOID = 6153 + DatemultirangeArrayOID = 6155 + Int8multirangeArrayOID = 6157 +) + +type InfinityModifier int8 + +const ( + Infinity InfinityModifier = 1 + Finite InfinityModifier = 0 + NegativeInfinity InfinityModifier = -Infinity +) + +func (im InfinityModifier) String() string { + switch im { + case Finite: + return "finite" + case Infinity: + return "infinity" + case NegativeInfinity: + return "-infinity" + default: + return "invalid" + } +} + +// PostgreSQL format codes +const ( + TextFormatCode = 0 + BinaryFormatCode = 1 +) + +// A Codec converts between Go and PostgreSQL values. A Codec must not be mutated after it is registered with a [Map]. +type Codec interface { + // FormatSupported returns true if the format is supported. + FormatSupported(int16) bool + + // PreferredFormat returns the preferred format. + PreferredFormat() int16 + + // PlanEncode returns an EncodePlan for encoding value into PostgreSQL format for oid and format. If no plan can be + // found then nil is returned. + PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan + + // PlanScan returns a ScanPlan for scanning a PostgreSQL value into a destination with the same type as target. If + // no plan can be found then nil is returned. + PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan + + // DecodeDatabaseSQLValue returns src decoded into a value compatible with the sql.Scanner interface. + DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) + + // DecodeValue returns src decoded into its default format. + DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) +} + +type nullAssignmentError struct { + dst any +} + +func (e *nullAssignmentError) Error() string { + return fmt.Sprintf("cannot assign NULL to %T", e.dst) +} + +// Type represents a PostgreSQL data type. It must not be mutated after it is registered with a [Map]. +type Type struct { + Codec Codec + Name string + OID uint32 +} + +// Map is the mapping between PostgreSQL server types and Go type handling logic. It can encode values for +// transmission to a PostgreSQL server and scan received values. +type Map struct { + oidToType map[uint32]*Type + nameToType map[string]*Type + reflectTypeToName map[reflect.Type]string + oidToFormatCode map[uint32]int16 + + reflectTypeToType map[reflect.Type]*Type + + memoizedEncodePlans map[uint32]map[reflect.Type][2]EncodePlan + + // TryWrapEncodePlanFuncs is a slice of functions that will wrap a value that cannot be encoded by the Codec. Every + // time a wrapper is found the PlanEncode method will be recursively called with the new value. This allows several layers of wrappers + // to be built up. There are default functions placed in this slice by NewMap(). In most cases these functions + // should run last. i.e. Additional functions should typically be prepended not appended. + TryWrapEncodePlanFuncs []TryWrapEncodePlanFunc + + // TryWrapScanPlanFuncs is a slice of functions that will wrap a target that cannot be scanned into by the Codec. Every + // time a wrapper is found the PlanScan method will be recursively called with the new target. This allows several layers of wrappers + // to be built up. There are default functions placed in this slice by NewMap(). In most cases these functions + // should run last. i.e. Additional functions should typically be prepended not appended. + TryWrapScanPlanFuncs []TryWrapScanPlanFunc +} + +// Copy returns a new Map containing the same registered types. +func (m *Map) Copy() *Map { + newMap := NewMap() + for _, type_ := range m.oidToType { + newMap.RegisterType(type_) + } + return newMap +} + +func NewMap() *Map { + defaultMapInitOnce.Do(initDefaultMap) + + return &Map{ + oidToType: make(map[uint32]*Type), + nameToType: make(map[string]*Type), + reflectTypeToName: make(map[reflect.Type]string), + oidToFormatCode: make(map[uint32]int16), + + memoizedEncodePlans: make(map[uint32]map[reflect.Type][2]EncodePlan), + + TryWrapEncodePlanFuncs: []TryWrapEncodePlanFunc{ + TryWrapDerefPointerEncodePlan, + TryWrapBuiltinTypeEncodePlan, + TryWrapFindUnderlyingTypeEncodePlan, + TryWrapStringerEncodePlan, + TryWrapStructEncodePlan, + TryWrapSliceEncodePlan, + TryWrapMultiDimSliceEncodePlan, + TryWrapArrayEncodePlan, + }, + + TryWrapScanPlanFuncs: []TryWrapScanPlanFunc{ + TryPointerPointerScanPlan, + TryWrapBuiltinTypeScanPlan, + TryFindUnderlyingTypeScanPlan, + TryWrapStructScanPlan, + TryWrapPtrSliceScanPlan, + TryWrapPtrMultiDimSliceScanPlan, + TryWrapPtrArrayScanPlan, + }, + } +} + +// RegisterTypes registers multiple data types in the sequence they are provided. +func (m *Map) RegisterTypes(types []*Type) { + for _, t := range types { + m.RegisterType(t) + } +} + +// RegisterType registers a data type with the [Map]. t must not be mutated after it is registered. +func (m *Map) RegisterType(t *Type) { + m.oidToType[t.OID] = t + m.nameToType[t.Name] = t + m.oidToFormatCode[t.OID] = t.Codec.PreferredFormat() + + // Invalidated by type registration + m.reflectTypeToType = nil + for k := range m.memoizedEncodePlans { + delete(m.memoizedEncodePlans, k) + } +} + +// RegisterDefaultPgType registers a mapping of a Go type to a PostgreSQL type name. Typically the data type to be +// encoded or decoded is determined by the PostgreSQL OID. But if the OID of a value to be encoded or decoded is +// unknown, this additional mapping will be used by TypeForValue to determine a suitable data type. +func (m *Map) RegisterDefaultPgType(value any, name string) { + m.reflectTypeToName[reflect.TypeOf(value)] = name + + // Invalidated by type registration + m.reflectTypeToType = nil + for k := range m.memoizedEncodePlans { + delete(m.memoizedEncodePlans, k) + } +} + +// TypeForOID returns the [Type] registered for the given OID. The returned [Type] must not be mutated. +func (m *Map) TypeForOID(oid uint32) (*Type, bool) { + if dt, ok := m.oidToType[oid]; ok { + return dt, true + } + + dt, ok := defaultMap.oidToType[oid] + return dt, ok +} + +// TypeForName returns the [Type] registered for the given name. The returned [Type] must not be mutated. +func (m *Map) TypeForName(name string) (*Type, bool) { + if dt, ok := m.nameToType[name]; ok { + return dt, true + } + dt, ok := defaultMap.nameToType[name] + return dt, ok +} + +func (m *Map) buildReflectTypeToType() { + m.reflectTypeToType = make(map[reflect.Type]*Type) + + for reflectType, name := range m.reflectTypeToName { + if dt, ok := m.TypeForName(name); ok { + m.reflectTypeToType[reflectType] = dt + } + } +} + +// TypeForValue finds a data type suitable for v. Use [Map.RegisterType] to register types that can encode and decode +// themselves. Use [Map.RegisterDefaultPgType] to register that can be handled by a registered data type. The returned [Type] +// must not be mutated. +func (m *Map) TypeForValue(v any) (*Type, bool) { + if m.reflectTypeToType == nil { + m.buildReflectTypeToType() + } + + if dt, ok := m.reflectTypeToType[reflect.TypeOf(v)]; ok { + return dt, true + } + + dt, ok := defaultMap.reflectTypeToType[reflect.TypeOf(v)] + return dt, ok +} + +// FormatCodeForOID returns the preferred format code for type oid. If the type is not registered it returns the text +// format code. +func (m *Map) FormatCodeForOID(oid uint32) int16 { + if fc, ok := m.oidToFormatCode[oid]; ok { + return fc + } + + if fc, ok := defaultMap.oidToFormatCode[oid]; ok { + return fc + } + + return TextFormatCode +} + +// EncodePlan is a precompiled plan to encode a particular type into a particular OID and format. +type EncodePlan interface { + // Encode appends the encoded bytes of value to buf. If value is the SQL value NULL then append nothing and return + // (nil, nil). The caller of Encode is responsible for writing the correct NULL value or the length of the data + // written. + Encode(value any, buf []byte) (newBuf []byte, err error) +} + +// ScanPlan is a precompiled plan to scan into a type of destination. +type ScanPlan interface { + // Scan scans src into target. src is only valid during the call to Scan. The ScanPlan must not retain a reference to + // src. + Scan(src []byte, target any) error +} + +type scanPlanCodecSQLScanner struct { + c Codec + m *Map + oid uint32 + formatCode int16 +} + +func (plan *scanPlanCodecSQLScanner) Scan(src []byte, dst any) error { + value, err := plan.c.DecodeDatabaseSQLValue(plan.m, plan.oid, plan.formatCode, src) + if err != nil { + return err + } + + scanner := dst.(sql.Scanner) + return scanner.Scan(value) +} + +type scanPlanSQLScanner struct { + formatCode int16 +} + +func (plan *scanPlanSQLScanner) Scan(src []byte, dst any) error { + scanner := dst.(sql.Scanner) + + switch { + case src == nil: + // This is necessary because interface value []byte:nil does not equal nil:nil for the binary format path and the + // text format path would be converted to empty string. + return scanner.Scan(nil) + case plan.formatCode == BinaryFormatCode: + return scanner.Scan(src) + default: + return scanner.Scan(string(src)) + } +} + +type scanPlanString struct{} + +func (scanPlanString) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p := (dst).(*string) + *p = string(src) + return nil +} + +type scanPlanAnyTextToBytes struct{} + +func (scanPlanAnyTextToBytes) Scan(src []byte, dst any) error { + dstBuf := dst.(*[]byte) + if src == nil { + *dstBuf = nil + return nil + } + + *dstBuf = make([]byte, len(src)) + copy(*dstBuf, src) + return nil +} + +type scanPlanFail struct { + m *Map + oid uint32 + formatCode int16 +} + +func (plan *scanPlanFail) Scan(src []byte, dst any) error { + // If src is NULL it might be possible to scan into dst even though it is the types are not compatible. While this + // may seem to be a contrived case it can occur when selecting NULL directly. PostgreSQL assigns it the type of text. + // It would be surprising to the caller to have to cast the NULL (e.g. `select null::int`). So try to figure out a + // compatible data type for dst and scan with that. + // + // See https://github.com/jackc/pgx/issues/1326 + if src == nil { + // As a horrible hack try all types to find anything that can scan into dst. + for oid := range plan.m.oidToType { + // using planScan instead of Scan or PlanScan to avoid polluting the planned scan cache. + plan := plan.m.planScan(oid, plan.formatCode, dst, 0) + if _, ok := plan.(*scanPlanFail); !ok { + return plan.Scan(src, dst) + } + } + for oid := range defaultMap.oidToType { + if _, ok := plan.m.oidToType[oid]; !ok { + plan := plan.m.planScan(oid, plan.formatCode, dst, 0) + if _, ok := plan.(*scanPlanFail); !ok { + return plan.Scan(src, dst) + } + } + } + } + + var format string + switch plan.formatCode { + case TextFormatCode: + format = "text" + case BinaryFormatCode: + format = "binary" + default: + format = fmt.Sprintf("unknown %d", plan.formatCode) + } + + var dataTypeName string + if t, ok := plan.m.TypeForOID(plan.oid); ok { + dataTypeName = t.Name + } else { + dataTypeName = "unknown type" + } + + return fmt.Errorf("cannot scan %s (OID %d) in %v format into %T", dataTypeName, plan.oid, format, dst) +} + +// TryWrapScanPlanFunc is a function that tries to create a wrapper plan for target. If successful it returns a plan +// that will convert the target passed to Scan and then call the next plan. nextTarget is target as it will be converted +// by plan. It must be used to find another suitable ScanPlan. When it is found SetNext must be called on plan for it +// to be usabled. ok indicates if a suitable wrapper was found. +type TryWrapScanPlanFunc func(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool) + +type pointerPointerScanPlan struct { + dstType reflect.Type + next ScanPlan +} + +func (plan *pointerPointerScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *pointerPointerScanPlan) Scan(src []byte, dst any) error { + el := reflect.ValueOf(dst).Elem() + if src == nil { + el.Set(reflect.Zero(el.Type())) + return nil + } + + el.Set(reflect.New(el.Type().Elem())) + return plan.next.Scan(src, el.Interface()) +} + +// TryPointerPointerScanPlan handles a pointer to a pointer by setting the target to nil for SQL NULL and allocating and +// scanning for non-NULL. +func TryPointerPointerScanPlan(target any) (plan WrappedScanPlanNextSetter, nextTarget any, ok bool) { + if dstValue := reflect.ValueOf(target); dstValue.Kind() == reflect.Pointer { + elemValue := dstValue.Elem() + if elemValue.Kind() == reflect.Pointer { + plan = &pointerPointerScanPlan{dstType: dstValue.Type()} + return plan, reflect.Zero(elemValue.Type()).Interface(), true + } + } + + return nil, nil, false +} + +// SkipUnderlyingTypePlanner prevents PlanScan and PlanDecode from trying to use the underlying type. +type SkipUnderlyingTypePlanner interface { + SkipUnderlyingTypePlan() +} + +var elemKindToPointerTypes map[reflect.Kind]reflect.Type = map[reflect.Kind]reflect.Type{ + reflect.Int: reflect.TypeFor[*int](), + reflect.Int8: reflect.TypeFor[*int8](), + reflect.Int16: reflect.TypeFor[*int16](), + reflect.Int32: reflect.TypeFor[*int32](), + reflect.Int64: reflect.TypeFor[*int64](), + reflect.Uint: reflect.TypeFor[*uint](), + reflect.Uint8: reflect.TypeFor[*uint8](), + reflect.Uint16: reflect.TypeFor[*uint16](), + reflect.Uint32: reflect.TypeFor[*uint32](), + reflect.Uint64: reflect.TypeFor[*uint64](), + reflect.Float32: reflect.TypeFor[*float32](), + reflect.Float64: reflect.TypeFor[*float64](), + reflect.String: reflect.TypeFor[*string](), + reflect.Bool: reflect.TypeFor[*bool](), +} + +type underlyingTypeScanPlan struct { + dstType reflect.Type + nextDstType reflect.Type + next ScanPlan +} + +func (plan *underlyingTypeScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *underlyingTypeScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, reflect.ValueOf(dst).Convert(plan.nextDstType).Interface()) +} + +// TryFindUnderlyingTypeScanPlan tries to convert to a Go builtin type. e.g. If value was of type MyString and +// MyString was defined as a string then a wrapper plan would be returned that converts MyString to string. +func TryFindUnderlyingTypeScanPlan(dst any) (plan WrappedScanPlanNextSetter, nextDst any, ok bool) { + if _, ok := dst.(SkipUnderlyingTypePlanner); ok { + return nil, nil, false + } + + dstValue := reflect.ValueOf(dst) + + if dstValue.Kind() == reflect.Pointer { + var elemValue reflect.Value + if dstValue.IsNil() { + elemValue = reflect.New(dstValue.Type().Elem()).Elem() + } else { + elemValue = dstValue.Elem() + } + nextDstType := elemKindToPointerTypes[elemValue.Kind()] + if nextDstType == nil { + if elemValue.Kind() == reflect.Slice { + if elemValue.Type().Elem().Kind() == reflect.Uint8 { + var v *[]byte + nextDstType = reflect.TypeOf(v) + } + } + + // Get underlying type of any array. + // https://github.com/jackc/pgx/issues/2107 + if elemValue.Kind() == reflect.Array { + nextDstType = reflect.PointerTo(reflect.ArrayOf(elemValue.Len(), elemValue.Type().Elem())) + } + } + + if nextDstType != nil && dstValue.Type() != nextDstType && dstValue.CanConvert(nextDstType) { + return &underlyingTypeScanPlan{dstType: dstValue.Type(), nextDstType: nextDstType}, dstValue.Convert(nextDstType).Interface(), true + } + } + + return nil, nil, false +} + +type WrappedScanPlanNextSetter interface { + SetNext(ScanPlan) + ScanPlan +} + +// TryWrapBuiltinTypeScanPlan tries to wrap a builtin type with a wrapper that provides additional methods. e.g. If +// value was of type int32 then a wrapper plan would be returned that converts target to a value that implements +// Int64Scanner. +func TryWrapBuiltinTypeScanPlan(target any) (plan WrappedScanPlanNextSetter, nextDst any, ok bool) { + switch target := target.(type) { + case *int8: + return &wrapInt8ScanPlan{}, (*int8Wrapper)(target), true + case *int16: + return &wrapInt16ScanPlan{}, (*int16Wrapper)(target), true + case *int32: + return &wrapInt32ScanPlan{}, (*int32Wrapper)(target), true + case *int64: + return &wrapInt64ScanPlan{}, (*int64Wrapper)(target), true + case *int: + return &wrapIntScanPlan{}, (*intWrapper)(target), true + case *uint8: + return &wrapUint8ScanPlan{}, (*uint8Wrapper)(target), true + case *uint16: + return &wrapUint16ScanPlan{}, (*uint16Wrapper)(target), true + case *uint32: + return &wrapUint32ScanPlan{}, (*uint32Wrapper)(target), true + case *uint64: + return &wrapUint64ScanPlan{}, (*uint64Wrapper)(target), true + case *uint: + return &wrapUintScanPlan{}, (*uintWrapper)(target), true + case *float32: + return &wrapFloat32ScanPlan{}, (*float32Wrapper)(target), true + case *float64: + return &wrapFloat64ScanPlan{}, (*float64Wrapper)(target), true + case *string: + return &wrapStringScanPlan{}, (*stringWrapper)(target), true + case *time.Time: + return &wrapTimeScanPlan{}, (*timeWrapper)(target), true + case *time.Duration: + return &wrapDurationScanPlan{}, (*durationWrapper)(target), true + case *net.IPNet: + return &wrapNetIPNetScanPlan{}, (*netIPNetWrapper)(target), true + case *net.IP: + return &wrapNetIPScanPlan{}, (*netIPWrapper)(target), true + case *netip.Prefix: + return &wrapNetipPrefixScanPlan{}, (*netipPrefixWrapper)(target), true + case *netip.Addr: + return &wrapNetipAddrScanPlan{}, (*netipAddrWrapper)(target), true + case *map[string]*string: + return &wrapMapStringToPointerStringScanPlan{}, (*mapStringToPointerStringWrapper)(target), true + case *map[string]string: + return &wrapMapStringToStringScanPlan{}, (*mapStringToStringWrapper)(target), true + case *[16]byte: + return &wrapByte16ScanPlan{}, (*byte16Wrapper)(target), true + case *[]byte: + return &wrapByteSliceScanPlan{}, (*byteSliceWrapper)(target), true + } + + return nil, nil, false +} + +type wrapInt8ScanPlan struct { + next ScanPlan +} + +func (plan *wrapInt8ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapInt8ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*int8Wrapper)(dst.(*int8))) +} + +type wrapInt16ScanPlan struct { + next ScanPlan +} + +func (plan *wrapInt16ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapInt16ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*int16Wrapper)(dst.(*int16))) +} + +type wrapInt32ScanPlan struct { + next ScanPlan +} + +func (plan *wrapInt32ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapInt32ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*int32Wrapper)(dst.(*int32))) +} + +type wrapInt64ScanPlan struct { + next ScanPlan +} + +func (plan *wrapInt64ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapInt64ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*int64Wrapper)(dst.(*int64))) +} + +type wrapIntScanPlan struct { + next ScanPlan +} + +func (plan *wrapIntScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapIntScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*intWrapper)(dst.(*int))) +} + +type wrapUint8ScanPlan struct { + next ScanPlan +} + +func (plan *wrapUint8ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapUint8ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*uint8Wrapper)(dst.(*uint8))) +} + +type wrapUint16ScanPlan struct { + next ScanPlan +} + +func (plan *wrapUint16ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapUint16ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*uint16Wrapper)(dst.(*uint16))) +} + +type wrapUint32ScanPlan struct { + next ScanPlan +} + +func (plan *wrapUint32ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapUint32ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*uint32Wrapper)(dst.(*uint32))) +} + +type wrapUint64ScanPlan struct { + next ScanPlan +} + +func (plan *wrapUint64ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapUint64ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*uint64Wrapper)(dst.(*uint64))) +} + +type wrapUintScanPlan struct { + next ScanPlan +} + +func (plan *wrapUintScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapUintScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*uintWrapper)(dst.(*uint))) +} + +type wrapFloat32ScanPlan struct { + next ScanPlan +} + +func (plan *wrapFloat32ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapFloat32ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*float32Wrapper)(dst.(*float32))) +} + +type wrapFloat64ScanPlan struct { + next ScanPlan +} + +func (plan *wrapFloat64ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapFloat64ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*float64Wrapper)(dst.(*float64))) +} + +type wrapStringScanPlan struct { + next ScanPlan +} + +func (plan *wrapStringScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapStringScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*stringWrapper)(dst.(*string))) +} + +type wrapTimeScanPlan struct { + next ScanPlan +} + +func (plan *wrapTimeScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapTimeScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*timeWrapper)(dst.(*time.Time))) +} + +type wrapDurationScanPlan struct { + next ScanPlan +} + +func (plan *wrapDurationScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapDurationScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*durationWrapper)(dst.(*time.Duration))) +} + +type wrapNetIPNetScanPlan struct { + next ScanPlan +} + +func (plan *wrapNetIPNetScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapNetIPNetScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*netIPNetWrapper)(dst.(*net.IPNet))) +} + +type wrapNetIPScanPlan struct { + next ScanPlan +} + +func (plan *wrapNetIPScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapNetIPScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*netIPWrapper)(dst.(*net.IP))) +} + +type wrapNetipPrefixScanPlan struct { + next ScanPlan +} + +func (plan *wrapNetipPrefixScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapNetipPrefixScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*netipPrefixWrapper)(dst.(*netip.Prefix))) +} + +type wrapNetipAddrScanPlan struct { + next ScanPlan +} + +func (plan *wrapNetipAddrScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapNetipAddrScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*netipAddrWrapper)(dst.(*netip.Addr))) +} + +type wrapMapStringToPointerStringScanPlan struct { + next ScanPlan +} + +func (plan *wrapMapStringToPointerStringScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapMapStringToPointerStringScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*mapStringToPointerStringWrapper)(dst.(*map[string]*string))) +} + +type wrapMapStringToStringScanPlan struct { + next ScanPlan +} + +func (plan *wrapMapStringToStringScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapMapStringToStringScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*mapStringToStringWrapper)(dst.(*map[string]string))) +} + +type wrapByte16ScanPlan struct { + next ScanPlan +} + +func (plan *wrapByte16ScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapByte16ScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*byte16Wrapper)(dst.(*[16]byte))) +} + +type wrapByteSliceScanPlan struct { + next ScanPlan +} + +func (plan *wrapByteSliceScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapByteSliceScanPlan) Scan(src []byte, dst any) error { + return plan.next.Scan(src, (*byteSliceWrapper)(dst.(*[]byte))) +} + +type pointerEmptyInterfaceScanPlan struct { + codec Codec + m *Map + oid uint32 + formatCode int16 +} + +func (plan *pointerEmptyInterfaceScanPlan) Scan(src []byte, dst any) error { + value, err := plan.codec.DecodeValue(plan.m, plan.oid, plan.formatCode, src) + if err != nil { + return err + } + + ptrAny := dst.(*any) + *ptrAny = value + + return nil +} + +// TryWrapStructScanPlan tries to wrap a struct with a wrapper that implements CompositeIndexGetter. +func TryWrapStructScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { + targetValue := reflect.ValueOf(target) + if targetValue.Kind() != reflect.Pointer { + return nil, nil, false + } + + var targetElemValue reflect.Value + if targetValue.IsNil() { + targetElemValue = reflect.Zero(targetValue.Type().Elem()) + } else { + targetElemValue = targetValue.Elem() + } + targetElemType := targetElemValue.Type() + + if targetElemType.Kind() == reflect.Struct { + exportedFields := getExportedFieldValues(targetElemValue) + if len(exportedFields) == 0 { + return nil, nil, false + } + + w := ptrStructWrapper{ + s: target, + exportedFields: exportedFields, + } + return &wrapAnyPtrStructScanPlan{}, &w, true + } + + return nil, nil, false +} + +type wrapAnyPtrStructScanPlan struct { + next ScanPlan +} + +func (plan *wrapAnyPtrStructScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapAnyPtrStructScanPlan) Scan(src []byte, target any) error { + w := ptrStructWrapper{ + s: target, + exportedFields: getExportedFieldValues(reflect.ValueOf(target).Elem()), + } + + return plan.next.Scan(src, &w) +} + +// TryWrapPtrSliceScanPlan tries to wrap a pointer to a single dimension slice. +func TryWrapPtrSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { + // Avoid using reflect path for common types. + switch target := target.(type) { + case *[]int16: + return &wrapPtrSliceScanPlan[int16]{}, (*FlatArray[int16])(target), true + case *[]int32: + return &wrapPtrSliceScanPlan[int32]{}, (*FlatArray[int32])(target), true + case *[]int64: + return &wrapPtrSliceScanPlan[int64]{}, (*FlatArray[int64])(target), true + case *[]float32: + return &wrapPtrSliceScanPlan[float32]{}, (*FlatArray[float32])(target), true + case *[]float64: + return &wrapPtrSliceScanPlan[float64]{}, (*FlatArray[float64])(target), true + case *[]string: + return &wrapPtrSliceScanPlan[string]{}, (*FlatArray[string])(target), true + case *[]time.Time: + return &wrapPtrSliceScanPlan[time.Time]{}, (*FlatArray[time.Time])(target), true + } + + targetType := reflect.TypeOf(target) + if targetType.Kind() != reflect.Pointer { + return nil, nil, false + } + + targetElemType := targetType.Elem() + + if targetElemType.Kind() == reflect.Slice { + slice := reflect.New(targetElemType).Elem() + return &wrapPtrSliceReflectScanPlan{}, &anySliceArrayReflect{slice: slice}, true + } + return nil, nil, false +} + +type wrapPtrSliceScanPlan[T any] struct { + next ScanPlan +} + +func (plan *wrapPtrSliceScanPlan[T]) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapPtrSliceScanPlan[T]) Scan(src []byte, target any) error { + return plan.next.Scan(src, (*FlatArray[T])(target.(*[]T))) +} + +type wrapPtrSliceReflectScanPlan struct { + next ScanPlan +} + +func (plan *wrapPtrSliceReflectScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapPtrSliceReflectScanPlan) Scan(src []byte, target any) error { + return plan.next.Scan(src, &anySliceArrayReflect{slice: reflect.ValueOf(target).Elem()}) +} + +// TryWrapPtrMultiDimSliceScanPlan tries to wrap a pointer to a multi-dimension slice. +func TryWrapPtrMultiDimSliceScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { + targetValue := reflect.ValueOf(target) + if targetValue.Kind() != reflect.Pointer { + return nil, nil, false + } + + targetElemValue := targetValue.Elem() + + if targetElemValue.Kind() == reflect.Slice { + elemElemKind := targetElemValue.Type().Elem().Kind() + if elemElemKind == reflect.Slice { + if !isRagged(targetElemValue) { + return &wrapPtrMultiDimSliceScanPlan{}, &anyMultiDimSliceArray{slice: targetValue.Elem()}, true + } + } + } + + return nil, nil, false +} + +type wrapPtrMultiDimSliceScanPlan struct { + next ScanPlan +} + +func (plan *wrapPtrMultiDimSliceScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapPtrMultiDimSliceScanPlan) Scan(src []byte, target any) error { + return plan.next.Scan(src, &anyMultiDimSliceArray{slice: reflect.ValueOf(target).Elem()}) +} + +// TryWrapPtrArrayScanPlan tries to wrap a pointer to a single dimension array. +func TryWrapPtrArrayScanPlan(target any) (plan WrappedScanPlanNextSetter, nextValue any, ok bool) { + targetValue := reflect.ValueOf(target) + if targetValue.Kind() != reflect.Pointer { + return nil, nil, false + } + + targetElemValue := targetValue.Elem() + + if targetElemValue.Kind() == reflect.Array { + return &wrapPtrArrayReflectScanPlan{}, &anyArrayArrayReflect{array: targetElemValue}, true + } + return nil, nil, false +} + +type wrapPtrArrayReflectScanPlan struct { + next ScanPlan +} + +func (plan *wrapPtrArrayReflectScanPlan) SetNext(next ScanPlan) { plan.next = next } + +func (plan *wrapPtrArrayReflectScanPlan) Scan(src []byte, target any) error { + return plan.next.Scan(src, &anyArrayArrayReflect{array: reflect.ValueOf(target).Elem()}) +} + +// PlanScan prepares a plan to scan a value into target. +func (m *Map) PlanScan(oid uint32, formatCode int16, target any) ScanPlan { + return m.planScan(oid, formatCode, target, 0) +} + +func (m *Map) planScan(oid uint32, formatCode int16, target any, depth int) ScanPlan { + if depth > 8 { + return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} + } + + if target == nil { + return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} + } + + if _, ok := target.(*UndecodedBytes); ok { + return scanPlanAnyToUndecodedBytes{} + } + + switch formatCode { + case BinaryFormatCode: + if _, ok := target.(*string); ok { + switch oid { + case TextOID, VarcharOID: + return scanPlanString{} + } + } + case TextFormatCode: + switch target.(type) { + case *string: + return scanPlanString{} + case *[]byte: + if oid != ByteaOID { + return scanPlanAnyTextToBytes{} + } + case TextScanner: + return scanPlanTextAnyToTextScanner{} + } + } + + var dt *Type + + if dataType, ok := m.TypeForOID(oid); ok { + dt = dataType + } else if dataType, ok := m.TypeForValue(target); ok { + dt = dataType + oid = dt.OID // Preserve assumed OID in case we are recursively called below. + } + + if dt != nil { + if plan := dt.Codec.PlanScan(m, oid, formatCode, target); plan != nil { + return plan + } + } + + // This needs to happen before trying m.TryWrapScanPlanFuncs. Otherwise, a sql.Scanner would not get called if it was + // defined on a type that could be unwrapped such as `type myString string`. + // + // https://github.com/jackc/pgtype/issues/197 + if _, ok := target.(sql.Scanner); ok { + if dt == nil { + return &scanPlanSQLScanner{formatCode: formatCode} + } else { + return &scanPlanCodecSQLScanner{c: dt.Codec, m: m, oid: oid, formatCode: formatCode} + } + } + + for _, f := range m.TryWrapScanPlanFuncs { + if wrapperPlan, nextDst, ok := f(target); ok { + if nextPlan := m.planScan(oid, formatCode, nextDst, depth+1); nextPlan != nil { + if _, failed := nextPlan.(*scanPlanFail); !failed { + wrapperPlan.SetNext(nextPlan) + return wrapperPlan + } + } + } + } + + if _, ok := target.(*any); ok { + var codec Codec + if dt != nil { + codec = dt.Codec + } else { + if formatCode == TextFormatCode { + codec = TextCodec{} + } else { + codec = ByteaCodec{} + } + } + return &pointerEmptyInterfaceScanPlan{codec: codec, m: m, oid: oid, formatCode: formatCode} + } + + return &scanPlanFail{m: m, oid: oid, formatCode: formatCode} +} + +func (m *Map) Scan(oid uint32, formatCode int16, src []byte, dst any) error { + if dst == nil { + return nil + } + + plan := m.PlanScan(oid, formatCode, dst) + return plan.Scan(src, dst) +} + +var ErrScanTargetTypeChanged = errors.New("scan target type changed") + +func codecScan(codec Codec, m *Map, oid uint32, format int16, src []byte, dst any) error { + scanPlan := codec.PlanScan(m, oid, format, dst) + if scanPlan == nil { + return fmt.Errorf("PlanScan did not find a plan") + } + return scanPlan.Scan(src, dst) +} + +func codecDecodeToTextFormat(codec Codec, m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + if format == TextFormatCode { + return string(src), nil + } else { + value, err := codec.DecodeValue(m, oid, format, src) + if err != nil { + return nil, err + } + buf, err := m.Encode(oid, TextFormatCode, value, nil) + if err != nil { + return nil, err + } + return string(buf), nil + } +} + +// PlanEncode returns an EncodePlan for encoding value into PostgreSQL format for oid and format. If no plan can be +// found then nil is returned. +func (m *Map) PlanEncode(oid uint32, format int16, value any) EncodePlan { + return m.planEncodeDepth(oid, format, value, 0) +} + +func (m *Map) planEncodeDepth(oid uint32, format int16, value any, depth int) EncodePlan { + // Guard against infinite recursion. + if depth > 8 { + return nil + } + + oidMemo := m.memoizedEncodePlans[oid] + if oidMemo == nil { + oidMemo = make(map[reflect.Type][2]EncodePlan) + m.memoizedEncodePlans[oid] = oidMemo + } + targetReflectType := reflect.TypeOf(value) + typeMemo := oidMemo[targetReflectType] + plan := typeMemo[format] + if plan == nil { + plan = m.planEncode(oid, format, value, depth) + typeMemo[format] = plan + oidMemo[targetReflectType] = typeMemo + } + + return plan +} + +func (m *Map) planEncode(oid uint32, format int16, value any, depth int) EncodePlan { + if format == TextFormatCode { + switch value.(type) { + case string: + return encodePlanStringToAnyTextFormat{} + case TextValuer: + return encodePlanTextValuerToAnyTextFormat{} + } + } + + var dt *Type + if dataType, ok := m.TypeForOID(oid); ok { + dt = dataType + } else { + // If no type for the OID was found, then either it is unknowable (e.g. the simple protocol) or it is an + // unregistered type. In either case try to find the type and OID that matches the value (e.g. a []byte would be + // registered to PostgreSQL bytea). + if dataType, ok := m.TypeForValue(value); ok { + dt = dataType + oid = dt.OID // Preserve assumed OID in case we are recursively called below. + } + } + + if dt != nil { + if plan := dt.Codec.PlanEncode(m, oid, format, value); plan != nil { + return plan + } + } + + for _, f := range m.TryWrapEncodePlanFuncs { + if wrapperPlan, nextValue, ok := f(value); ok { + if nextPlan := m.planEncodeDepth(oid, format, nextValue, depth+1); nextPlan != nil { + wrapperPlan.SetNext(nextPlan) + return wrapperPlan + } + } + } + + if _, ok := value.(driver.Valuer); ok { + return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} + } + + return nil +} + +type encodePlanStringToAnyTextFormat struct{} + +func (encodePlanStringToAnyTextFormat) Encode(value any, buf []byte) (newBuf []byte, err error) { + s := value.(string) + return append(buf, s...), nil +} + +type encodePlanTextValuerToAnyTextFormat struct{} + +func (encodePlanTextValuerToAnyTextFormat) Encode(value any, buf []byte) (newBuf []byte, err error) { + t, err := value.(TextValuer).TextValue() + if err != nil { + return nil, err + } + if !t.Valid { + return nil, nil + } + + return append(buf, t.String...), nil +} + +type encodePlanDriverValuer struct { + m *Map + oid uint32 + formatCode int16 +} + +func (plan *encodePlanDriverValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + dv := value.(driver.Valuer) + if dv == nil { + return nil, nil + } + v, err := dv.Value() + if err != nil { + return nil, err + } + if v == nil { + return nil, nil + } + + newBuf, err = plan.m.Encode(plan.oid, plan.formatCode, v, buf) + if err == nil { + return newBuf, nil + } + + s, ok := v.(string) + if !ok { + return nil, err + } + + var scannedValue any + scanErr := plan.m.Scan(plan.oid, TextFormatCode, []byte(s), &scannedValue) + if scanErr != nil { + return nil, err + } + + // Prevent infinite loop. We can't encode this. See https://github.com/jackc/pgx/issues/1331. + if reflect.TypeOf(value) == reflect.TypeOf(scannedValue) { + return nil, fmt.Errorf("tried to encode %v via encoding to text and scanning but failed due to receiving same type back", value) + } + + var err2 error + newBuf, err2 = plan.m.Encode(plan.oid, BinaryFormatCode, scannedValue, buf) + if err2 != nil { + return nil, err + } + + return newBuf, nil +} + +// TryWrapEncodePlanFunc is a function that tries to create a wrapper plan for value. If successful it returns a plan +// that will convert the value passed to Encode and then call the next plan. nextValue is value as it will be converted +// by plan. It must be used to find another suitable EncodePlan. When it is found SetNext must be called on plan for it +// to be usabled. ok indicates if a suitable wrapper was found. +type TryWrapEncodePlanFunc func(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) + +type derefPointerEncodePlan struct { + next EncodePlan +} + +func (plan *derefPointerEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *derefPointerEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + ptr := reflect.ValueOf(value) + + if ptr.IsNil() { + return nil, nil + } + + return plan.next.Encode(ptr.Elem().Interface(), buf) +} + +// TryWrapDerefPointerEncodePlan tries to dereference a pointer. e.g. If value was of type *string then a wrapper plan +// would be returned that dereferences the value. +func TryWrapDerefPointerEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Pointer { + return &derefPointerEncodePlan{}, reflect.New(valueType.Elem()).Elem().Interface(), true + } + + return nil, nil, false +} + +var kindToTypes map[reflect.Kind]reflect.Type = map[reflect.Kind]reflect.Type{ + reflect.Int: reflect.TypeFor[int](), + reflect.Int8: reflect.TypeFor[int8](), + reflect.Int16: reflect.TypeFor[int16](), + reflect.Int32: reflect.TypeFor[int32](), + reflect.Int64: reflect.TypeFor[int64](), + reflect.Uint: reflect.TypeFor[uint](), + reflect.Uint8: reflect.TypeFor[uint8](), + reflect.Uint16: reflect.TypeFor[uint16](), + reflect.Uint32: reflect.TypeFor[uint32](), + reflect.Uint64: reflect.TypeFor[uint64](), + reflect.Float32: reflect.TypeFor[float32](), + reflect.Float64: reflect.TypeFor[float64](), + reflect.String: reflect.TypeFor[string](), + reflect.Bool: reflect.TypeFor[bool](), +} + +var byteSliceType = reflect.TypeFor[[]byte]() + +type underlyingTypeEncodePlan struct { + nextValueType reflect.Type + next EncodePlan +} + +func (plan *underlyingTypeEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *underlyingTypeEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(reflect.ValueOf(value).Convert(plan.nextValueType).Interface(), buf) +} + +// TryWrapFindUnderlyingTypeEncodePlan tries to convert to a Go builtin type. e.g. If value was of type MyString and +// MyString was defined as a string then a wrapper plan would be returned that converts MyString to string. +func TryWrapFindUnderlyingTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if value == nil { + return nil, nil, false + } + + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + if _, ok := value.(SkipUnderlyingTypePlanner); ok { + return nil, nil, false + } + + refValue := reflect.ValueOf(value) + + nextValueType := kindToTypes[refValue.Kind()] + if nextValueType != nil && refValue.Type() != nextValueType { + return &underlyingTypeEncodePlan{nextValueType: nextValueType}, refValue.Convert(nextValueType).Interface(), true + } + + // []byte is a special case. It is a slice but we treat it as a scalar type. In the case of a named type like + // json.RawMessage which is defined as []byte the underlying type should be considered as []byte. But any other slice + // does not have a special underlying type. + // + // https://github.com/jackc/pgx/issues/1763 + if refValue.Type() != byteSliceType && refValue.Type().AssignableTo(byteSliceType) { + return &underlyingTypeEncodePlan{nextValueType: byteSliceType}, refValue.Convert(byteSliceType).Interface(), true + } + + // Get underlying type of any array. + // https://github.com/jackc/pgx/issues/2107 + if refValue.Kind() == reflect.Array { + underlyingArrayType := reflect.ArrayOf(refValue.Len(), refValue.Type().Elem()) + if refValue.Type() != underlyingArrayType { + return &underlyingTypeEncodePlan{nextValueType: underlyingArrayType}, refValue.Convert(underlyingArrayType).Interface(), true + } + } + + return nil, nil, false +} + +// TryWrapStringerEncodePlan tries to wrap a fmt.Stringer type with a wrapper that provides TextValuer. This is +// intentionally a separate function from TryWrapBuiltinTypeEncodePlan so it can be ordered after +// TryWrapFindUnderlyingTypeEncodePlan. This ensures that named types with an underlying builtin type (e.g. type MyEnum +// int32 with a String() method) prefer encoding via the underlying type's codec (e.g. as an integer) rather than via +// Stringer. Stringer is only used as a fallback when no type-specific encoding plan succeeds. +// (https://github.com/jackc/pgx/discussions/2527) +func TryWrapStringerEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + if s, ok := value.(fmt.Stringer); ok { + return &wrapFmtStringerEncodePlan{}, fmtStringerWrapper{s}, true + } + + return nil, nil, false +} + +type WrappedEncodePlanNextSetter interface { + SetNext(EncodePlan) + EncodePlan +} + +// TryWrapBuiltinTypeEncodePlan tries to wrap a builtin type with a wrapper that provides additional methods. e.g. If +// value was of type int32 then a wrapper plan would be returned that converts value to a type that implements +// Int64Valuer. +func TryWrapBuiltinTypeEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + switch value := value.(type) { + case int8: + return &wrapInt8EncodePlan{}, int8Wrapper(value), true + case int16: + return &wrapInt16EncodePlan{}, int16Wrapper(value), true + case int32: + return &wrapInt32EncodePlan{}, int32Wrapper(value), true + case int64: + return &wrapInt64EncodePlan{}, int64Wrapper(value), true + case int: + return &wrapIntEncodePlan{}, intWrapper(value), true + case uint8: + return &wrapUint8EncodePlan{}, uint8Wrapper(value), true + case uint16: + return &wrapUint16EncodePlan{}, uint16Wrapper(value), true + case uint32: + return &wrapUint32EncodePlan{}, uint32Wrapper(value), true + case uint64: + return &wrapUint64EncodePlan{}, uint64Wrapper(value), true + case uint: + return &wrapUintEncodePlan{}, uintWrapper(value), true + case float32: + return &wrapFloat32EncodePlan{}, float32Wrapper(value), true + case float64: + return &wrapFloat64EncodePlan{}, float64Wrapper(value), true + case string: + return &wrapStringEncodePlan{}, stringWrapper(value), true + case time.Time: + return &wrapTimeEncodePlan{}, timeWrapper(value), true + case time.Duration: + return &wrapDurationEncodePlan{}, durationWrapper(value), true + case net.IPNet: + return &wrapNetIPNetEncodePlan{}, netIPNetWrapper(value), true + case net.IP: + return &wrapNetIPEncodePlan{}, netIPWrapper(value), true + case netip.Prefix: + return &wrapNetipPrefixEncodePlan{}, netipPrefixWrapper(value), true + case netip.Addr: + return &wrapNetipAddrEncodePlan{}, netipAddrWrapper(value), true + case map[string]*string: + return &wrapMapStringToPointerStringEncodePlan{}, mapStringToPointerStringWrapper(value), true + case map[string]string: + return &wrapMapStringToStringEncodePlan{}, mapStringToStringWrapper(value), true + case [16]byte: + return &wrapByte16EncodePlan{}, byte16Wrapper(value), true + case []byte: + return &wrapByteSliceEncodePlan{}, byteSliceWrapper(value), true + } + + return nil, nil, false +} + +type wrapInt8EncodePlan struct { + next EncodePlan +} + +func (plan *wrapInt8EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapInt8EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(int8Wrapper(value.(int8)), buf) +} + +type wrapInt16EncodePlan struct { + next EncodePlan +} + +func (plan *wrapInt16EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapInt16EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(int16Wrapper(value.(int16)), buf) +} + +type wrapInt32EncodePlan struct { + next EncodePlan +} + +func (plan *wrapInt32EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapInt32EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(int32Wrapper(value.(int32)), buf) +} + +type wrapInt64EncodePlan struct { + next EncodePlan +} + +func (plan *wrapInt64EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapInt64EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(int64Wrapper(value.(int64)), buf) +} + +type wrapIntEncodePlan struct { + next EncodePlan +} + +func (plan *wrapIntEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapIntEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(intWrapper(value.(int)), buf) +} + +type wrapUint8EncodePlan struct { + next EncodePlan +} + +func (plan *wrapUint8EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapUint8EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(uint8Wrapper(value.(uint8)), buf) +} + +type wrapUint16EncodePlan struct { + next EncodePlan +} + +func (plan *wrapUint16EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapUint16EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(uint16Wrapper(value.(uint16)), buf) +} + +type wrapUint32EncodePlan struct { + next EncodePlan +} + +func (plan *wrapUint32EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapUint32EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(uint32Wrapper(value.(uint32)), buf) +} + +type wrapUint64EncodePlan struct { + next EncodePlan +} + +func (plan *wrapUint64EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapUint64EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(uint64Wrapper(value.(uint64)), buf) +} + +type wrapUintEncodePlan struct { + next EncodePlan +} + +func (plan *wrapUintEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapUintEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(uintWrapper(value.(uint)), buf) +} + +type wrapFloat32EncodePlan struct { + next EncodePlan +} + +func (plan *wrapFloat32EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapFloat32EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(float32Wrapper(value.(float32)), buf) +} + +type wrapFloat64EncodePlan struct { + next EncodePlan +} + +func (plan *wrapFloat64EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapFloat64EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(float64Wrapper(value.(float64)), buf) +} + +type wrapStringEncodePlan struct { + next EncodePlan +} + +func (plan *wrapStringEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapStringEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(stringWrapper(value.(string)), buf) +} + +type wrapTimeEncodePlan struct { + next EncodePlan +} + +func (plan *wrapTimeEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapTimeEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(timeWrapper(value.(time.Time)), buf) +} + +type wrapDurationEncodePlan struct { + next EncodePlan +} + +func (plan *wrapDurationEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapDurationEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(durationWrapper(value.(time.Duration)), buf) +} + +type wrapNetIPNetEncodePlan struct { + next EncodePlan +} + +func (plan *wrapNetIPNetEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapNetIPNetEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(netIPNetWrapper(value.(net.IPNet)), buf) +} + +type wrapNetIPEncodePlan struct { + next EncodePlan +} + +func (plan *wrapNetIPEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapNetIPEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(netIPWrapper(value.(net.IP)), buf) +} + +type wrapNetipPrefixEncodePlan struct { + next EncodePlan +} + +func (plan *wrapNetipPrefixEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapNetipPrefixEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(netipPrefixWrapper(value.(netip.Prefix)), buf) +} + +type wrapNetipAddrEncodePlan struct { + next EncodePlan +} + +func (plan *wrapNetipAddrEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapNetipAddrEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(netipAddrWrapper(value.(netip.Addr)), buf) +} + +type wrapMapStringToPointerStringEncodePlan struct { + next EncodePlan +} + +func (plan *wrapMapStringToPointerStringEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapMapStringToPointerStringEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(mapStringToPointerStringWrapper(value.(map[string]*string)), buf) +} + +type wrapMapStringToStringEncodePlan struct { + next EncodePlan +} + +func (plan *wrapMapStringToStringEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapMapStringToStringEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(mapStringToStringWrapper(value.(map[string]string)), buf) +} + +type wrapByte16EncodePlan struct { + next EncodePlan +} + +func (plan *wrapByte16EncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapByte16EncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(byte16Wrapper(value.([16]byte)), buf) +} + +type wrapByteSliceEncodePlan struct { + next EncodePlan +} + +func (plan *wrapByteSliceEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapByteSliceEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(byteSliceWrapper(value.([]byte)), buf) +} + +type wrapFmtStringerEncodePlan struct { + next EncodePlan +} + +func (plan *wrapFmtStringerEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapFmtStringerEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode(fmtStringerWrapper{value.(fmt.Stringer)}, buf) +} + +// TryWrapStructEncodePlan tries to wrap a struct with a wrapper that implements CompositeIndexGetter. +func TryWrapStructEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Struct { + exportedFields := getExportedFieldValues(reflect.ValueOf(value)) + if len(exportedFields) == 0 { + return nil, nil, false + } + + w := structWrapper{ + s: value, + exportedFields: exportedFields, + } + return &wrapAnyStructEncodePlan{}, w, true + } + + return nil, nil, false +} + +type wrapAnyStructEncodePlan struct { + next EncodePlan +} + +func (plan *wrapAnyStructEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapAnyStructEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + w := structWrapper{ + s: value, + exportedFields: getExportedFieldValues(reflect.ValueOf(value)), + } + + return plan.next.Encode(w, buf) +} + +func getExportedFieldValues(structValue reflect.Value) []reflect.Value { + structType := structValue.Type() + exportedFields := make([]reflect.Value, 0, structValue.NumField()) + for i := 0; i < structType.NumField(); i++ { + sf := structType.Field(i) + if sf.IsExported() { + exportedFields = append(exportedFields, structValue.Field(i)) + } + } + + return exportedFields +} + +func TryWrapSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + // Avoid using reflect path for common types. + switch value := value.(type) { + case []int16: + return &wrapSliceEncodePlan[int16]{}, (FlatArray[int16])(value), true + case []int32: + return &wrapSliceEncodePlan[int32]{}, (FlatArray[int32])(value), true + case []int64: + return &wrapSliceEncodePlan[int64]{}, (FlatArray[int64])(value), true + case []float32: + return &wrapSliceEncodePlan[float32]{}, (FlatArray[float32])(value), true + case []float64: + return &wrapSliceEncodePlan[float64]{}, (FlatArray[float64])(value), true + case []string: + return &wrapSliceEncodePlan[string]{}, (FlatArray[string])(value), true + case []time.Time: + return &wrapSliceEncodePlan[time.Time]{}, (FlatArray[time.Time])(value), true + } + + if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Slice { + w := anySliceArrayReflect{ + slice: reflect.ValueOf(value), + } + return &wrapSliceEncodeReflectPlan{}, w, true + } + + return nil, nil, false +} + +type wrapSliceEncodePlan[T any] struct { + next EncodePlan +} + +func (plan *wrapSliceEncodePlan[T]) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapSliceEncodePlan[T]) Encode(value any, buf []byte) (newBuf []byte, err error) { + return plan.next.Encode((FlatArray[T])(value.([]T)), buf) +} + +type wrapSliceEncodeReflectPlan struct { + next EncodePlan +} + +func (plan *wrapSliceEncodeReflectPlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapSliceEncodeReflectPlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + w := anySliceArrayReflect{ + slice: reflect.ValueOf(value), + } + + return plan.next.Encode(w, buf) +} + +func TryWrapMultiDimSliceEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + sliceValue := reflect.ValueOf(value) + if sliceValue.Kind() == reflect.Slice { + valueElemType := sliceValue.Type().Elem() + + if valueElemType.Kind() == reflect.Slice { + if !isRagged(sliceValue) { + w := anyMultiDimSliceArray{ + slice: reflect.ValueOf(value), + } + return &wrapMultiDimSliceEncodePlan{}, &w, true + } + } + } + + return nil, nil, false +} + +type wrapMultiDimSliceEncodePlan struct { + next EncodePlan +} + +func (plan *wrapMultiDimSliceEncodePlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapMultiDimSliceEncodePlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + w := anyMultiDimSliceArray{ + slice: reflect.ValueOf(value), + } + + return plan.next.Encode(&w, buf) +} + +func TryWrapArrayEncodePlan(value any) (plan WrappedEncodePlanNextSetter, nextValue any, ok bool) { + if _, ok := value.(driver.Valuer); ok { + return nil, nil, false + } + + if valueType := reflect.TypeOf(value); valueType != nil && valueType.Kind() == reflect.Array { + w := anyArrayArrayReflect{ + array: reflect.ValueOf(value), + } + return &wrapArrayEncodeReflectPlan{}, w, true + } + + return nil, nil, false +} + +type wrapArrayEncodeReflectPlan struct { + next EncodePlan +} + +func (plan *wrapArrayEncodeReflectPlan) SetNext(next EncodePlan) { plan.next = next } + +func (plan *wrapArrayEncodeReflectPlan) Encode(value any, buf []byte) (newBuf []byte, err error) { + w := anyArrayArrayReflect{ + array: reflect.ValueOf(value), + } + + return plan.next.Encode(w, buf) +} + +func newEncodeError(value any, m *Map, oid uint32, formatCode int16, err error) error { + var format string + switch formatCode { + case TextFormatCode: + format = "text" + case BinaryFormatCode: + format = "binary" + default: + format = fmt.Sprintf("unknown (%d)", formatCode) + } + + var dataTypeName string + if t, ok := m.TypeForOID(oid); ok { + dataTypeName = t.Name + } else { + dataTypeName = "unknown type" + } + + return fmt.Errorf("unable to encode %#v into %s format for %s (OID %d): %w", value, format, dataTypeName, oid, err) +} + +// Encode appends the encoded bytes of value to buf. If value is the SQL value NULL then append nothing and return +// (nil, nil). The caller of Encode is responsible for writing the correct NULL value or the length of the data +// written. +func (m *Map) Encode(oid uint32, formatCode int16, value any, buf []byte) (newBuf []byte, err error) { + if isNil, callNilDriverValuer := isNilDriverValuer(value); isNil { + if callNilDriverValuer { + newBuf, err = (&encodePlanDriverValuer{m: m, oid: oid, formatCode: formatCode}).Encode(value, buf) + if err != nil { + return nil, newEncodeError(value, m, oid, formatCode, err) + } + + return newBuf, nil + } else { + return nil, nil + } + } + + plan := m.PlanEncode(oid, formatCode, value) + if plan == nil { + return nil, newEncodeError(value, m, oid, formatCode, errors.New("cannot find encode plan")) + } + + newBuf, err = plan.Encode(value, buf) + if err != nil { + return nil, newEncodeError(value, m, oid, formatCode, err) + } + + return newBuf, nil +} + +// SQLScanner returns a database/sql.Scanner for v. This is necessary for types like Array[T] and Range[T] where the +// type needs assistance from Map to implement the sql.Scanner interface. It is not necessary for types like Box that +// implement sql.Scanner directly. +// +// This uses the type of v to look up the PostgreSQL OID that v presumably came from. This means v must be registered +// with m by calling RegisterDefaultPgType. +func (m *Map) SQLScanner(v any) sql.Scanner { + if s, ok := v.(sql.Scanner); ok { + return s + } + + return &sqlScannerWrapper{m: m, v: v} +} + +type sqlScannerWrapper struct { + m *Map + v any +} + +func (w *sqlScannerWrapper) Scan(src any) error { + t, ok := w.m.TypeForValue(w.v) + if !ok { + return fmt.Errorf("cannot convert to sql.Scanner: cannot find registered type for %T", w.v) + } + + var bufSrc []byte + if src != nil { + switch src := src.(type) { + case string: + bufSrc = []byte(src) + case []byte: + bufSrc = src + default: + bufSrc = fmt.Append(nil, bufSrc) + } + } + + return w.m.Scan(t.OID, TextFormatCode, bufSrc, w.v) +} + +var valuerReflectType = reflect.TypeFor[driver.Valuer]() + +// isNilDriverValuer returns true if value is any type of nil unless it implements driver.Valuer. *T is not considered to implement +// driver.Valuer if it is only implemented by T. +func isNilDriverValuer(value any) (isNil, callNilDriverValuer bool) { + if value == nil { + return true, false + } + + refVal := reflect.ValueOf(value) + kind := refVal.Kind() + switch kind { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.UnsafePointer, reflect.Interface, reflect.Slice: + if !refVal.IsNil() { + return false, false + } + + if _, ok := value.(driver.Valuer); ok { + if kind == reflect.Pointer { + // The type assertion will succeed if driver.Valuer is implemented on T or *T. Check if it is implemented on *T + // by checking if it is not implemented on *T. + return true, !refVal.Type().Elem().Implements(valuerReflectType) + } else { + return true, true + } + } + + return true, false + default: + return false, false + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go new file mode 100644 index 0000000..42b39d8 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/pgtype_default.go @@ -0,0 +1,251 @@ +package pgtype + +import ( + "encoding/json" + "encoding/xml" + "net" + "net/netip" + "reflect" + "sync" + "time" +) + +var ( + // defaultMap contains default mappings between PostgreSQL server types and Go type handling logic. + defaultMap *Map + defaultMapInitOnce = sync.Once{} +) + +func initDefaultMap() { + defaultMap = &Map{ + oidToType: make(map[uint32]*Type), + nameToType: make(map[string]*Type), + reflectTypeToName: make(map[reflect.Type]string), + oidToFormatCode: make(map[uint32]int16), + + memoizedEncodePlans: make(map[uint32]map[reflect.Type][2]EncodePlan), + + TryWrapEncodePlanFuncs: []TryWrapEncodePlanFunc{ + TryWrapDerefPointerEncodePlan, + TryWrapBuiltinTypeEncodePlan, + TryWrapFindUnderlyingTypeEncodePlan, + TryWrapStructEncodePlan, + TryWrapSliceEncodePlan, + TryWrapMultiDimSliceEncodePlan, + TryWrapArrayEncodePlan, + }, + + TryWrapScanPlanFuncs: []TryWrapScanPlanFunc{ + TryPointerPointerScanPlan, + TryWrapBuiltinTypeScanPlan, + TryFindUnderlyingTypeScanPlan, + TryWrapStructScanPlan, + TryWrapPtrSliceScanPlan, + TryWrapPtrMultiDimSliceScanPlan, + TryWrapPtrArrayScanPlan, + }, + } + + // Base types + defaultMap.RegisterType(&Type{Name: "aclitem", OID: ACLItemOID, Codec: &TextFormatOnlyCodec{TextCodec{}}}) + defaultMap.RegisterType(&Type{Name: "bit", OID: BitOID, Codec: BitsCodec{}}) + defaultMap.RegisterType(&Type{Name: "bool", OID: BoolOID, Codec: BoolCodec{}}) + defaultMap.RegisterType(&Type{Name: "box", OID: BoxOID, Codec: BoxCodec{}}) + defaultMap.RegisterType(&Type{Name: "bpchar", OID: BPCharOID, Codec: TextCodec{}}) + defaultMap.RegisterType(&Type{Name: "bytea", OID: ByteaOID, Codec: ByteaCodec{}}) + defaultMap.RegisterType(&Type{Name: "char", OID: QCharOID, Codec: QCharCodec{}}) + defaultMap.RegisterType(&Type{Name: "cid", OID: CIDOID, Codec: Uint32Codec{}}) + defaultMap.RegisterType(&Type{Name: "cidr", OID: CIDROID, Codec: InetCodec{}}) + defaultMap.RegisterType(&Type{Name: "circle", OID: CircleOID, Codec: CircleCodec{}}) + defaultMap.RegisterType(&Type{Name: "date", OID: DateOID, Codec: DateCodec{}}) + defaultMap.RegisterType(&Type{Name: "float4", OID: Float4OID, Codec: Float4Codec{}}) + defaultMap.RegisterType(&Type{Name: "float8", OID: Float8OID, Codec: Float8Codec{}}) + defaultMap.RegisterType(&Type{Name: "inet", OID: InetOID, Codec: InetCodec{}}) + defaultMap.RegisterType(&Type{Name: "int2", OID: Int2OID, Codec: Int2Codec{}}) + defaultMap.RegisterType(&Type{Name: "int4", OID: Int4OID, Codec: Int4Codec{}}) + defaultMap.RegisterType(&Type{Name: "int8", OID: Int8OID, Codec: Int8Codec{}}) + defaultMap.RegisterType(&Type{Name: "interval", OID: IntervalOID, Codec: IntervalCodec{}}) + defaultMap.RegisterType(&Type{Name: "json", OID: JSONOID, Codec: &JSONCodec{Marshal: json.Marshal, Unmarshal: json.Unmarshal}}) + defaultMap.RegisterType(&Type{Name: "jsonb", OID: JSONBOID, Codec: &JSONBCodec{Marshal: json.Marshal, Unmarshal: json.Unmarshal}}) + defaultMap.RegisterType(&Type{Name: "jsonpath", OID: JSONPathOID, Codec: &TextFormatOnlyCodec{TextCodec{}}}) + defaultMap.RegisterType(&Type{Name: "line", OID: LineOID, Codec: LineCodec{}}) + defaultMap.RegisterType(&Type{Name: "lseg", OID: LsegOID, Codec: LsegCodec{}}) + defaultMap.RegisterType(&Type{Name: "macaddr8", OID: Macaddr8OID, Codec: MacaddrCodec{}}) + defaultMap.RegisterType(&Type{Name: "macaddr", OID: MacaddrOID, Codec: MacaddrCodec{}}) + defaultMap.RegisterType(&Type{Name: "name", OID: NameOID, Codec: TextCodec{}}) + defaultMap.RegisterType(&Type{Name: "numeric", OID: NumericOID, Codec: NumericCodec{}}) + defaultMap.RegisterType(&Type{Name: "oid", OID: OIDOID, Codec: Uint32Codec{}}) + defaultMap.RegisterType(&Type{Name: "path", OID: PathOID, Codec: PathCodec{}}) + defaultMap.RegisterType(&Type{Name: "point", OID: PointOID, Codec: PointCodec{}}) + defaultMap.RegisterType(&Type{Name: "polygon", OID: PolygonOID, Codec: PolygonCodec{}}) + defaultMap.RegisterType(&Type{Name: "record", OID: RecordOID, Codec: RecordCodec{}}) + defaultMap.RegisterType(&Type{Name: "text", OID: TextOID, Codec: TextCodec{}}) + defaultMap.RegisterType(&Type{Name: "tid", OID: TIDOID, Codec: TIDCodec{}}) + defaultMap.RegisterType(&Type{Name: "tsvector", OID: TSVectorOID, Codec: TSVectorCodec{}}) + defaultMap.RegisterType(&Type{Name: "time", OID: TimeOID, Codec: TimeCodec{}}) + defaultMap.RegisterType(&Type{Name: "timestamp", OID: TimestampOID, Codec: &TimestampCodec{}}) + defaultMap.RegisterType(&Type{Name: "timestamptz", OID: TimestamptzOID, Codec: &TimestamptzCodec{}}) + defaultMap.RegisterType(&Type{Name: "unknown", OID: UnknownOID, Codec: TextCodec{}}) + defaultMap.RegisterType(&Type{Name: "uuid", OID: UUIDOID, Codec: UUIDCodec{}}) + defaultMap.RegisterType(&Type{Name: "varbit", OID: VarbitOID, Codec: BitsCodec{}}) + defaultMap.RegisterType(&Type{Name: "varchar", OID: VarcharOID, Codec: TextCodec{}}) + defaultMap.RegisterType(&Type{Name: "xid", OID: XIDOID, Codec: Uint32Codec{}}) + defaultMap.RegisterType(&Type{Name: "xid8", OID: XID8OID, Codec: Uint64Codec{}}) + defaultMap.RegisterType(&Type{Name: "xml", OID: XMLOID, Codec: &XMLCodec{ + Marshal: xml.Marshal, + // xml.Unmarshal does not support unmarshalling into *any. However, XMLCodec.DecodeValue calls Unmarshal with a + // *any. Wrap xml.Marshal with a function that copies the data into a new byte slice in this case. Not implementing + // directly in XMLCodec.DecodeValue to allow for the unlikely possibility that someone uses an alternative XML + // unmarshaler that does support unmarshalling into *any. + // + // https://github.com/jackc/pgx/issues/2227 + // https://github.com/jackc/pgx/pull/2228 + Unmarshal: func(data []byte, v any) error { + if v, ok := v.(*any); ok { + dstBuf := make([]byte, len(data)) + copy(dstBuf, data) + *v = dstBuf + return nil + } + return xml.Unmarshal(data, v) + }, + }}) + + // Range types + defaultMap.RegisterType(&Type{Name: "daterange", OID: DaterangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[DateOID]}}) + defaultMap.RegisterType(&Type{Name: "int4range", OID: Int4rangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[Int4OID]}}) + defaultMap.RegisterType(&Type{Name: "int8range", OID: Int8rangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[Int8OID]}}) + defaultMap.RegisterType(&Type{Name: "numrange", OID: NumrangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[NumericOID]}}) + defaultMap.RegisterType(&Type{Name: "tsrange", OID: TsrangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[TimestampOID]}}) + defaultMap.RegisterType(&Type{Name: "tstzrange", OID: TstzrangeOID, Codec: &RangeCodec{ElementType: defaultMap.oidToType[TimestamptzOID]}}) + + // Multirange types + defaultMap.RegisterType(&Type{Name: "datemultirange", OID: DatemultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[DaterangeOID]}}) + defaultMap.RegisterType(&Type{Name: "int4multirange", OID: Int4multirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[Int4rangeOID]}}) + defaultMap.RegisterType(&Type{Name: "int8multirange", OID: Int8multirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[Int8rangeOID]}}) + defaultMap.RegisterType(&Type{Name: "nummultirange", OID: NummultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[NumrangeOID]}}) + defaultMap.RegisterType(&Type{Name: "tsmultirange", OID: TsmultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[TsrangeOID]}}) + defaultMap.RegisterType(&Type{Name: "tstzmultirange", OID: TstzmultirangeOID, Codec: &MultirangeCodec{ElementType: defaultMap.oidToType[TstzrangeOID]}}) + + // Array types + defaultMap.RegisterType(&Type{Name: "_aclitem", OID: ACLItemArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ACLItemOID]}}) + defaultMap.RegisterType(&Type{Name: "_bit", OID: BitArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BitOID]}}) + defaultMap.RegisterType(&Type{Name: "_bool", OID: BoolArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoolOID]}}) + defaultMap.RegisterType(&Type{Name: "_box", OID: BoxArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BoxOID]}}) + defaultMap.RegisterType(&Type{Name: "_bpchar", OID: BPCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[BPCharOID]}}) + defaultMap.RegisterType(&Type{Name: "_bytea", OID: ByteaArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[ByteaOID]}}) + defaultMap.RegisterType(&Type{Name: "_char", OID: QCharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[QCharOID]}}) + defaultMap.RegisterType(&Type{Name: "_cid", OID: CIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[CIDOID]}}) + defaultMap.RegisterType(&Type{Name: "_cidr", OID: CIDRArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[CIDROID]}}) + defaultMap.RegisterType(&Type{Name: "_circle", OID: CircleArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[CircleOID]}}) + defaultMap.RegisterType(&Type{Name: "_date", OID: DateArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[DateOID]}}) + defaultMap.RegisterType(&Type{Name: "_daterange", OID: DaterangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[DaterangeOID]}}) + defaultMap.RegisterType(&Type{Name: "_float4", OID: Float4ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Float4OID]}}) + defaultMap.RegisterType(&Type{Name: "_float8", OID: Float8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Float8OID]}}) + defaultMap.RegisterType(&Type{Name: "_inet", OID: InetArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[InetOID]}}) + defaultMap.RegisterType(&Type{Name: "_int2", OID: Int2ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int2OID]}}) + defaultMap.RegisterType(&Type{Name: "_int4", OID: Int4ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int4OID]}}) + defaultMap.RegisterType(&Type{Name: "_int4range", OID: Int4rangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int4rangeOID]}}) + defaultMap.RegisterType(&Type{Name: "_int8", OID: Int8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int8OID]}}) + defaultMap.RegisterType(&Type{Name: "_int8range", OID: Int8rangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[Int8rangeOID]}}) + defaultMap.RegisterType(&Type{Name: "_interval", OID: IntervalArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[IntervalOID]}}) + defaultMap.RegisterType(&Type{Name: "_json", OID: JSONArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[JSONOID]}}) + defaultMap.RegisterType(&Type{Name: "_jsonb", OID: JSONBArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[JSONBOID]}}) + defaultMap.RegisterType(&Type{Name: "_jsonpath", OID: JSONPathArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[JSONPathOID]}}) + defaultMap.RegisterType(&Type{Name: "_line", OID: LineArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[LineOID]}}) + defaultMap.RegisterType(&Type{Name: "_lseg", OID: LsegArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[LsegOID]}}) + defaultMap.RegisterType(&Type{Name: "_macaddr", OID: MacaddrArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[MacaddrOID]}}) + defaultMap.RegisterType(&Type{Name: "_name", OID: NameArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NameOID]}}) + defaultMap.RegisterType(&Type{Name: "_numeric", OID: NumericArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NumericOID]}}) + defaultMap.RegisterType(&Type{Name: "_numrange", OID: NumrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[NumrangeOID]}}) + defaultMap.RegisterType(&Type{Name: "_oid", OID: OIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[OIDOID]}}) + defaultMap.RegisterType(&Type{Name: "_path", OID: PathArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PathOID]}}) + defaultMap.RegisterType(&Type{Name: "_point", OID: PointArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PointOID]}}) + defaultMap.RegisterType(&Type{Name: "_polygon", OID: PolygonArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[PolygonOID]}}) + defaultMap.RegisterType(&Type{Name: "_record", OID: RecordArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[RecordOID]}}) + defaultMap.RegisterType(&Type{Name: "_text", OID: TextArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TextOID]}}) + defaultMap.RegisterType(&Type{Name: "_tid", OID: TIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TIDOID]}}) + defaultMap.RegisterType(&Type{Name: "_tsvector", OID: TSVectorArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TSVectorOID]}}) + defaultMap.RegisterType(&Type{Name: "_time", OID: TimeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TimeOID]}}) + defaultMap.RegisterType(&Type{Name: "_timestamp", OID: TimestampArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TimestampOID]}}) + defaultMap.RegisterType(&Type{Name: "_timestamptz", OID: TimestamptzArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TimestamptzOID]}}) + defaultMap.RegisterType(&Type{Name: "_tsrange", OID: TsrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TsrangeOID]}}) + defaultMap.RegisterType(&Type{Name: "_tstzrange", OID: TstzrangeArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[TstzrangeOID]}}) + defaultMap.RegisterType(&Type{Name: "_uuid", OID: UUIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[UUIDOID]}}) + defaultMap.RegisterType(&Type{Name: "_varbit", OID: VarbitArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[VarbitOID]}}) + defaultMap.RegisterType(&Type{Name: "_varchar", OID: VarcharArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[VarcharOID]}}) + defaultMap.RegisterType(&Type{Name: "_xid", OID: XIDArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[XIDOID]}}) + defaultMap.RegisterType(&Type{Name: "_xid8", OID: XID8ArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[XID8OID]}}) + defaultMap.RegisterType(&Type{Name: "_xml", OID: XMLArrayOID, Codec: &ArrayCodec{ElementType: defaultMap.oidToType[XMLOID]}}) + + // Integer types that directly map to a PostgreSQL type + registerDefaultPgTypeVariants[int16](defaultMap, "int2") + registerDefaultPgTypeVariants[int32](defaultMap, "int4") + registerDefaultPgTypeVariants[int64](defaultMap, "int8") + + // Integer types that do not have a direct match to a PostgreSQL type + registerDefaultPgTypeVariants[int8](defaultMap, "int8") + registerDefaultPgTypeVariants[int](defaultMap, "int8") + registerDefaultPgTypeVariants[uint8](defaultMap, "int8") + registerDefaultPgTypeVariants[uint16](defaultMap, "int8") + registerDefaultPgTypeVariants[uint32](defaultMap, "int8") + registerDefaultPgTypeVariants[uint64](defaultMap, "numeric") + registerDefaultPgTypeVariants[uint](defaultMap, "numeric") + + registerDefaultPgTypeVariants[float32](defaultMap, "float4") + registerDefaultPgTypeVariants[float64](defaultMap, "float8") + + registerDefaultPgTypeVariants[bool](defaultMap, "bool") + registerDefaultPgTypeVariants[time.Time](defaultMap, "timestamptz") + registerDefaultPgTypeVariants[time.Duration](defaultMap, "interval") + registerDefaultPgTypeVariants[string](defaultMap, "text") + registerDefaultPgTypeVariants[json.RawMessage](defaultMap, "json") + registerDefaultPgTypeVariants[[]byte](defaultMap, "bytea") + + registerDefaultPgTypeVariants[net.IP](defaultMap, "inet") + registerDefaultPgTypeVariants[net.IPNet](defaultMap, "cidr") + registerDefaultPgTypeVariants[netip.Addr](defaultMap, "inet") + registerDefaultPgTypeVariants[netip.Prefix](defaultMap, "cidr") + + // pgtype provided structs + registerDefaultPgTypeVariants[Bits](defaultMap, "varbit") + registerDefaultPgTypeVariants[Bool](defaultMap, "bool") + registerDefaultPgTypeVariants[Box](defaultMap, "box") + registerDefaultPgTypeVariants[Circle](defaultMap, "circle") + registerDefaultPgTypeVariants[Date](defaultMap, "date") + registerDefaultPgTypeVariants[Range[Date]](defaultMap, "daterange") + registerDefaultPgTypeVariants[Multirange[Range[Date]]](defaultMap, "datemultirange") + registerDefaultPgTypeVariants[Float4](defaultMap, "float4") + registerDefaultPgTypeVariants[Float8](defaultMap, "float8") + registerDefaultPgTypeVariants[Range[Float8]](defaultMap, "numrange") // There is no PostgreSQL builtin float8range so map it to numrange. + registerDefaultPgTypeVariants[Multirange[Range[Float8]]](defaultMap, "nummultirange") // There is no PostgreSQL builtin float8multirange so map it to nummultirange. + registerDefaultPgTypeVariants[Int2](defaultMap, "int2") + registerDefaultPgTypeVariants[Int4](defaultMap, "int4") + registerDefaultPgTypeVariants[Range[Int4]](defaultMap, "int4range") + registerDefaultPgTypeVariants[Multirange[Range[Int4]]](defaultMap, "int4multirange") + registerDefaultPgTypeVariants[Int8](defaultMap, "int8") + registerDefaultPgTypeVariants[Range[Int8]](defaultMap, "int8range") + registerDefaultPgTypeVariants[Multirange[Range[Int8]]](defaultMap, "int8multirange") + registerDefaultPgTypeVariants[Interval](defaultMap, "interval") + registerDefaultPgTypeVariants[Line](defaultMap, "line") + registerDefaultPgTypeVariants[Lseg](defaultMap, "lseg") + registerDefaultPgTypeVariants[Numeric](defaultMap, "numeric") + registerDefaultPgTypeVariants[Range[Numeric]](defaultMap, "numrange") + registerDefaultPgTypeVariants[Multirange[Range[Numeric]]](defaultMap, "nummultirange") + registerDefaultPgTypeVariants[Path](defaultMap, "path") + registerDefaultPgTypeVariants[Point](defaultMap, "point") + registerDefaultPgTypeVariants[Polygon](defaultMap, "polygon") + registerDefaultPgTypeVariants[TID](defaultMap, "tid") + registerDefaultPgTypeVariants[Text](defaultMap, "text") + registerDefaultPgTypeVariants[Time](defaultMap, "time") + registerDefaultPgTypeVariants[Timestamp](defaultMap, "timestamp") + registerDefaultPgTypeVariants[Timestamptz](defaultMap, "timestamptz") + registerDefaultPgTypeVariants[Range[Timestamp]](defaultMap, "tsrange") + registerDefaultPgTypeVariants[Multirange[Range[Timestamp]]](defaultMap, "tsmultirange") + registerDefaultPgTypeVariants[Range[Timestamptz]](defaultMap, "tstzrange") + registerDefaultPgTypeVariants[Multirange[Range[Timestamptz]]](defaultMap, "tstzmultirange") + registerDefaultPgTypeVariants[TSVector](defaultMap, "tsvector") + registerDefaultPgTypeVariants[UUID](defaultMap, "uuid") + + defaultMap.buildReflectTypeToType() +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/point.go b/vendor/github.com/jackc/pgx/v5/pgtype/point.go new file mode 100644 index 0000000..d90cb70 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/point.go @@ -0,0 +1,266 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Vec2 struct { + X float64 + Y float64 +} + +type PointScanner interface { + ScanPoint(v Point) error +} + +type PointValuer interface { + PointValue() (Point, error) +} + +type Point struct { + P Vec2 + Valid bool +} + +// ScanPoint implements the [PointScanner] interface. +func (p *Point) ScanPoint(v Point) error { + *p = v + return nil +} + +// PointValue implements the [PointValuer] interface. +func (p Point) PointValue() (Point, error) { + return p, nil +} + +func parsePoint(src []byte) (*Point, error) { + if src == nil || bytes.Equal(src, []byte("null")) { + return &Point{}, nil + } + + if len(src) < 5 { + return nil, fmt.Errorf("invalid length for point: %v", len(src)) + } + if src[0] == '"' && src[len(src)-1] == '"' { + src = src[1 : len(src)-1] + } + sx, sy, found := strings.Cut(string(src[1:len(src)-1]), ",") + if !found { + return nil, fmt.Errorf("invalid format for point") + } + + x, err := strconv.ParseFloat(sx, 64) + if err != nil { + return nil, err + } + + y, err := strconv.ParseFloat(sy, 64) + if err != nil { + return nil, err + } + + return &Point{P: Vec2{x, y}, Valid: true}, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Point) Scan(src any) error { + if src == nil { + *dst = Point{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToPointScanner{}.Scan([]byte(src), dst) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Point) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + buf, err := PointCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Point) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + + var buff bytes.Buffer + buff.WriteByte('"') + buff.WriteString(fmt.Sprintf("(%g,%g)", src.P.X, src.P.Y)) + buff.WriteByte('"') + return buff.Bytes(), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Point) UnmarshalJSON(point []byte) error { + p, err := parsePoint(point) + if err != nil { + return err + } + *dst = *p + return nil +} + +type PointCodec struct{} + +func (PointCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (PointCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (PointCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(PointValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanPointCodecBinary{} + case TextFormatCode: + return encodePlanPointCodecText{} + } + + return nil +} + +type encodePlanPointCodecBinary struct{} + +func (encodePlanPointCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + point, err := value.(PointValuer).PointValue() + if err != nil { + return nil, err + } + + if !point.Valid { + return nil, nil + } + + buf = pgio.AppendUint64(buf, math.Float64bits(point.P.X)) + buf = pgio.AppendUint64(buf, math.Float64bits(point.P.Y)) + return buf, nil +} + +type encodePlanPointCodecText struct{} + +func (encodePlanPointCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + point, err := value.(PointValuer).PointValue() + if err != nil { + return nil, err + } + + if !point.Valid { + return nil, nil + } + + return append(buf, fmt.Sprintf(`(%s,%s)`, + strconv.FormatFloat(point.P.X, 'f', -1, 64), + strconv.FormatFloat(point.P.Y, 'f', -1, 64), + )...), nil +} + +func (PointCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(PointScanner); ok { + return scanPlanBinaryPointToPointScanner{} + } + case TextFormatCode: + if _, ok := target.(PointScanner); ok { + return scanPlanTextAnyToPointScanner{} + } + } + + return nil +} + +func (c PointCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c PointCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var point Point + err := codecScan(c, m, oid, format, src, &point) + if err != nil { + return nil, err + } + return point, nil +} + +type scanPlanBinaryPointToPointScanner struct{} + +func (scanPlanBinaryPointToPointScanner) Scan(src []byte, dst any) error { + scanner := (dst).(PointScanner) + + if src == nil { + return scanner.ScanPoint(Point{}) + } + + if len(src) != 16 { + return fmt.Errorf("invalid length for point: %v", len(src)) + } + + x := binary.BigEndian.Uint64(src) + y := binary.BigEndian.Uint64(src[8:]) + + return scanner.ScanPoint(Point{ + P: Vec2{math.Float64frombits(x), math.Float64frombits(y)}, + Valid: true, + }) +} + +type scanPlanTextAnyToPointScanner struct{} + +func (scanPlanTextAnyToPointScanner) Scan(src []byte, dst any) error { + scanner := (dst).(PointScanner) + + if src == nil { + return scanner.ScanPoint(Point{}) + } + + if len(src) < 5 { + return fmt.Errorf("invalid length for point: %v", len(src)) + } + + sx, sy, found := strings.Cut(string(src[1:len(src)-1]), ",") + if !found { + return fmt.Errorf("invalid format for point") + } + + x, err := strconv.ParseFloat(sx, 64) + if err != nil { + return err + } + + y, err := strconv.ParseFloat(sy, 64) + if err != nil { + return err + } + + return scanner.ScanPoint(Point{P: Vec2{x, y}, Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go new file mode 100644 index 0000000..34aa0a6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/polygon.go @@ -0,0 +1,261 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type PolygonScanner interface { + ScanPolygon(v Polygon) error +} + +type PolygonValuer interface { + PolygonValue() (Polygon, error) +} + +type Polygon struct { + P []Vec2 + Valid bool +} + +// ScanPolygon implements the [PolygonScanner] interface. +func (p *Polygon) ScanPolygon(v Polygon) error { + *p = v + return nil +} + +// PolygonValue implements the [PolygonValuer] interface. +func (p Polygon) PolygonValue() (Polygon, error) { + return p, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (p *Polygon) Scan(src any) error { + if src == nil { + *p = Polygon{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToPolygonScanner{}.Scan([]byte(src), p) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (p Polygon) Value() (driver.Value, error) { + if !p.Valid { + return nil, nil + } + + buf, err := PolygonCodec{}.PlanEncode(nil, 0, TextFormatCode, p).Encode(p, nil) + if err != nil { + return nil, err + } + + return string(buf), err +} + +type PolygonCodec struct{} + +func (PolygonCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (PolygonCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (PolygonCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(PolygonValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanPolygonCodecBinary{} + case TextFormatCode: + return encodePlanPolygonCodecText{} + } + + return nil +} + +type encodePlanPolygonCodecBinary struct{} + +func (encodePlanPolygonCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + polygon, err := value.(PolygonValuer).PolygonValue() + if err != nil { + return nil, err + } + + if !polygon.Valid { + return nil, nil + } + + buf = pgio.AppendInt32(buf, int32(len(polygon.P))) + + for _, p := range polygon.P { + buf = pgio.AppendUint64(buf, math.Float64bits(p.X)) + buf = pgio.AppendUint64(buf, math.Float64bits(p.Y)) + } + + return buf, nil +} + +type encodePlanPolygonCodecText struct{} + +func (encodePlanPolygonCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + polygon, err := value.(PolygonValuer).PolygonValue() + if err != nil { + return nil, err + } + + if !polygon.Valid { + return nil, nil + } + + buf = append(buf, '(') + + for i, p := range polygon.P { + if i > 0 { + buf = append(buf, ',') + } + buf = append(buf, fmt.Sprintf(`(%s,%s)`, + strconv.FormatFloat(p.X, 'f', -1, 64), + strconv.FormatFloat(p.Y, 'f', -1, 64), + )...) + } + + buf = append(buf, ')') + + return buf, nil +} + +func (PolygonCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(PolygonScanner); ok { + return scanPlanBinaryPolygonToPolygonScanner{} + } + case TextFormatCode: + if _, ok := target.(PolygonScanner); ok { + return scanPlanTextAnyToPolygonScanner{} + } + } + + return nil +} + +type scanPlanBinaryPolygonToPolygonScanner struct{} + +func (scanPlanBinaryPolygonToPolygonScanner) Scan(src []byte, dst any) error { + scanner := (dst).(PolygonScanner) + + if src == nil { + return scanner.ScanPolygon(Polygon{}) + } + + if len(src) < 5 { + return fmt.Errorf("invalid length for polygon: %v", len(src)) + } + + pointCount := int(binary.BigEndian.Uint32(src)) + rp := 4 + + if 4+pointCount*16 != len(src) { + return fmt.Errorf("invalid length for Polygon with %d points: %v", pointCount, len(src)) + } + + points := make([]Vec2, pointCount) + for i := range points { + x := binary.BigEndian.Uint64(src[rp:]) + rp += 8 + y := binary.BigEndian.Uint64(src[rp:]) + rp += 8 + points[i] = Vec2{math.Float64frombits(x), math.Float64frombits(y)} + } + + return scanner.ScanPolygon(Polygon{ + P: points, + Valid: true, + }) +} + +type scanPlanTextAnyToPolygonScanner struct{} + +func (scanPlanTextAnyToPolygonScanner) Scan(src []byte, dst any) error { + scanner := (dst).(PolygonScanner) + + if src == nil { + return scanner.ScanPolygon(Polygon{}) + } + + if len(src) < 7 { + return fmt.Errorf("invalid length for Polygon: %v", len(src)) + } + + points := make([]Vec2, 0) + + // Expected format: ((x1,y1),...,(xn,yn)) + str := string(src[1 : len(src)-1]) + + for { + if len(str) == 0 || str[0] != '(' { + return fmt.Errorf("invalid format for Polygon") + } + body, rest, found := strings.Cut(str[1:], ")") + if !found { + return fmt.Errorf("invalid format for Polygon") + } + + sx, sy, found := strings.Cut(body, ",") + if !found { + return fmt.Errorf("invalid format for Polygon") + } + x, err := strconv.ParseFloat(sx, 64) + if err != nil { + return err + } + y, err := strconv.ParseFloat(sy, 64) + if err != nil { + return err + } + + points = append(points, Vec2{x, y}) + + if rest == "" { + break + } + str, found = strings.CutPrefix(rest, ",") + if !found { + return fmt.Errorf("invalid format for Polygon") + } + } + + return scanner.ScanPolygon(Polygon{P: points, Valid: true}) +} + +func (c PolygonCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c PolygonCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var polygon Polygon + err := codecScan(c, m, oid, format, src, &polygon) + if err != nil { + return nil, err + } + return polygon, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/qchar.go b/vendor/github.com/jackc/pgx/v5/pgtype/qchar.go new file mode 100644 index 0000000..3de0b01 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/qchar.go @@ -0,0 +1,163 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" + "math" +) + +// QCharCodec is for PostgreSQL's special 8-bit-only "char" type more akin to the C +// language's char type, or Go's byte type. (Note that the name in PostgreSQL +// itself is "char", in double-quotes, and not char.) It gets used a lot in +// PostgreSQL's system tables to hold a single ASCII character value (eg +// pg_class.relkind). It is named Qchar for quoted char to disambiguate from SQL +// standard type char. +type QCharCodec struct{} + +func (QCharCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (QCharCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (QCharCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case TextFormatCode, BinaryFormatCode: + switch value.(type) { + case byte: + return encodePlanQcharCodecByte{} + case rune: + return encodePlanQcharCodecRune{} + } + } + + return nil +} + +type encodePlanQcharCodecByte struct{} + +func (encodePlanQcharCodecByte) Encode(value any, buf []byte) (newBuf []byte, err error) { + b := value.(byte) + buf = append(buf, b) + return buf, nil +} + +type encodePlanQcharCodecRune struct{} + +func (encodePlanQcharCodecRune) Encode(value any, buf []byte) (newBuf []byte, err error) { + r := value.(rune) + if r > math.MaxUint8 { + return nil, fmt.Errorf(`%v cannot be encoded to "char"`, r) + } + b := byte(r) + buf = append(buf, b) + return buf, nil +} + +func (QCharCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case TextFormatCode, BinaryFormatCode: + switch target.(type) { + case *byte: + return scanPlanQcharCodecByte{} + case *rune: + return scanPlanQcharCodecRune{} + case *string: + return scanPlanQcharCodecString{} + } + } + + return nil +} + +type scanPlanQcharCodecByte struct{} + +func (scanPlanQcharCodecByte) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) > 1 { + return fmt.Errorf(`invalid length for "char": %v`, len(src)) + } + + b := dst.(*byte) + // In the text format the zero value is returned as a zero byte value instead of 0 + if len(src) == 0 { + *b = 0 + } else { + *b = src[0] + } + + return nil +} + +type scanPlanQcharCodecRune struct{} + +func (scanPlanQcharCodecRune) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) > 1 { + return fmt.Errorf(`invalid length for "char": %v`, len(src)) + } + + r := dst.(*rune) + // In the text format the zero value is returned as a zero byte value instead of 0 + if len(src) == 0 { + *r = 0 + } else { + *r = rune(src[0]) + } + + return nil +} + +type scanPlanQcharCodecString struct{} + +func (scanPlanQcharCodecString) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) > 1 { + return fmt.Errorf(`invalid length for "char": %v`, len(src)) + } + + p := dst.(*string) + // Copy the raw byte so the result matches the text-format *string scan path + // (string(src)) byte-for-byte. string(src[0]) would instead UTF-8-encode the + // byte as a code point, diverging for byte values >= 128. + *p = string(src) + + return nil +} + +func (c QCharCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var r rune + err := codecScan(c, m, oid, format, src, &r) + if err != nil { + return nil, err + } + return string(r), nil +} + +func (c QCharCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var r rune + err := codecScan(c, m, oid, format, src, &r) + if err != nil { + return nil, err + } + return r, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range.go b/vendor/github.com/jackc/pgx/v5/pgtype/range.go new file mode 100644 index 0000000..dec153e --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range.go @@ -0,0 +1,331 @@ +package pgtype + +import ( + "bytes" + "encoding/binary" + "fmt" +) + +type BoundType byte + +const ( + Inclusive = BoundType('i') + Exclusive = BoundType('e') + Unbounded = BoundType('U') + Empty = BoundType('E') +) + +func (bt BoundType) String() string { + return string(bt) +} + +type untypedTextRange struct { + Lower string + Upper string + LowerType BoundType + UpperType BoundType +} + +func parseUntypedTextRange(src string) (*untypedTextRange, error) { + utr := &untypedTextRange{} + if src == "empty" { + utr.LowerType = Empty + utr.UpperType = Empty + return utr, nil + } + + buf := bytes.NewBufferString(src) + + skipWhitespace(buf) + + r, _, err := buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid lower bound: %w", err) + } + switch r { + case '(': + utr.LowerType = Exclusive + case '[': + utr.LowerType = Inclusive + default: + return nil, fmt.Errorf("missing lower bound, instead got: %v", string(r)) + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid lower value: %w", err) + } + buf.UnreadRune() + + if r == ',' { + utr.LowerType = Unbounded + } else { + utr.Lower, err = rangeParseValue(buf) + if err != nil { + return nil, fmt.Errorf("invalid lower value: %w", err) + } + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("missing range separator: %w", err) + } + if r != ',' { + return nil, fmt.Errorf("missing range separator: %v", r) + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("invalid upper value: %w", err) + } + + if r == ')' || r == ']' { + utr.UpperType = Unbounded + } else { + buf.UnreadRune() + utr.Upper, err = rangeParseValue(buf) + if err != nil { + return nil, fmt.Errorf("invalid upper value: %w", err) + } + + r, _, err = buf.ReadRune() + if err != nil { + return nil, fmt.Errorf("missing upper bound: %w", err) + } + switch r { + case ')': + utr.UpperType = Exclusive + case ']': + utr.UpperType = Inclusive + default: + return nil, fmt.Errorf("missing upper bound, instead got: %v", string(r)) + } + } + + skipWhitespace(buf) + + if buf.Len() > 0 { + return nil, fmt.Errorf("unexpected trailing data: %v", buf.String()) + } + + return utr, nil +} + +func rangeParseValue(buf *bytes.Buffer) (string, error) { + r, _, err := buf.ReadRune() + if err != nil { + return "", err + } + if r == '"' { + return rangeParseQuotedValue(buf) + } + buf.UnreadRune() + + s := &bytes.Buffer{} + + for { + r, _, err := buf.ReadRune() + if err != nil { + return "", err + } + + switch r { + case '\\': + r, _, err = buf.ReadRune() + if err != nil { + return "", err + } + case ',', '[', ']', '(', ')': + buf.UnreadRune() + return s.String(), nil + } + + s.WriteRune(r) + } +} + +func rangeParseQuotedValue(buf *bytes.Buffer) (string, error) { + s := &bytes.Buffer{} + + for { + r, _, err := buf.ReadRune() + if err != nil { + return "", err + } + + switch r { + case '\\': + r, _, err = buf.ReadRune() + if err != nil { + return "", err + } + case '"': + r, _, err = buf.ReadRune() + if err != nil { + return "", err + } + if r != '"' { + buf.UnreadRune() + return s.String(), nil + } + } + s.WriteRune(r) + } +} + +type untypedBinaryRange struct { + Lower []byte + Upper []byte + LowerType BoundType + UpperType BoundType +} + +// 0 = () = 00000 +// 1 = empty = 00001 +// 2 = [) = 00010 +// 4 = (] = 00100 +// 6 = [] = 00110 +// 8 = ) = 01000 +// 12 = ] = 01100 +// 16 = ( = 10000 +// 18 = [ = 10010 +// 24 = = 11000 + +const ( + emptyMask = 1 + lowerInclusiveMask = 2 + upperInclusiveMask = 4 + lowerUnboundedMask = 8 + upperUnboundedMask = 16 +) + +func parseUntypedBinaryRange(src []byte) (*untypedBinaryRange, error) { + ubr := &untypedBinaryRange{} + + if len(src) == 0 { + return nil, fmt.Errorf("range too short: %v", len(src)) + } + + rangeType := src[0] + rp := 1 + + if rangeType&emptyMask > 0 { + if len(src[rp:]) > 0 { + return nil, fmt.Errorf("unexpected trailing bytes parsing empty range: %v", len(src[rp:])) + } + ubr.LowerType = Empty + ubr.UpperType = Empty + return ubr, nil + } + + switch { + case rangeType&lowerInclusiveMask > 0: + ubr.LowerType = Inclusive + case rangeType&lowerUnboundedMask > 0: + ubr.LowerType = Unbounded + default: + ubr.LowerType = Exclusive + } + + switch { + case rangeType&upperInclusiveMask > 0: + ubr.UpperType = Inclusive + case rangeType&upperUnboundedMask > 0: + ubr.UpperType = Unbounded + default: + ubr.UpperType = Exclusive + } + + if ubr.LowerType == Unbounded && ubr.UpperType == Unbounded { + if len(src[rp:]) > 0 { + return nil, fmt.Errorf("unexpected trailing bytes parsing unbounded range: %v", len(src[rp:])) + } + return ubr, nil + } + + if len(src[rp:]) < 4 { + return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) + } + valueLen := int(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + + if valueLen < 0 || len(src[rp:]) < valueLen { + return nil, fmt.Errorf("range lower bound length %d exceeds remaining %d bytes", valueLen, len(src[rp:])) + } + val := src[rp : rp+valueLen] + rp += valueLen + + if ubr.LowerType != Unbounded { + ubr.Lower = val + } else { + ubr.Upper = val + if len(src[rp:]) > 0 { + return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) + } + return ubr, nil + } + + if ubr.UpperType != Unbounded { + if len(src[rp:]) < 4 { + return nil, fmt.Errorf("too few bytes for size: %v", src[rp:]) + } + valueLen := int(binary.BigEndian.Uint32(src[rp:])) + rp += 4 + if valueLen < 0 || len(src[rp:]) < valueLen { + return nil, fmt.Errorf("range upper bound length %d exceeds remaining %d bytes", valueLen, len(src[rp:])) + } + ubr.Upper = src[rp : rp+valueLen] + rp += valueLen + } + + if len(src[rp:]) > 0 { + return nil, fmt.Errorf("unexpected trailing bytes parsing range: %v", len(src[rp:])) + } + + return ubr, nil +} + +// Range is a generic range type. +type Range[T any] struct { + Lower T + Upper T + LowerType BoundType + UpperType BoundType + Valid bool +} + +func (r Range[T]) IsNull() bool { + return !r.Valid +} + +func (r Range[T]) BoundTypes() (lower, upper BoundType) { + return r.LowerType, r.UpperType +} + +func (r Range[T]) Bounds() (lower, upper any) { + return &r.Lower, &r.Upper +} + +func (r *Range[T]) ScanNull() error { + *r = Range[T]{} + return nil +} + +func (r *Range[T]) ScanBounds() (lowerTarget, upperTarget any) { + return &r.Lower, &r.Upper +} + +func (r *Range[T]) SetBoundTypes(lower, upper BoundType) error { + if lower == Unbounded || lower == Empty { + var zero T + r.Lower = zero + } + if upper == Unbounded || upper == Empty { + var zero T + r.Upper = zero + } + r.LowerType = lower + r.UpperType = upper + r.Valid = true + return nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go new file mode 100644 index 0000000..dc1ac8b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/range_codec.go @@ -0,0 +1,377 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +// RangeValuer is a type that can be converted into a PostgreSQL range. +type RangeValuer interface { + // IsNull returns true if the value is SQL NULL. + IsNull() bool + + // BoundTypes returns the lower and upper bound types. + BoundTypes() (lower, upper BoundType) + + // Bounds returns the lower and upper range values. + Bounds() (lower, upper any) +} + +// RangeScanner is a type can be scanned from a PostgreSQL range. +type RangeScanner interface { + // ScanNull sets the value to SQL NULL. + ScanNull() error + + // ScanBounds returns values usable as a scan target. The returned values may not be scanned if the range is empty or + // the bound type is unbounded. + ScanBounds() (lowerTarget, upperTarget any) + + // SetBoundTypes sets the lower and upper bound types. ScanBounds will be called and the returned values scanned + // (if appropriate) before SetBoundTypes is called. If the bound types are unbounded or empty this method must + // also set the bound values. + SetBoundTypes(lower, upper BoundType) error +} + +// RangeCodec is a codec for any range type. +type RangeCodec struct { + ElementType *Type +} + +func (c *RangeCodec) FormatSupported(format int16) bool { + return c.ElementType.Codec.FormatSupported(format) +} + +func (c *RangeCodec) PreferredFormat() int16 { + if c.FormatSupported(BinaryFormatCode) { + return BinaryFormatCode + } + return TextFormatCode +} + +func (c *RangeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(RangeValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return &encodePlanRangeCodecRangeValuerToBinary{rc: c, m: m} + case TextFormatCode: + return &encodePlanRangeCodecRangeValuerToText{rc: c, m: m} + } + + return nil +} + +type encodePlanRangeCodecRangeValuerToBinary struct { + rc *RangeCodec + m *Map +} + +func (plan *encodePlanRangeCodecRangeValuerToBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + getter := value.(RangeValuer) + + if getter.IsNull() { + return nil, nil + } + + lowerType, upperType := getter.BoundTypes() + lower, upper := getter.Bounds() + + var rangeType byte + switch lowerType { + case Inclusive: + rangeType |= lowerInclusiveMask + case Unbounded: + rangeType |= lowerUnboundedMask + case Exclusive: + case Empty: + return append(buf, emptyMask), nil + default: + return nil, fmt.Errorf("unknown LowerType: %v", lowerType) + } + + switch upperType { + case Inclusive: + rangeType |= upperInclusiveMask + case Unbounded: + rangeType |= upperUnboundedMask + case Exclusive: + default: + return nil, fmt.Errorf("unknown UpperType: %v", upperType) + } + + buf = append(buf, rangeType) + + if lowerType != Unbounded { + if lower == nil { + return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") + } + + sp := len(buf) + buf = pgio.AppendInt32(buf, -1) + + lowerPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, BinaryFormatCode, lower) + if lowerPlan == nil { + return nil, fmt.Errorf("cannot encode %v as element of range", lower) + } + + buf, err = lowerPlan.Encode(lower, buf) + if err != nil { + return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) + } + if buf == nil { + return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") + } + + pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) + } + + if upperType != Unbounded { + if upper == nil { + return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") + } + + sp := len(buf) + buf = pgio.AppendInt32(buf, -1) + + upperPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, BinaryFormatCode, upper) + if upperPlan == nil { + return nil, fmt.Errorf("cannot encode %v as element of range", upper) + } + + buf, err = upperPlan.Encode(upper, buf) + if err != nil { + return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) + } + if buf == nil { + return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") + } + + pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) + } + + return buf, nil +} + +type encodePlanRangeCodecRangeValuerToText struct { + rc *RangeCodec + m *Map +} + +func (plan *encodePlanRangeCodecRangeValuerToText) Encode(value any, buf []byte) (newBuf []byte, err error) { + getter := value.(RangeValuer) + + if getter.IsNull() { + return nil, nil + } + + lowerType, upperType := getter.BoundTypes() + lower, upper := getter.Bounds() + + switch lowerType { + case Exclusive, Unbounded: + buf = append(buf, '(') + case Inclusive: + buf = append(buf, '[') + case Empty: + return append(buf, "empty"...), nil + default: + return nil, fmt.Errorf("unknown lower bound type %v", lowerType) + } + + if lowerType != Unbounded { + if lower == nil { + return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") + } + + lowerPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, TextFormatCode, lower) + if lowerPlan == nil { + return nil, fmt.Errorf("cannot encode %v as element of range", lower) + } + + buf, err = lowerPlan.Encode(lower, buf) + if err != nil { + return nil, fmt.Errorf("failed to encode %v as element of range: %w", lower, err) + } + if buf == nil { + return nil, fmt.Errorf("Lower cannot be NULL unless LowerType is Unbounded") + } + } + + buf = append(buf, ',') + + if upperType != Unbounded { + if upper == nil { + return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") + } + + upperPlan := plan.m.PlanEncode(plan.rc.ElementType.OID, TextFormatCode, upper) + if upperPlan == nil { + return nil, fmt.Errorf("cannot encode %v as element of range", upper) + } + + buf, err = upperPlan.Encode(upper, buf) + if err != nil { + return nil, fmt.Errorf("failed to encode %v as element of range: %w", upper, err) + } + if buf == nil { + return nil, fmt.Errorf("Upper cannot be NULL unless UpperType is Unbounded") + } + } + + switch upperType { + case Exclusive, Unbounded: + buf = append(buf, ')') + case Inclusive: + buf = append(buf, ']') + default: + return nil, fmt.Errorf("unknown upper bound type %v", upperType) + } + + return buf, nil +} + +func (c *RangeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(RangeScanner); ok { + return &scanPlanBinaryRangeToRangeScanner{rc: c, m: m} + } + case TextFormatCode: + if _, ok := target.(RangeScanner); ok { + return &scanPlanTextRangeToRangeScanner{rc: c, m: m} + } + } + + return nil +} + +type scanPlanBinaryRangeToRangeScanner struct { + rc *RangeCodec + m *Map +} + +func (plan *scanPlanBinaryRangeToRangeScanner) Scan(src []byte, target any) error { + rangeScanner := (target).(RangeScanner) + + if src == nil { + return rangeScanner.ScanNull() + } + + ubr, err := parseUntypedBinaryRange(src) + if err != nil { + return err + } + + if ubr.LowerType == Empty { + return rangeScanner.SetBoundTypes(ubr.LowerType, ubr.UpperType) + } + + lowerTarget, upperTarget := rangeScanner.ScanBounds() + + if ubr.LowerType == Inclusive || ubr.LowerType == Exclusive { + lowerPlan := plan.m.PlanScan(plan.rc.ElementType.OID, BinaryFormatCode, lowerTarget) + if lowerPlan == nil { + return fmt.Errorf("cannot scan into %v from range element", lowerTarget) + } + + err = lowerPlan.Scan(ubr.Lower, lowerTarget) + if err != nil { + return fmt.Errorf("cannot scan into %v from range element: %w", lowerTarget, err) + } + } + + if ubr.UpperType == Inclusive || ubr.UpperType == Exclusive { + upperPlan := plan.m.PlanScan(plan.rc.ElementType.OID, BinaryFormatCode, upperTarget) + if upperPlan == nil { + return fmt.Errorf("cannot scan into %v from range element", upperTarget) + } + + err = upperPlan.Scan(ubr.Upper, upperTarget) + if err != nil { + return fmt.Errorf("cannot scan into %v from range element: %w", upperTarget, err) + } + } + + return rangeScanner.SetBoundTypes(ubr.LowerType, ubr.UpperType) +} + +type scanPlanTextRangeToRangeScanner struct { + rc *RangeCodec + m *Map +} + +func (plan *scanPlanTextRangeToRangeScanner) Scan(src []byte, target any) error { + rangeScanner := (target).(RangeScanner) + + if src == nil { + return rangeScanner.ScanNull() + } + + utr, err := parseUntypedTextRange(string(src)) + if err != nil { + return err + } + + if utr.LowerType == Empty { + return rangeScanner.SetBoundTypes(utr.LowerType, utr.UpperType) + } + + lowerTarget, upperTarget := rangeScanner.ScanBounds() + + if utr.LowerType == Inclusive || utr.LowerType == Exclusive { + lowerPlan := plan.m.PlanScan(plan.rc.ElementType.OID, TextFormatCode, lowerTarget) + if lowerPlan == nil { + return fmt.Errorf("cannot scan into %v from range element", lowerTarget) + } + + err = lowerPlan.Scan([]byte(utr.Lower), lowerTarget) + if err != nil { + return fmt.Errorf("cannot scan into %v from range element: %w", lowerTarget, err) + } + } + + if utr.UpperType == Inclusive || utr.UpperType == Exclusive { + upperPlan := plan.m.PlanScan(plan.rc.ElementType.OID, TextFormatCode, upperTarget) + if upperPlan == nil { + return fmt.Errorf("cannot scan into %v from range element", upperTarget) + } + + err = upperPlan.Scan([]byte(utr.Upper), upperTarget) + if err != nil { + return fmt.Errorf("cannot scan into %v from range element: %w", upperTarget, err) + } + } + + return rangeScanner.SetBoundTypes(utr.LowerType, utr.UpperType) +} + +func (c *RangeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + return string(src), nil + case BinaryFormatCode: + buf := make([]byte, len(src)) + copy(buf, src) + return buf, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} + +func (c *RangeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var r Range[any] + err := c.PlanScan(m, oid, format, &r).Scan(src, &r) + return r, err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go new file mode 100644 index 0000000..a663e4d --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/record_codec.go @@ -0,0 +1,123 @@ +package pgtype + +import ( + "database/sql/driver" + "fmt" +) + +// ArrayGetter is a type that can be converted into a PostgreSQL array. + +// RecordCodec is a codec for the generic PostgreSQL record type such as is created with the "row" function. Record can +// only decode the binary format. The text format output format from PostgreSQL does not include type information and +// is therefore impossible to decode. Encoding is impossible because PostgreSQL does not support input of generic +// records. +type RecordCodec struct{} + +func (RecordCodec) FormatSupported(format int16) bool { + return format == BinaryFormatCode +} + +func (RecordCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (RecordCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + return nil +} + +func (RecordCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + if format == BinaryFormatCode { + if _, ok := target.(CompositeIndexScanner); ok { + return &scanPlanBinaryRecordToCompositeIndexScanner{m: m} + } + } + + return nil +} + +type scanPlanBinaryRecordToCompositeIndexScanner struct { + m *Map +} + +func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target any) error { + targetScanner := (target).(CompositeIndexScanner) + + if src == nil { + return targetScanner.ScanNull() + } + + scanner := NewCompositeBinaryScanner(plan.m, src) + for i := 0; scanner.Next(); i++ { + fieldTarget := targetScanner.ScanIndex(i) + if fieldTarget != nil { + fieldPlan := plan.m.PlanScan(scanner.OID(), BinaryFormatCode, fieldTarget) + if fieldPlan == nil { + return fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), fieldTarget) + } + + err := fieldPlan.Scan(scanner.Bytes(), fieldTarget) + if err != nil { + return err + } + } + } + + if err := scanner.Err(); err != nil { + return err + } + + return nil +} + +func (RecordCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + return string(src), nil + case BinaryFormatCode: + buf := make([]byte, len(src)) + copy(buf, src) + return buf, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} + +func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + switch format { + case TextFormatCode: + return string(src), nil + case BinaryFormatCode: + scanner := NewCompositeBinaryScanner(m, src) + values := make([]any, scanner.FieldCount()) + for i := 0; scanner.Next(); i++ { + var v any + fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v) + if fieldPlan == nil { + return nil, fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), v) + } + + err := fieldPlan.Scan(scanner.Bytes(), &v) + if err != nil { + return nil, err + } + + values[i] = v + } + + if err := scanner.Err(); err != nil { + return nil, err + } + + return values, nil + default: + return nil, fmt.Errorf("unknown format code %d", format) + } +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go b/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go new file mode 100644 index 0000000..be1ca4a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types.go @@ -0,0 +1,35 @@ +//go:build !nopgxregisterdefaulttypes + +package pgtype + +func registerDefaultPgTypeVariants[T any](m *Map, name string) { + arrayName := "_" + name + + var value T + m.RegisterDefaultPgType(value, name) // T + m.RegisterDefaultPgType(&value, name) // *T + + var sliceT []T + m.RegisterDefaultPgType(sliceT, arrayName) // []T + m.RegisterDefaultPgType(&sliceT, arrayName) // *[]T + + var slicePtrT []*T + m.RegisterDefaultPgType(slicePtrT, arrayName) // []*T + m.RegisterDefaultPgType(&slicePtrT, arrayName) // *[]*T + + var arrayOfT Array[T] + m.RegisterDefaultPgType(arrayOfT, arrayName) // Array[T] + m.RegisterDefaultPgType(&arrayOfT, arrayName) // *Array[T] + + var arrayOfPtrT Array[*T] + m.RegisterDefaultPgType(arrayOfPtrT, arrayName) // Array[*T] + m.RegisterDefaultPgType(&arrayOfPtrT, arrayName) // *Array[*T] + + var flatArrayOfT FlatArray[T] + m.RegisterDefaultPgType(flatArrayOfT, arrayName) // FlatArray[T] + m.RegisterDefaultPgType(&flatArrayOfT, arrayName) // *FlatArray[T] + + var flatArrayOfPtrT FlatArray[*T] + m.RegisterDefaultPgType(flatArrayOfPtrT, arrayName) // FlatArray[*T] + m.RegisterDefaultPgType(&flatArrayOfPtrT, arrayName) // *FlatArray[*T] +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go b/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go new file mode 100644 index 0000000..56fe7c2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/register_default_pg_types_disabled.go @@ -0,0 +1,6 @@ +//go:build nopgxregisterdefaulttypes + +package pgtype + +func registerDefaultPgTypeVariants[T any](m *Map, name string) { +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/text.go b/vendor/github.com/jackc/pgx/v5/pgtype/text.go new file mode 100644 index 0000000..e08b125 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/text.go @@ -0,0 +1,226 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/json" + "fmt" +) + +type TextScanner interface { + ScanText(v Text) error +} + +type TextValuer interface { + TextValue() (Text, error) +} + +type Text struct { + String string + Valid bool +} + +// ScanText implements the [TextScanner] interface. +func (t *Text) ScanText(v Text) error { + *t = v + return nil +} + +// TextValue implements the [TextValuer] interface. +func (t Text) TextValue() (Text, error) { + return t, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Text) Scan(src any) error { + if src == nil { + *dst = Text{} + return nil + } + + switch src := src.(type) { + case string: + *dst = Text{String: src, Valid: true} + return nil + case []byte: + *dst = Text{String: string(src), Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Text) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + return src.String, nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Text) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + + return json.Marshal(src.String) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Text) UnmarshalJSON(b []byte) error { + var s *string + err := json.Unmarshal(b, &s) + if err != nil { + return err + } + + if s == nil { + *dst = Text{} + } else { + *dst = Text{String: *s, Valid: true} + } + + return nil +} + +type TextCodec struct{} + +func (TextCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (TextCodec) PreferredFormat() int16 { + return TextFormatCode +} + +func (TextCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case TextFormatCode, BinaryFormatCode: + switch value.(type) { + case string: + return encodePlanTextCodecString{} + case []byte: + return encodePlanTextCodecByteSlice{} + case TextValuer: + return encodePlanTextCodecTextValuer{} + } + } + + return nil +} + +type encodePlanTextCodecString struct{} + +func (encodePlanTextCodecString) Encode(value any, buf []byte) (newBuf []byte, err error) { + s := value.(string) + buf = append(buf, s...) + return buf, nil +} + +type encodePlanTextCodecByteSlice struct{} + +func (encodePlanTextCodecByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { + s := value.([]byte) + buf = append(buf, s...) + return buf, nil +} + +type encodePlanTextCodecStringer struct{} + +func (encodePlanTextCodecStringer) Encode(value any, buf []byte) (newBuf []byte, err error) { + s := value.(fmt.Stringer) + buf = append(buf, s.String()...) + return buf, nil +} + +type encodePlanTextCodecTextValuer struct{} + +func (encodePlanTextCodecTextValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + text, err := value.(TextValuer).TextValue() + if err != nil { + return nil, err + } + + if !text.Valid { + return nil, nil + } + + buf = append(buf, text.String...) + return buf, nil +} + +func (TextCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case TextFormatCode, BinaryFormatCode: + switch target.(type) { + case *string: + return scanPlanTextAnyToString{} + case *[]byte: + return scanPlanAnyToNewByteSlice{} + case BytesScanner: + return scanPlanAnyToByteScanner{} + case TextScanner: + return scanPlanTextAnyToTextScanner{} + } + } + + return nil +} + +func (c TextCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return c.DecodeValue(m, oid, format, src) +} + +func (c TextCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + return string(src), nil +} + +type scanPlanTextAnyToString struct{} + +func (scanPlanTextAnyToString) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + p := (dst).(*string) + *p = string(src) + + return nil +} + +type scanPlanAnyToNewByteSlice struct{} + +func (scanPlanAnyToNewByteSlice) Scan(src []byte, dst any) error { + p := (dst).(*[]byte) + if src == nil { + *p = nil + } else { + *p = make([]byte, len(src)) + copy(*p, src) + } + + return nil +} + +type scanPlanAnyToByteScanner struct{} + +func (scanPlanAnyToByteScanner) Scan(src []byte, dst any) error { + p := (dst).(BytesScanner) + return p.ScanBytes(src) +} + +type scanPlanTextAnyToTextScanner struct{} + +func (scanPlanTextAnyToTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + + return scanner.ScanText(Text{String: string(src), Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go b/vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go new file mode 100644 index 0000000..d5e4cdb --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/text_format_only_codec.go @@ -0,0 +1,13 @@ +package pgtype + +type TextFormatOnlyCodec struct { + Codec +} + +func (c *TextFormatOnlyCodec) FormatSupported(format int16) bool { + return format == TextFormatCode && c.Codec.FormatSupported(format) +} + +func (TextFormatOnlyCodec) PreferredFormat() int16 { + return TextFormatCode +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tid.go b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go new file mode 100644 index 0000000..98d067a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/tid.go @@ -0,0 +1,240 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type TIDScanner interface { + ScanTID(v TID) error +} + +type TIDValuer interface { + TIDValue() (TID, error) +} + +// TID is PostgreSQL's Tuple Identifier type. +// +// When one does +// +// select ctid, * from some_table; +// +// it is the data type of the ctid hidden system column. +// +// It is currently implemented as a pair unsigned two byte integers. +// Its conversion functions can be found in src/backend/utils/adt/tid.c +// in the PostgreSQL sources. +type TID struct { + BlockNumber uint32 + OffsetNumber uint16 + Valid bool +} + +// ScanTID implements the [TIDScanner] interface. +func (b *TID) ScanTID(v TID) error { + *b = v + return nil +} + +// TIDValue implements the [TIDValuer] interface. +func (b TID) TIDValue() (TID, error) { + return b, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *TID) Scan(src any) error { + if src == nil { + *dst = TID{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToTIDScanner{}.Scan([]byte(src), dst) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src TID) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + buf, err := TIDCodec{}.PlanEncode(nil, 0, TextFormatCode, src).Encode(src, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type TIDCodec struct{} + +func (TIDCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (TIDCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (TIDCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(TIDValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTIDCodecBinary{} + case TextFormatCode: + return encodePlanTIDCodecText{} + } + + return nil +} + +type encodePlanTIDCodecBinary struct{} + +func (encodePlanTIDCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + tid, err := value.(TIDValuer).TIDValue() + if err != nil { + return nil, err + } + + if !tid.Valid { + return nil, nil + } + + buf = pgio.AppendUint32(buf, tid.BlockNumber) + buf = pgio.AppendUint16(buf, tid.OffsetNumber) + return buf, nil +} + +type encodePlanTIDCodecText struct{} + +func (encodePlanTIDCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + tid, err := value.(TIDValuer).TIDValue() + if err != nil { + return nil, err + } + + if !tid.Valid { + return nil, nil + } + + buf = append(buf, fmt.Sprintf(`(%d,%d)`, tid.BlockNumber, tid.OffsetNumber)...) + return buf, nil +} + +func (TIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case TIDScanner: + return scanPlanBinaryTIDToTIDScanner{} + case TextScanner: + return scanPlanBinaryTIDToTextScanner{} + } + case TextFormatCode: + if _, ok := target.(TIDScanner); ok { + return scanPlanTextAnyToTIDScanner{} + } + } + + return nil +} + +type scanPlanBinaryTIDToTIDScanner struct{} + +func (scanPlanBinaryTIDToTIDScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TIDScanner) + + if src == nil { + return scanner.ScanTID(TID{}) + } + + if len(src) != 6 { + return fmt.Errorf("invalid length for tid: %v", len(src)) + } + + return scanner.ScanTID(TID{ + BlockNumber: binary.BigEndian.Uint32(src), + OffsetNumber: binary.BigEndian.Uint16(src[4:]), + Valid: true, + }) +} + +type scanPlanBinaryTIDToTextScanner struct{} + +func (scanPlanBinaryTIDToTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + + if len(src) != 6 { + return fmt.Errorf("invalid length for tid: %v", len(src)) + } + + blockNumber := binary.BigEndian.Uint32(src) + offsetNumber := binary.BigEndian.Uint16(src[4:]) + + return scanner.ScanText(Text{ + String: fmt.Sprintf(`(%d,%d)`, blockNumber, offsetNumber), + Valid: true, + }) +} + +type scanPlanTextAnyToTIDScanner struct{} + +func (scanPlanTextAnyToTIDScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TIDScanner) + + if src == nil { + return scanner.ScanTID(TID{}) + } + + if len(src) < 5 { + return fmt.Errorf("invalid length for tid: %v", len(src)) + } + + block, offset, found := strings.Cut(string(src[1:len(src)-1]), ",") + if !found { + return fmt.Errorf("invalid format for tid") + } + + blockNumber, err := strconv.ParseUint(block, 10, 32) + if err != nil { + return err + } + + offsetNumber, err := strconv.ParseUint(offset, 10, 16) + if err != nil { + return err + } + + return scanner.ScanTID(TID{BlockNumber: uint32(blockNumber), OffsetNumber: uint16(offsetNumber), Valid: true}) +} + +func (c TIDCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c TIDCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var tid TID + err := codecScan(c, m, oid, format, src, &tid) + if err != nil { + return nil, err + } + return tid, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/time.go b/vendor/github.com/jackc/pgx/v5/pgtype/time.go new file mode 100644 index 0000000..72cdb50 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/time.go @@ -0,0 +1,273 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type TimeScanner interface { + ScanTime(v Time) error +} + +type TimeValuer interface { + TimeValue() (Time, error) +} + +// Time represents the PostgreSQL time type. The PostgreSQL time is a time of day without time zone. +// +// Time is represented as the number of microseconds since midnight in the same way that PostgreSQL does. Other time and +// date types in pgtype can use time.Time as the underlying representation. However, pgtype.Time type cannot due to +// needing to handle 24:00:00. time.Time converts that to 00:00:00 on the following day. +// +// The time with time zone type is not supported. Use of time with time zone is discouraged by the PostgreSQL documentation. +type Time struct { + Microseconds int64 // Number of microseconds since midnight + Valid bool +} + +// ScanTime implements the [TimeScanner] interface. +func (t *Time) ScanTime(v Time) error { + *t = v + return nil +} + +// TimeValue implements the [TimeValuer] interface. +func (t Time) TimeValue() (Time, error) { + return t, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (t *Time) Scan(src any) error { + if src == nil { + *t = Time{} + return nil + } + + if src, ok := src.(string); ok { + err := scanPlanTextAnyToTimeScanner{}.Scan([]byte(src), t) + if err != nil { + t.Microseconds = 0 + t.Valid = false + } + return err + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (t Time) Value() (driver.Value, error) { + if !t.Valid { + return nil, nil + } + + buf, err := TimeCodec{}.PlanEncode(nil, 0, TextFormatCode, t).Encode(t, nil) + if err != nil { + return nil, err + } + return string(buf), err +} + +type TimeCodec struct{} + +func (TimeCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (TimeCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (TimeCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(TimeValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTimeCodecBinary{} + case TextFormatCode: + return encodePlanTimeCodecText{} + } + + return nil +} + +type encodePlanTimeCodecBinary struct{} + +func (encodePlanTimeCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + t, err := value.(TimeValuer).TimeValue() + if err != nil { + return nil, err + } + + if !t.Valid { + return nil, nil + } + + return pgio.AppendInt64(buf, t.Microseconds), nil +} + +type encodePlanTimeCodecText struct{} + +func (encodePlanTimeCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + t, err := value.(TimeValuer).TimeValue() + if err != nil { + return nil, err + } + + if !t.Valid { + return nil, nil + } + + usec := t.Microseconds + hours := usec / microsecondsPerHour + usec -= hours * microsecondsPerHour + minutes := usec / microsecondsPerMinute + usec -= minutes * microsecondsPerMinute + seconds := usec / microsecondsPerSecond + usec -= seconds * microsecondsPerSecond + + s := fmt.Sprintf("%02d:%02d:%02d.%06d", hours, minutes, seconds, usec) + + return append(buf, s...), nil +} + +func (TimeCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case TimeScanner: + return scanPlanBinaryTimeToTimeScanner{} + case TextScanner: + return scanPlanBinaryTimeToTextScanner{} + } + case TextFormatCode: + if _, ok := target.(TimeScanner); ok { + return scanPlanTextAnyToTimeScanner{} + } + } + + return nil +} + +type scanPlanBinaryTimeToTimeScanner struct{} + +func (scanPlanBinaryTimeToTimeScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TimeScanner) + + if src == nil { + return scanner.ScanTime(Time{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for time: %v", len(src)) + } + + usec := int64(binary.BigEndian.Uint64(src)) + + return scanner.ScanTime(Time{Microseconds: usec, Valid: true}) +} + +type scanPlanBinaryTimeToTextScanner struct{} + +func (scanPlanBinaryTimeToTextScanner) Scan(src []byte, dst any) error { + ts, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return ts.ScanText(Text{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for time: %v", len(src)) + } + + usec := int64(binary.BigEndian.Uint64(src)) + + tim := Time{Microseconds: usec, Valid: true} + + buf, err := TimeCodec{}.PlanEncode(nil, 0, TextFormatCode, tim).Encode(tim, nil) + if err != nil { + return err + } + + return ts.ScanText(Text{String: string(buf), Valid: true}) +} + +type scanPlanTextAnyToTimeScanner struct{} + +func (scanPlanTextAnyToTimeScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TimeScanner) + + if src == nil { + return scanner.ScanTime(Time{}) + } + + s := string(src) + + if len(s) < 8 || s[2] != ':' || s[5] != ':' { + return fmt.Errorf("cannot decode %v into Time", s) + } + + hours, err := strconv.ParseInt(s[0:2], 10, 64) + if err != nil { + return fmt.Errorf("cannot decode %v into Time", s) + } + usec := hours * microsecondsPerHour + + minutes, err := strconv.ParseInt(s[3:5], 10, 64) + if err != nil { + return fmt.Errorf("cannot decode %v into Time", s) + } + usec += minutes * microsecondsPerMinute + + seconds, err := strconv.ParseInt(s[6:8], 10, 64) + if err != nil { + return fmt.Errorf("cannot decode %v into Time", s) + } + usec += seconds * microsecondsPerSecond + + if len(s) > 9 { + if s[8] != '.' || len(s) > 15 { + return fmt.Errorf("cannot decode %v into Time", s) + } + + fraction := s[9:] + n, err := strconv.ParseInt(fraction, 10, 64) + if err != nil { + return fmt.Errorf("cannot decode %v into Time", s) + } + + for i := len(fraction); i < 6; i++ { + n *= 10 + } + + usec += n + } + + return scanner.ScanTime(Time{Microseconds: usec, Valid: true}) +} + +func (c TimeCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c TimeCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var t Time + err := codecScan(c, m, oid, format, src, &t) + if err != nil { + return nil, err + } + return t, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go new file mode 100644 index 0000000..405c77e --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/timestamp.go @@ -0,0 +1,368 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const ( + pgTimestampFormat = "2006-01-02 15:04:05.999999999" + jsonISO8601 = "2006-01-02T15:04:05.999999999" +) + +type TimestampScanner interface { + ScanTimestamp(v Timestamp) error +} + +type TimestampValuer interface { + TimestampValue() (Timestamp, error) +} + +// Timestamp represents the PostgreSQL timestamp type. +type Timestamp struct { + Time time.Time // Time zone will be ignored when encoding to PostgreSQL. + InfinityModifier InfinityModifier + Valid bool +} + +// ScanTimestamp implements the [TimestampScanner] interface. +func (ts *Timestamp) ScanTimestamp(v Timestamp) error { + *ts = v + return nil +} + +// TimestampValue implements the [TimestampValuer] interface. +func (ts Timestamp) TimestampValue() (Timestamp, error) { + return ts, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (ts *Timestamp) Scan(src any) error { + if src == nil { + *ts = Timestamp{} + return nil + } + + switch src := src.(type) { + case string: + return (&scanPlanTextTimestampToTimestampScanner{}).Scan([]byte(src), ts) + case time.Time: + *ts = Timestamp{Time: src, Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (ts Timestamp) Value() (driver.Value, error) { + if !ts.Valid { + return nil, nil + } + + if ts.InfinityModifier != Finite { + return ts.InfinityModifier.String(), nil + } + return ts.Time, nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (ts Timestamp) MarshalJSON() ([]byte, error) { + if !ts.Valid { + return []byte("null"), nil + } + + var s string + + switch ts.InfinityModifier { + case Finite: + s = ts.Time.Format(jsonISO8601) + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + return json.Marshal(s) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (ts *Timestamp) UnmarshalJSON(b []byte) error { + var s *string + err := json.Unmarshal(b, &s) + if err != nil { + return err + } + + if s == nil { + *ts = Timestamp{} + return nil + } + + switch *s { + case "infinity": + *ts = Timestamp{Valid: true, InfinityModifier: Infinity} + case "-infinity": + *ts = Timestamp{Valid: true, InfinityModifier: -Infinity} + default: + // Parse time with or without timezone + tss := *s + // PostgreSQL uses ISO 8601 without timezone for to_json function and casting from a string to timestamp + tim, err := time.Parse(time.RFC3339Nano, tss) + if err == nil { + *ts = Timestamp{Time: tim, Valid: true} + return nil + } + tim, err = time.ParseInLocation(jsonISO8601, tss, time.UTC) + if err == nil { + *ts = Timestamp{Time: tim, Valid: true} + return nil + } + ts.Valid = false + return fmt.Errorf("cannot unmarshal %s to timestamp with layout %s or %s (%w)", + *s, time.RFC3339Nano, jsonISO8601, err) + } + return nil +} + +type TimestampCodec struct { + // ScanLocation is the location that the time is assumed to be in for scanning. This is different from + // TimestamptzCodec.ScanLocation in that this setting does change the instant in time that the timestamp represents. + ScanLocation *time.Location +} + +func (*TimestampCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (*TimestampCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (*TimestampCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(TimestampValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTimestampCodecBinary{} + case TextFormatCode: + return encodePlanTimestampCodecText{} + } + + return nil +} + +type encodePlanTimestampCodecBinary struct{} + +func (encodePlanTimestampCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestampValuer).TimestampValue() + if err != nil { + return nil, err + } + + if !ts.Valid { + return nil, nil + } + + var microsecSinceY2K int64 + switch ts.InfinityModifier { + case Finite: + t := discardTimeZone(ts.Time) + microsecSinceUnixEpoch := t.Unix()*1_000_000 + int64(t.Nanosecond())/1000 + microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K + case Infinity: + microsecSinceY2K = infinityMicrosecondOffset + case NegativeInfinity: + microsecSinceY2K = negativeInfinityMicrosecondOffset + } + + buf = pgio.AppendInt64(buf, microsecSinceY2K) + + return buf, nil +} + +type encodePlanTimestampCodecText struct{} + +func (encodePlanTimestampCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestampValuer).TimestampValue() + if err != nil { + return nil, err + } + + if !ts.Valid { + return nil, nil + } + + var s string + + switch ts.InfinityModifier { + case Finite: + t := discardTimeZone(ts.Time) + + // Year 0000 is 1 BC + bc := false + if year := t.Year(); year <= 0 { + year = -year + 1 + t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) + bc = true + } + + s = t.Truncate(time.Microsecond).Format(pgTimestampFormat) + + if bc { + s += " BC" + } + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + buf = append(buf, s...) + + return buf, nil +} + +func discardTimeZone(t time.Time) time.Time { + if t.Location() != time.UTC { + return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) + } + + return t +} + +func (c *TimestampCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(TimestampScanner); ok { + return &scanPlanBinaryTimestampToTimestampScanner{location: c.ScanLocation} + } + case TextFormatCode: + if _, ok := target.(TimestampScanner); ok { + return &scanPlanTextTimestampToTimestampScanner{location: c.ScanLocation} + } + } + + return nil +} + +type scanPlanBinaryTimestampToTimestampScanner struct{ location *time.Location } + +func (plan *scanPlanBinaryTimestampToTimestampScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TimestampScanner) + + if src == nil { + return scanner.ScanTimestamp(Timestamp{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for timestamp: %v", len(src)) + } + + var ts Timestamp + microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + + switch microsecSinceY2K { + case infinityMicrosecondOffset: + ts = Timestamp{Valid: true, InfinityModifier: Infinity} + case negativeInfinityMicrosecondOffset: + ts = Timestamp{Valid: true, InfinityModifier: -Infinity} + default: + tim := time.Unix( + microsecFromUnixEpochToY2K/1_000_000+microsecSinceY2K/1_000_000, + (microsecFromUnixEpochToY2K%1_000_000*1_000)+(microsecSinceY2K%1_000_000*1000), + ).UTC() + if plan.location != nil { + tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) + } + ts = Timestamp{Time: tim, Valid: true} + } + + return scanner.ScanTimestamp(ts) +} + +type scanPlanTextTimestampToTimestampScanner struct{ location *time.Location } + +func (plan *scanPlanTextTimestampToTimestampScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TimestampScanner) + + if src == nil { + return scanner.ScanTimestamp(Timestamp{}) + } + + var ts Timestamp + sbuf := string(src) + switch sbuf { + case "infinity": + ts = Timestamp{Valid: true, InfinityModifier: Infinity} + case "-infinity": + ts = Timestamp{Valid: true, InfinityModifier: -Infinity} + default: + bc := false + if strings.HasSuffix(sbuf, " BC") { + sbuf = sbuf[:len(sbuf)-3] + bc = true + } + tim, err := time.Parse(pgTimestampFormat, sbuf) + if err != nil { + return err + } + + if bc { + year := -tim.Year() + 1 + tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) + } + + if plan.location != nil { + tim = time.Date(tim.Year(), tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), plan.location) + } + + ts = Timestamp{Time: tim, Valid: true} + } + + return scanner.ScanTimestamp(ts) +} + +func (c *TimestampCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var ts Timestamp + err := codecScan(c, m, oid, format, src, &ts) + if err != nil { + return nil, err + } + + if ts.InfinityModifier != Finite { + return ts.InfinityModifier.String(), nil + } + + return ts.Time, nil +} + +func (c *TimestampCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var ts Timestamp + err := codecScan(c, m, oid, format, src, &ts) + if err != nil { + return nil, err + } + + if ts.InfinityModifier != Finite { + return ts.InfinityModifier, nil + } + + return ts.Time, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go new file mode 100644 index 0000000..139312a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/timestamptz.go @@ -0,0 +1,370 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "strings" + "time" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +const ( + pgTimestamptzHourFormat = "2006-01-02 15:04:05.999999999Z07" + pgTimestamptzMinuteFormat = "2006-01-02 15:04:05.999999999Z07:00" + pgTimestamptzSecondFormat = "2006-01-02 15:04:05.999999999Z07:00:00" + microsecFromUnixEpochToY2K = 946_684_800 * 1_000_000 +) + +const ( + negativeInfinityMicrosecondOffset = -9223372036854775808 + infinityMicrosecondOffset = 9223372036854775807 +) + +type TimestamptzScanner interface { + ScanTimestamptz(v Timestamptz) error +} + +type TimestamptzValuer interface { + TimestamptzValue() (Timestamptz, error) +} + +// Timestamptz represents the PostgreSQL timestamptz type. +type Timestamptz struct { + Time time.Time + InfinityModifier InfinityModifier + Valid bool +} + +// ScanTimestamptz implements the [TimestamptzScanner] interface. +func (tstz *Timestamptz) ScanTimestamptz(v Timestamptz) error { + *tstz = v + return nil +} + +// TimestamptzValue implements the [TimestamptzValuer] interface. +func (tstz Timestamptz) TimestamptzValue() (Timestamptz, error) { + return tstz, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (tstz *Timestamptz) Scan(src any) error { + if src == nil { + *tstz = Timestamptz{} + return nil + } + + switch src := src.(type) { + case string: + return (&scanPlanTextTimestamptzToTimestamptzScanner{}).Scan([]byte(src), tstz) + case time.Time: + *tstz = Timestamptz{Time: src, Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (tstz Timestamptz) Value() (driver.Value, error) { + if !tstz.Valid { + return nil, nil + } + + if tstz.InfinityModifier != Finite { + return tstz.InfinityModifier.String(), nil + } + return tstz.Time, nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (tstz Timestamptz) MarshalJSON() ([]byte, error) { + if !tstz.Valid { + return []byte("null"), nil + } + + var s string + + switch tstz.InfinityModifier { + case Finite: + s = tstz.Time.Format(time.RFC3339Nano) + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + return json.Marshal(s) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (tstz *Timestamptz) UnmarshalJSON(b []byte) error { + var s *string + err := json.Unmarshal(b, &s) + if err != nil { + return err + } + + if s == nil { + *tstz = Timestamptz{} + return nil + } + + switch *s { + case "infinity": + *tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} + case "-infinity": + *tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} + default: + // PostgreSQL uses ISO 8601 for to_json function and casting from a string to timestamptz + tim, err := time.Parse(time.RFC3339Nano, *s) + if err != nil { + return err + } + + *tstz = Timestamptz{Time: tim, Valid: true} + } + + return nil +} + +type TimestamptzCodec struct { + // ScanLocation is the location to return scanned timestamptz values in. This does not change the instant in time that + // the timestamptz represents. + ScanLocation *time.Location +} + +func (*TimestamptzCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (*TimestamptzCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (*TimestamptzCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(TimestamptzValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTimestamptzCodecBinary{} + case TextFormatCode: + return encodePlanTimestamptzCodecText{} + } + + return nil +} + +type encodePlanTimestamptzCodecBinary struct{} + +func (encodePlanTimestamptzCodecBinary) Encode(value any, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestamptzValuer).TimestamptzValue() + if err != nil { + return nil, err + } + + if !ts.Valid { + return nil, nil + } + + var microsecSinceY2K int64 + switch ts.InfinityModifier { + case Finite: + microsecSinceUnixEpoch := ts.Time.Unix()*1000000 + int64(ts.Time.Nanosecond())/1000 + microsecSinceY2K = microsecSinceUnixEpoch - microsecFromUnixEpochToY2K + case Infinity: + microsecSinceY2K = infinityMicrosecondOffset + case NegativeInfinity: + microsecSinceY2K = negativeInfinityMicrosecondOffset + } + + buf = pgio.AppendInt64(buf, microsecSinceY2K) + + return buf, nil +} + +type encodePlanTimestamptzCodecText struct{} + +func (encodePlanTimestamptzCodecText) Encode(value any, buf []byte) (newBuf []byte, err error) { + ts, err := value.(TimestamptzValuer).TimestamptzValue() + if err != nil { + return nil, err + } + + if !ts.Valid { + return nil, nil + } + + var s string + + switch ts.InfinityModifier { + case Finite: + + t := ts.Time.UTC().Truncate(time.Microsecond) + + // Year 0000 is 1 BC + bc := false + if year := t.Year(); year <= 0 { + year = -year + 1 + t = time.Date(year, t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC) + bc = true + } + + s = t.Format(pgTimestamptzSecondFormat) + + if bc { + s += " BC" + } + case Infinity: + s = "infinity" + case NegativeInfinity: + s = "-infinity" + } + + buf = append(buf, s...) + + return buf, nil +} + +func (c *TimestamptzCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(TimestamptzScanner); ok { + return &scanPlanBinaryTimestamptzToTimestamptzScanner{location: c.ScanLocation} + } + case TextFormatCode: + if _, ok := target.(TimestamptzScanner); ok { + return &scanPlanTextTimestamptzToTimestamptzScanner{location: c.ScanLocation} + } + } + + return nil +} + +type scanPlanBinaryTimestamptzToTimestamptzScanner struct{ location *time.Location } + +func (plan *scanPlanBinaryTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TimestamptzScanner) + + if src == nil { + return scanner.ScanTimestamptz(Timestamptz{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for timestamptz: %v", len(src)) + } + + var tstz Timestamptz + microsecSinceY2K := int64(binary.BigEndian.Uint64(src)) + + switch microsecSinceY2K { + case infinityMicrosecondOffset: + tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} + case negativeInfinityMicrosecondOffset: + tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} + default: + tim := time.Unix( + microsecFromUnixEpochToY2K/1_000_000+microsecSinceY2K/1_000_000, + (microsecFromUnixEpochToY2K%1_000_000*1_000)+(microsecSinceY2K%1_000_000*1_000), + ) + if plan.location != nil { + tim = tim.In(plan.location) + } + tstz = Timestamptz{Time: tim, Valid: true} + } + + return scanner.ScanTimestamptz(tstz) +} + +type scanPlanTextTimestamptzToTimestamptzScanner struct{ location *time.Location } + +func (plan *scanPlanTextTimestamptzToTimestamptzScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TimestamptzScanner) + + if src == nil { + return scanner.ScanTimestamptz(Timestamptz{}) + } + + var tstz Timestamptz + sbuf := string(src) + switch sbuf { + case "infinity": + tstz = Timestamptz{Valid: true, InfinityModifier: Infinity} + case "-infinity": + tstz = Timestamptz{Valid: true, InfinityModifier: -Infinity} + default: + bc := false + if strings.HasSuffix(sbuf, " BC") { + sbuf = sbuf[:len(sbuf)-3] + bc = true + } + + var format string + switch { + case len(sbuf) >= 9 && (sbuf[len(sbuf)-9] == '-' || sbuf[len(sbuf)-9] == '+'): + format = pgTimestamptzSecondFormat + case len(sbuf) >= 6 && (sbuf[len(sbuf)-6] == '-' || sbuf[len(sbuf)-6] == '+'): + format = pgTimestamptzMinuteFormat + default: + format = pgTimestamptzHourFormat + } + + tim, err := time.Parse(format, sbuf) + if err != nil { + return err + } + + if bc { + year := -tim.Year() + 1 + tim = time.Date(year, tim.Month(), tim.Day(), tim.Hour(), tim.Minute(), tim.Second(), tim.Nanosecond(), tim.Location()) + } + + if plan.location != nil { + tim = tim.In(plan.location) + } + + tstz = Timestamptz{Time: tim, Valid: true} + } + + return scanner.ScanTimestamptz(tstz) +} + +func (c *TimestamptzCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var tstz Timestamptz + err := codecScan(c, m, oid, format, src, &tstz) + if err != nil { + return nil, err + } + + if tstz.InfinityModifier != Finite { + return tstz.InfinityModifier.String(), nil + } + + return tstz.Time, nil +} + +func (c *TimestamptzCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var tstz Timestamptz + err := codecScan(c, m, oid, format, src, &tstz) + if err != nil { + return nil, err + } + + if tstz.InfinityModifier != Finite { + return tstz.InfinityModifier, nil + } + + return tstz.Time, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go b/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go new file mode 100644 index 0000000..cc7b831 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/tsvector.go @@ -0,0 +1,514 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "encoding/binary" + "fmt" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type TSVectorScanner interface { + ScanTSVector(TSVector) error +} + +type TSVectorValuer interface { + TSVectorValue() (TSVector, error) +} + +// TSVector represents a PostgreSQL tsvector value. +type TSVector struct { + Lexemes []TSVectorLexeme + Valid bool +} + +// TSVectorLexeme represents a lexeme within a tsvector, consisting of a word and its positions. +type TSVectorLexeme struct { + Word string + Positions []TSVectorPosition +} + +// ScanTSVector implements the [TSVectorScanner] interface. +func (t *TSVector) ScanTSVector(v TSVector) error { + *t = v + return nil +} + +// TSVectorValue implements the [TSVectorValuer] interface. +func (t TSVector) TSVectorValue() (TSVector, error) { + return t, nil +} + +func (t TSVector) String() string { + buf, _ := encodePlanTSVectorCodecText{}.Encode(t, nil) + return string(buf) +} + +// Scan implements the [database/sql.Scanner] interface. +func (t *TSVector) Scan(src any) error { + if src == nil { + *t = TSVector{} + return nil + } + + if src, ok := src.(string); ok { + return scanPlanTextAnyToTSVectorScanner{}.scanString(src, t) + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (t TSVector) Value() (driver.Value, error) { + if !t.Valid { + return nil, nil + } + + buf, err := TSVectorCodec{}.PlanEncode(nil, 0, TextFormatCode, t).Encode(t, nil) + if err != nil { + return nil, err + } + + return string(buf), nil +} + +// TSVectorWeight represents the weight label of a lexeme position in a tsvector. +type TSVectorWeight byte + +const ( + TSVectorWeightA = TSVectorWeight('A') + TSVectorWeightB = TSVectorWeight('B') + TSVectorWeightC = TSVectorWeight('C') + TSVectorWeightD = TSVectorWeight('D') +) + +// tsvectorWeightToBinary converts a TSVectorWeight to the 2-bit binary encoding used by PostgreSQL. +func tsvectorWeightToBinary(w TSVectorWeight) uint16 { + switch w { + case TSVectorWeightA: + return 3 + case TSVectorWeightB: + return 2 + case TSVectorWeightC: + return 1 + default: + return 0 // D or unset + } +} + +// tsvectorWeightFromBinary converts a 2-bit binary weight value to a TSVectorWeight. +func tsvectorWeightFromBinary(b uint16) TSVectorWeight { + switch b { + case 3: + return TSVectorWeightA + case 2: + return TSVectorWeightB + case 1: + return TSVectorWeightC + default: + return TSVectorWeightD + } +} + +// TSVectorPosition represents a lexeme position and its optional weight within a tsvector. +type TSVectorPosition struct { + Position uint16 + Weight TSVectorWeight +} + +func (p TSVectorPosition) String() string { + s := strconv.FormatUint(uint64(p.Position), 10) + if p.Weight != 0 && p.Weight != TSVectorWeightD { + s += string(p.Weight) + } + return s +} + +type TSVectorCodec struct{} + +func (TSVectorCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (TSVectorCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (TSVectorCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(TSVectorValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanTSVectorCodecBinary{} + case TextFormatCode: + return encodePlanTSVectorCodecText{} + } + + return nil +} + +type encodePlanTSVectorCodecBinary struct{} + +func (encodePlanTSVectorCodecBinary) Encode(value any, buf []byte) ([]byte, error) { + tsv, err := value.(TSVectorValuer).TSVectorValue() + if err != nil { + return nil, err + } + + if !tsv.Valid { + return nil, nil + } + + buf = pgio.AppendInt32(buf, int32(len(tsv.Lexemes))) + + for _, entry := range tsv.Lexemes { + buf = append(buf, entry.Word...) + buf = append(buf, 0x00) + buf = pgio.AppendUint16(buf, uint16(len(entry.Positions))) + + // Each position is a uint16: weight (2 bits) | position (14 bits) + for _, pos := range entry.Positions { + packed := tsvectorWeightToBinary(pos.Weight)<<14 | pos.Position&0x3FFF + buf = pgio.AppendUint16(buf, packed) + } + } + + return buf, nil +} + +type scanPlanBinaryTSVectorToTSVectorScanner struct{} + +func (scanPlanBinaryTSVectorToTSVectorScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TSVectorScanner) + + if src == nil { + return scanner.ScanTSVector(TSVector{}) + } + + rp := 0 + + const ( + uint16Len = 2 + uint32Len = 4 + ) + + if len(src[rp:]) < uint32Len { + return fmt.Errorf("tsvector incomplete %v", src) + } + entryCount := int(int32(binary.BigEndian.Uint32(src[rp:]))) + rp += uint32Len + + if entryCount < 0 { + return fmt.Errorf("tsvector invalid lexeme count: %d", entryCount) + } + // Each lexeme carries at minimum a 1-byte NUL terminator and a 2-byte position count, so + // entryCount cannot exceed remaining/3. This bounds the up-front make() against a malicious + // server claiming a huge lexeme count in a small message. + if maxEntries := len(src[rp:]) / 3; entryCount > maxEntries { + return fmt.Errorf("tsvector invalid lexeme count %d for %d remaining bytes", entryCount, len(src[rp:])) + } + + var tsv TSVector + if entryCount > 0 { + tsv.Lexemes = make([]TSVectorLexeme, entryCount) + } + + for i := range entryCount { + nullIndex := bytes.IndexByte(src[rp:], 0x00) + if nullIndex == -1 { + return fmt.Errorf("invalid tsvector binary format: missing null terminator") + } + + lexeme := TSVectorLexeme{Word: string(src[rp : rp+nullIndex])} + rp += nullIndex + 1 // skip past null terminator + + // Read position count. + if len(src[rp:]) < uint16Len { + return fmt.Errorf("invalid tsvector binary format: incomplete position count") + } + + numPositions := int(binary.BigEndian.Uint16(src[rp:])) + rp += uint16Len + + // Read each packed position: weight (2 bits) | position (14 bits) + if len(src[rp:]) < numPositions*uint16Len { + return fmt.Errorf("invalid tsvector binary format: incomplete positions") + } + + if numPositions > 0 { + lexeme.Positions = make([]TSVectorPosition, numPositions) + for pos := range numPositions { + packed := binary.BigEndian.Uint16(src[rp:]) + rp += uint16Len + lexeme.Positions[pos] = TSVectorPosition{ + Position: packed & 0x3FFF, + Weight: tsvectorWeightFromBinary(packed >> 14), + } + } + } + + tsv.Lexemes[i] = lexeme + } + tsv.Valid = true + + return scanner.ScanTSVector(tsv) +} + +var tsvectorLexemeReplacer = strings.NewReplacer( + `\`, `\\`, + `'`, `\'`, +) + +type encodePlanTSVectorCodecText struct{} + +func (encodePlanTSVectorCodecText) Encode(value any, buf []byte) ([]byte, error) { + tsv, err := value.(TSVectorValuer).TSVectorValue() + if err != nil { + return nil, err + } + + if !tsv.Valid { + return nil, nil + } + + if buf == nil { + buf = []byte{} + } + + for i, lex := range tsv.Lexemes { + if i > 0 { + buf = append(buf, ' ') + } + + buf = append(buf, '\'') + buf = append(buf, tsvectorLexemeReplacer.Replace(lex.Word)...) + buf = append(buf, '\'') + + sep := byte(':') + for _, p := range lex.Positions { + buf = append(buf, sep) + buf = append(buf, p.String()...) + sep = ',' + } + } + + return buf, nil +} + +func (TSVectorCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + if _, ok := target.(TSVectorScanner); ok { + return scanPlanBinaryTSVectorToTSVectorScanner{} + } + case TextFormatCode: + if _, ok := target.(TSVectorScanner); ok { + return scanPlanTextAnyToTSVectorScanner{} + } + } + + return nil +} + +type scanPlanTextAnyToTSVectorScanner struct{} + +func (s scanPlanTextAnyToTSVectorScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TSVectorScanner) + + if src == nil { + return scanner.ScanTSVector(TSVector{}) + } + + return s.scanString(string(src), scanner) +} + +func (scanPlanTextAnyToTSVectorScanner) scanString(src string, scanner TSVectorScanner) error { + tsv, err := parseTSVector(src) + if err != nil { + return err + } + return scanner.ScanTSVector(tsv) +} + +func (c TSVectorCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + return codecDecodeToTextFormat(c, m, oid, format, src) +} + +func (c TSVectorCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var tsv TSVector + err := codecScan(c, m, oid, format, src, &tsv) + if err != nil { + return nil, err + } + return tsv, nil +} + +type tsvectorParser struct { + str string + pos int +} + +func (p *tsvectorParser) atEnd() bool { + return p.pos >= len(p.str) +} + +func (p *tsvectorParser) peek() byte { + return p.str[p.pos] +} + +func (p *tsvectorParser) consume() (byte, bool) { + if p.pos >= len(p.str) { + return 0, true + } + b := p.str[p.pos] + p.pos++ + return b, false +} + +func (p *tsvectorParser) consumeSpaces() { + for !p.atEnd() && p.peek() == ' ' { + p.consume() + } +} + +// consumeLexeme consumes a single-quoted lexeme, handling single quotes and backslash escapes. +func (p *tsvectorParser) consumeLexeme() (string, error) { + ch, end := p.consume() + if end || ch != '\'' { + return "", fmt.Errorf("invalid tsvector format: lexeme must start with a single quote") + } + + var buf strings.Builder + for { + ch, end := p.consume() + if end { + return "", fmt.Errorf("invalid tsvector format: unterminated quoted lexeme") + } + + switch ch { + case '\'': + // Escaped quote ('') — write a literal single quote + if !p.atEnd() && p.peek() == '\'' { + p.consume() + buf.WriteByte('\'') + } else { + // Closing quote — lexeme is complete + return buf.String(), nil + } + case '\\': + next, end := p.consume() + if end { + return "", fmt.Errorf("invalid tsvector format: unexpected end after backslash") + } + buf.WriteByte(next) + default: + buf.WriteByte(ch) + } + } +} + +// consumePositions consumes a comma-separated list of position[weight] values. +func (p *tsvectorParser) consumePositions() ([]TSVectorPosition, error) { + var positions []TSVectorPosition + + for { + pos, err := p.consumePosition() + if err != nil { + return nil, err + } + positions = append(positions, pos) + + if p.atEnd() || p.peek() != ',' { + break + } + + p.consume() // skip ',' + } + + return positions, nil +} + +// consumePosition consumes a single position number with optional weight letter. +func (p *tsvectorParser) consumePosition() (TSVectorPosition, error) { + start := p.pos + + for !p.atEnd() && p.peek() >= '0' && p.peek() <= '9' { + p.consume() + } + + if p.pos == start { + return TSVectorPosition{}, fmt.Errorf("invalid tsvector format: expected position number") + } + + num, err := strconv.ParseUint(p.str[start:p.pos], 10, 16) + if err != nil { + return TSVectorPosition{}, fmt.Errorf("invalid tsvector format: invalid position number %q", p.str[start:p.pos]) + } + + pos := TSVectorPosition{Position: uint16(num), Weight: TSVectorWeightD} + + // Check for optional weight letter + if !p.atEnd() { + switch p.peek() { + case 'A', 'a': + pos.Weight = TSVectorWeightA + case 'B', 'b': + pos.Weight = TSVectorWeightB + case 'C', 'c': + pos.Weight = TSVectorWeightC + case 'D', 'd': + pos.Weight = TSVectorWeightD + default: + return pos, nil + } + p.consume() + } + + return pos, nil +} + +// parseTSVector parses a PostgreSQL tsvector text representation. +func parseTSVector(s string) (TSVector, error) { + result := TSVector{} + p := &tsvectorParser{str: strings.TrimSpace(s), pos: 0} + + for !p.atEnd() { + p.consumeSpaces() + if p.atEnd() { + break + } + + word, err := p.consumeLexeme() + if err != nil { + return TSVector{}, err + } + + entry := TSVectorLexeme{Word: word} + + // Check for optional positions after ':' + if !p.atEnd() && p.peek() == ':' { + p.consume() // skip ':' + + positions, err := p.consumePositions() + if err != nil { + return TSVector{}, err + } + entry.Positions = positions + } + + result.Lexemes = append(result.Lexemes, entry) + } + + result.Valid = true + + return result, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go new file mode 100644 index 0000000..e6d4b1c --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uint32.go @@ -0,0 +1,352 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "encoding/json" + "fmt" + "math" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Uint32Scanner interface { + ScanUint32(v Uint32) error +} + +type Uint32Valuer interface { + Uint32Value() (Uint32, error) +} + +// Uint32 is the core type that is used to represent PostgreSQL types such as OID, CID, and XID. +type Uint32 struct { + Uint32 uint32 + Valid bool +} + +// ScanUint32 implements the [Uint32Scanner] interface. +func (n *Uint32) ScanUint32(v Uint32) error { + *n = v + return nil +} + +// Uint32Value implements the [Uint32Valuer] interface. +func (n Uint32) Uint32Value() (Uint32, error) { + return n, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Uint32) Scan(src any) error { + if src == nil { + *dst = Uint32{} + return nil + } + + var n int64 + + switch src := src.(type) { + case int64: + n = src + case string: + un, err := strconv.ParseUint(src, 10, 32) + if err != nil { + return err + } + n = int64(un) + default: + return fmt.Errorf("cannot scan %T", src) + } + + if n < 0 { + return fmt.Errorf("%d is less than the minimum value for Uint32", n) + } + if n > math.MaxUint32 { + return fmt.Errorf("%d is greater than maximum value for Uint32", n) + } + + *dst = Uint32{Uint32: uint32(n), Valid: true} + + return nil +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Uint32) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + return int64(src.Uint32), nil +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src Uint32) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + return json.Marshal(src.Uint32) +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *Uint32) UnmarshalJSON(b []byte) error { + var n *uint32 + err := json.Unmarshal(b, &n) + if err != nil { + return err + } + + if n == nil { + *dst = Uint32{} + } else { + *dst = Uint32{Uint32: *n, Valid: true} + } + + return nil +} + +type Uint32Codec struct{} + +func (Uint32Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Uint32Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Uint32Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case uint32: + return encodePlanUint32CodecBinaryUint32{} + case Uint32Valuer: + return encodePlanUint32CodecBinaryUint32Valuer{} + case Int64Valuer: + return encodePlanUint32CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case uint32: + return encodePlanUint32CodecTextUint32{} + case Int64Valuer: + return encodePlanUint32CodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanUint32CodecBinaryUint32 struct{} + +func (encodePlanUint32CodecBinaryUint32) Encode(value any, buf []byte) (newBuf []byte, err error) { + v := value.(uint32) + return pgio.AppendUint32(buf, v), nil +} + +type encodePlanUint32CodecBinaryUint32Valuer struct{} + +func (encodePlanUint32CodecBinaryUint32Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Uint32Valuer).Uint32Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + return pgio.AppendUint32(buf, v.Uint32), nil +} + +type encodePlanUint32CodecBinaryInt64Valuer struct{} + +func (encodePlanUint32CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + if v.Int64 < 0 { + return nil, fmt.Errorf("%d is less than minimum value for uint32", v.Int64) + } + if v.Int64 > math.MaxUint32 { + return nil, fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) + } + + return pgio.AppendUint32(buf, uint32(v.Int64)), nil +} + +type encodePlanUint32CodecTextUint32 struct{} + +func (encodePlanUint32CodecTextUint32) Encode(value any, buf []byte) (newBuf []byte, err error) { + v := value.(uint32) + return append(buf, strconv.FormatUint(uint64(v), 10)...), nil +} + +type encodePlanUint32CodecTextUint32Valuer struct{} + +func (encodePlanUint32CodecTextUint32Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Uint32Valuer).Uint32Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + return append(buf, strconv.FormatUint(uint64(v.Uint32), 10)...), nil +} + +type encodePlanUint32CodecTextInt64Valuer struct{} + +func (encodePlanUint32CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + if v.Int64 < 0 { + return nil, fmt.Errorf("%d is less than minimum value for uint32", v.Int64) + } + if v.Int64 > math.MaxUint32 { + return nil, fmt.Errorf("%d is greater than maximum value for uint32", v.Int64) + } + + return append(buf, strconv.FormatInt(v.Int64, 10)...), nil +} + +func (Uint32Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *uint32: + return scanPlanBinaryUint32ToUint32{} + case Uint32Scanner: + return scanPlanBinaryUint32ToUint32Scanner{} + case TextScanner: + return scanPlanBinaryUint32ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *uint32: + return scanPlanTextAnyToUint32{} + case Uint32Scanner: + return scanPlanTextAnyToUint32Scanner{} + } + } + + return nil +} + +func (c Uint32Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n uint32 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return int64(n), nil +} + +func (c Uint32Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n uint32 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +type scanPlanBinaryUint32ToUint32 struct{} + +func (scanPlanBinaryUint32ToUint32) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint32: %v", len(src)) + } + + p := (dst).(*uint32) + *p = binary.BigEndian.Uint32(src) + + return nil +} + +type scanPlanBinaryUint32ToUint32Scanner struct{} + +func (scanPlanBinaryUint32ToUint32Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Uint32Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanUint32(Uint32{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint32: %v", len(src)) + } + + n := binary.BigEndian.Uint32(src) + + return s.ScanUint32(Uint32{Uint32: n, Valid: true}) +} + +type scanPlanBinaryUint32ToTextScanner struct{} + +func (scanPlanBinaryUint32ToTextScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 4 { + return fmt.Errorf("invalid length for uint32: %v", len(src)) + } + + n := uint64(binary.BigEndian.Uint32(src)) + return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) +} + +type scanPlanTextAnyToUint32Scanner struct{} + +func (scanPlanTextAnyToUint32Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Uint32Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanUint32(Uint32{}) + } + + n, err := strconv.ParseUint(string(src), 10, 32) + if err != nil { + return err + } + + return s.ScanUint32(Uint32{Uint32: uint32(n), Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go new file mode 100644 index 0000000..fc407bd --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uint64.go @@ -0,0 +1,323 @@ +package pgtype + +import ( + "database/sql/driver" + "encoding/binary" + "fmt" + "math" + "strconv" + + "github.com/jackc/pgx/v5/internal/pgio" +) + +type Uint64Scanner interface { + ScanUint64(v Uint64) error +} + +type Uint64Valuer interface { + Uint64Value() (Uint64, error) +} + +// Uint64 is the core type that is used to represent PostgreSQL types such as XID8. +type Uint64 struct { + Uint64 uint64 + Valid bool +} + +// ScanUint64 implements the [Uint64Scanner] interface. +func (n *Uint64) ScanUint64(v Uint64) error { + *n = v + return nil +} + +// Uint64Value implements the [Uint64Valuer] interface. +func (n Uint64) Uint64Value() (Uint64, error) { + return n, nil +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *Uint64) Scan(src any) error { + if src == nil { + *dst = Uint64{} + return nil + } + + var n uint64 + + switch src := src.(type) { + case int64: + if src < 0 { + return fmt.Errorf("%d is less than the minimum value for Uint64", src) + } + n = uint64(src) + case string: + un, err := strconv.ParseUint(src, 10, 64) + if err != nil { + return err + } + n = un + default: + return fmt.Errorf("cannot scan %T", src) + } + + *dst = Uint64{Uint64: n, Valid: true} + + return nil +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src Uint64) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + // If the value is greater than the maximum value for int64, return it as a string instead of losing data or returning + // an error. + if src.Uint64 > math.MaxInt64 { + return strconv.FormatUint(src.Uint64, 10), nil + } + + return int64(src.Uint64), nil +} + +type Uint64Codec struct{} + +func (Uint64Codec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (Uint64Codec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (Uint64Codec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch format { + case BinaryFormatCode: + switch value.(type) { + case uint64: + return encodePlanUint64CodecBinaryUint64{} + case Uint64Valuer: + return encodePlanUint64CodecBinaryUint64Valuer{} + case Int64Valuer: + return encodePlanUint64CodecBinaryInt64Valuer{} + } + case TextFormatCode: + switch value.(type) { + case uint64: + return encodePlanUint64CodecTextUint64{} + case Int64Valuer: + return encodePlanUint64CodecTextInt64Valuer{} + } + } + + return nil +} + +type encodePlanUint64CodecBinaryUint64 struct{} + +func (encodePlanUint64CodecBinaryUint64) Encode(value any, buf []byte) (newBuf []byte, err error) { + v := value.(uint64) + return pgio.AppendUint64(buf, v), nil +} + +type encodePlanUint64CodecBinaryUint64Valuer struct{} + +func (encodePlanUint64CodecBinaryUint64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Uint64Valuer).Uint64Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + return pgio.AppendUint64(buf, v.Uint64), nil +} + +type encodePlanUint64CodecBinaryInt64Valuer struct{} + +func (encodePlanUint64CodecBinaryInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + if v.Int64 < 0 { + return nil, fmt.Errorf("%d is less than minimum value for uint64", v.Int64) + } + + return pgio.AppendUint64(buf, uint64(v.Int64)), nil +} + +type encodePlanUint64CodecTextUint64 struct{} + +func (encodePlanUint64CodecTextUint64) Encode(value any, buf []byte) (newBuf []byte, err error) { + v := value.(uint64) + return append(buf, strconv.FormatUint(v, 10)...), nil +} + +type encodePlanUint64CodecTextUint64Valuer struct{} + +func (encodePlanUint64CodecTextUint64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Uint64Valuer).Uint64Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + return append(buf, strconv.FormatUint(v.Uint64, 10)...), nil +} + +type encodePlanUint64CodecTextInt64Valuer struct{} + +func (encodePlanUint64CodecTextInt64Valuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + v, err := value.(Int64Valuer).Int64Value() + if err != nil { + return nil, err + } + + if !v.Valid { + return nil, nil + } + + if v.Int64 < 0 { + return nil, fmt.Errorf("%d is less than minimum value for uint64", v.Int64) + } + + return append(buf, strconv.FormatInt(v.Int64, 10)...), nil +} + +func (Uint64Codec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case *uint64: + return scanPlanBinaryUint64ToUint64{} + case Uint64Scanner: + return scanPlanBinaryUint64ToUint64Scanner{} + case TextScanner: + return scanPlanBinaryUint64ToTextScanner{} + } + case TextFormatCode: + switch target.(type) { + case *uint64: + return scanPlanTextAnyToUint64{} + case Uint64Scanner: + return scanPlanTextAnyToUint64Scanner{} + } + } + + return nil +} + +func (c Uint64Codec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var n uint64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return int64(n), nil +} + +func (c Uint64Codec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var n uint64 + err := codecScan(c, m, oid, format, src, &n) + if err != nil { + return nil, err + } + return n, nil +} + +type scanPlanBinaryUint64ToUint64 struct{} + +func (scanPlanBinaryUint64ToUint64) Scan(src []byte, dst any) error { + if src == nil { + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint64: %v", len(src)) + } + + p := (dst).(*uint64) + *p = binary.BigEndian.Uint64(src) + + return nil +} + +type scanPlanBinaryUint64ToUint64Scanner struct{} + +func (scanPlanBinaryUint64ToUint64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Uint64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanUint64(Uint64{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint64: %v", len(src)) + } + + n := binary.BigEndian.Uint64(src) + + return s.ScanUint64(Uint64{Uint64: n, Valid: true}) +} + +type scanPlanBinaryUint64ToTextScanner struct{} + +func (scanPlanBinaryUint64ToTextScanner) Scan(src []byte, dst any) error { + s, ok := (dst).(TextScanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanText(Text{}) + } + + if len(src) != 8 { + return fmt.Errorf("invalid length for uint64: %v", len(src)) + } + + n := binary.BigEndian.Uint64(src) + return s.ScanText(Text{String: strconv.FormatUint(n, 10), Valid: true}) +} + +type scanPlanTextAnyToUint64Scanner struct{} + +func (scanPlanTextAnyToUint64Scanner) Scan(src []byte, dst any) error { + s, ok := (dst).(Uint64Scanner) + if !ok { + return ErrScanTargetTypeChanged + } + + if src == nil { + return s.ScanUint64(Uint64{}) + } + + n, err := strconv.ParseUint(string(src), 10, 64) + if err != nil { + return err + } + + return s.ScanUint64(Uint64{Uint64: n, Valid: true}) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go new file mode 100644 index 0000000..476889a --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/uuid.go @@ -0,0 +1,291 @@ +package pgtype + +import ( + "bytes" + "database/sql/driver" + "encoding/hex" + "fmt" +) + +type UUIDScanner interface { + ScanUUID(v UUID) error +} + +type UUIDValuer interface { + UUIDValue() (UUID, error) +} + +type UUID struct { + Bytes [16]byte + Valid bool +} + +// ScanUUID implements the [UUIDScanner] interface. +func (b *UUID) ScanUUID(v UUID) error { + *b = v + return nil +} + +// UUIDValue implements the [UUIDValuer] interface. +func (b UUID) UUIDValue() (UUID, error) { + return b, nil +} + +// parseUUID converts a string UUID in standard form to a byte array. +func parseUUID(src string) (dst [16]byte, err error) { + switch len(src) { + case 36: + src = src[0:8] + src[9:13] + src[14:18] + src[19:23] + src[24:] + case 32: + // dashes already stripped, assume valid + default: + // assume invalid. + return dst, fmt.Errorf("cannot parse UUID %v", src) + } + + buf, err := hex.DecodeString(src) + if err != nil { + return dst, err + } + + copy(dst[:], buf) + return dst, err +} + +// encodeUUID converts a uuid byte array to UUID standard string form. +func encodeUUID(src [16]byte) string { + var buf [36]byte + + hex.Encode(buf[0:8], src[:4]) + buf[8] = '-' + hex.Encode(buf[9:13], src[4:6]) + buf[13] = '-' + hex.Encode(buf[14:18], src[6:8]) + buf[18] = '-' + hex.Encode(buf[19:23], src[8:10]) + buf[23] = '-' + hex.Encode(buf[24:], src[10:]) + + return string(buf[:]) +} + +// Scan implements the [database/sql.Scanner] interface. +func (dst *UUID) Scan(src any) error { + if src == nil { + *dst = UUID{} + return nil + } + + if src, ok := src.(string); ok { + buf, err := parseUUID(src) + if err != nil { + return err + } + *dst = UUID{Bytes: buf, Valid: true} + return nil + } + + return fmt.Errorf("cannot scan %T", src) +} + +// Value implements the [database/sql/driver.Valuer] interface. +func (src UUID) Value() (driver.Value, error) { + if !src.Valid { + return nil, nil + } + + return encodeUUID(src.Bytes), nil +} + +func (src UUID) String() string { + if !src.Valid { + return "" + } + + return encodeUUID(src.Bytes) +} + +// MarshalJSON implements the [encoding/json.Marshaler] interface. +func (src UUID) MarshalJSON() ([]byte, error) { + if !src.Valid { + return []byte("null"), nil + } + + var buff bytes.Buffer + buff.WriteByte('"') + buff.WriteString(encodeUUID(src.Bytes)) + buff.WriteByte('"') + return buff.Bytes(), nil +} + +// UnmarshalJSON implements the [encoding/json.Unmarshaler] interface. +func (dst *UUID) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + *dst = UUID{} + return nil + } + if len(src) != 38 { + return fmt.Errorf("invalid length for UUID: %v", len(src)) + } + buf, err := parseUUID(string(src[1 : len(src)-1])) + if err != nil { + return err + } + *dst = UUID{Bytes: buf, Valid: true} + return nil +} + +type UUIDCodec struct{} + +func (UUIDCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (UUIDCodec) PreferredFormat() int16 { + return BinaryFormatCode +} + +func (UUIDCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + if _, ok := value.(UUIDValuer); !ok { + return nil + } + + switch format { + case BinaryFormatCode: + return encodePlanUUIDCodecBinaryUUIDValuer{} + case TextFormatCode: + return encodePlanUUIDCodecTextUUIDValuer{} + } + + return nil +} + +type encodePlanUUIDCodecBinaryUUIDValuer struct{} + +func (encodePlanUUIDCodecBinaryUUIDValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + uuid, err := value.(UUIDValuer).UUIDValue() + if err != nil { + return nil, err + } + + if !uuid.Valid { + return nil, nil + } + + return append(buf, uuid.Bytes[:]...), nil +} + +type encodePlanUUIDCodecTextUUIDValuer struct{} + +func (encodePlanUUIDCodecTextUUIDValuer) Encode(value any, buf []byte) (newBuf []byte, err error) { + uuid, err := value.(UUIDValuer).UUIDValue() + if err != nil { + return nil, err + } + + if !uuid.Valid { + return nil, nil + } + + return append(buf, encodeUUID(uuid.Bytes)...), nil +} + +func (UUIDCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch format { + case BinaryFormatCode: + switch target.(type) { + case UUIDScanner: + return scanPlanBinaryUUIDToUUIDScanner{} + case TextScanner: + return scanPlanBinaryUUIDToTextScanner{} + } + case TextFormatCode: + if _, ok := target.(UUIDScanner); ok { + return scanPlanTextAnyToUUIDScanner{} + } + } + + return nil +} + +type scanPlanBinaryUUIDToUUIDScanner struct{} + +func (scanPlanBinaryUUIDToUUIDScanner) Scan(src []byte, dst any) error { + scanner := (dst).(UUIDScanner) + + if src == nil { + return scanner.ScanUUID(UUID{}) + } + + if len(src) != 16 { + return fmt.Errorf("invalid length for UUID: %v", len(src)) + } + + uuid := UUID{Valid: true} + copy(uuid.Bytes[:], src) + + return scanner.ScanUUID(uuid) +} + +type scanPlanBinaryUUIDToTextScanner struct{} + +func (scanPlanBinaryUUIDToTextScanner) Scan(src []byte, dst any) error { + scanner := (dst).(TextScanner) + + if src == nil { + return scanner.ScanText(Text{}) + } + + if len(src) != 16 { + return fmt.Errorf("invalid length for UUID: %v", len(src)) + } + + var buf [16]byte + copy(buf[:], src) + + return scanner.ScanText(Text{String: encodeUUID(buf), Valid: true}) +} + +type scanPlanTextAnyToUUIDScanner struct{} + +func (scanPlanTextAnyToUUIDScanner) Scan(src []byte, dst any) error { + scanner := (dst).(UUIDScanner) + + if src == nil { + return scanner.ScanUUID(UUID{}) + } + + buf, err := parseUUID(string(src)) + if err != nil { + return err + } + + return scanner.ScanUUID(UUID{Bytes: buf, Valid: true}) +} + +func (c UUIDCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + var uuid UUID + err := codecScan(c, m, oid, format, src, &uuid) + if err != nil { + return nil, err + } + + return encodeUUID(uuid.Bytes), nil +} + +func (c UUIDCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var uuid UUID + err := codecScan(c, m, oid, format, src, &uuid) + if err != nil { + return nil, err + } + return uuid.Bytes, nil +} diff --git a/vendor/github.com/jackc/pgx/v5/pgtype/xml.go b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go new file mode 100644 index 0000000..66e6dff --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgtype/xml.go @@ -0,0 +1,198 @@ +package pgtype + +import ( + "database/sql" + "database/sql/driver" + "encoding/xml" + "fmt" + "reflect" +) + +type XMLCodec struct { + Marshal func(v any) ([]byte, error) + Unmarshal func(data []byte, v any) error +} + +func (*XMLCodec) FormatSupported(format int16) bool { + return format == TextFormatCode || format == BinaryFormatCode +} + +func (*XMLCodec) PreferredFormat() int16 { + return TextFormatCode +} + +func (c *XMLCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan { + switch value.(type) { + case string: + return encodePlanXMLCodecEitherFormatString{} + case []byte: + return encodePlanXMLCodecEitherFormatByteSlice{} + + // Cannot rely on driver.Valuer being handled later because anything can be marshalled. + // + // https://github.com/jackc/pgx/issues/1430 + // + // Check for driver.Valuer must come before xml.Marshaler so that it is guaranteed to be used + // when both are implemented https://github.com/jackc/pgx/issues/1805 + case driver.Valuer: + return &encodePlanDriverValuer{m: m, oid: oid, formatCode: format} + + // Must come before trying wrap encode plans because a pointer to a struct may be unwrapped to a struct that can be + // marshalled. + // + // https://github.com/jackc/pgx/issues/1681 + case xml.Marshaler: + return &encodePlanXMLCodecEitherFormatMarshal{ + marshal: c.Marshal, + } + } + + // Because anything can be marshalled the normal wrapping in Map.PlanScan doesn't get a chance to run. So try the + // appropriate wrappers here. + for _, f := range []TryWrapEncodePlanFunc{ + TryWrapDerefPointerEncodePlan, + TryWrapFindUnderlyingTypeEncodePlan, + } { + if wrapperPlan, nextValue, ok := f(value); ok { + if nextPlan := c.PlanEncode(m, oid, format, nextValue); nextPlan != nil { + wrapperPlan.SetNext(nextPlan) + return wrapperPlan + } + } + } + + return &encodePlanXMLCodecEitherFormatMarshal{ + marshal: c.Marshal, + } +} + +type encodePlanXMLCodecEitherFormatString struct{} + +func (encodePlanXMLCodecEitherFormatString) Encode(value any, buf []byte) (newBuf []byte, err error) { + xmlString := value.(string) + buf = append(buf, xmlString...) + return buf, nil +} + +type encodePlanXMLCodecEitherFormatByteSlice struct{} + +func (encodePlanXMLCodecEitherFormatByteSlice) Encode(value any, buf []byte) (newBuf []byte, err error) { + xmlBytes := value.([]byte) + if xmlBytes == nil { + return nil, nil + } + + buf = append(buf, xmlBytes...) + return buf, nil +} + +type encodePlanXMLCodecEitherFormatMarshal struct { + marshal func(v any) ([]byte, error) +} + +func (e *encodePlanXMLCodecEitherFormatMarshal) Encode(value any, buf []byte) (newBuf []byte, err error) { + xmlBytes, err := e.marshal(value) + if err != nil { + return nil, err + } + + buf = append(buf, xmlBytes...) + return buf, nil +} + +func (c *XMLCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan { + switch target.(type) { + case *string: + return scanPlanAnyToString{} + + case **string: + // This is to fix **string scanning. It seems wrong to special case **string, but it's not clear what a better + // solution would be. + // + // https://github.com/jackc/pgx/issues/1470 -- **string + // https://github.com/jackc/pgx/issues/1691 -- ** anything else + + if wrapperPlan, nextDst, ok := TryPointerPointerScanPlan(target); ok { + if nextPlan := m.planScan(oid, format, nextDst, 0); nextPlan != nil { + if _, failed := nextPlan.(*scanPlanFail); !failed { + wrapperPlan.SetNext(nextPlan) + return wrapperPlan + } + } + } + + case *[]byte: + return scanPlanXMLToByteSlice{} + case BytesScanner: + return scanPlanBinaryBytesToBytesScanner{} + + // Cannot rely on sql.Scanner being handled later because scanPlanXMLToXMLUnmarshal will take precedence. + // + // https://github.com/jackc/pgx/issues/1418 + case sql.Scanner: + return &scanPlanSQLScanner{formatCode: format} + } + + return &scanPlanXMLToXMLUnmarshal{ + unmarshal: c.Unmarshal, + } +} + +type scanPlanXMLToByteSlice struct{} + +func (scanPlanXMLToByteSlice) Scan(src []byte, dst any) error { + dstBuf := dst.(*[]byte) + if src == nil { + *dstBuf = nil + return nil + } + + *dstBuf = make([]byte, len(src)) + copy(*dstBuf, src) + return nil +} + +type scanPlanXMLToXMLUnmarshal struct { + unmarshal func(data []byte, v any) error +} + +func (s *scanPlanXMLToXMLUnmarshal) Scan(src []byte, dst any) error { + if src == nil { + dstValue := reflect.ValueOf(dst) + if dstValue.Kind() == reflect.Pointer { + el := dstValue.Elem() + switch el.Kind() { + case reflect.Pointer, reflect.Slice, reflect.Map, reflect.Interface, reflect.Struct: + el.Set(reflect.Zero(el.Type())) + return nil + } + } + + return fmt.Errorf("cannot scan NULL into %T", dst) + } + + elem := reflect.ValueOf(dst).Elem() + elem.Set(reflect.Zero(elem.Type())) + + return s.unmarshal(src, dst) +} + +func (c *XMLCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) { + if src == nil { + return nil, nil + } + + dstBuf := make([]byte, len(src)) + copy(dstBuf, src) + return dstBuf, nil +} + +func (c *XMLCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) { + if src == nil { + return nil, nil + } + + var dst any + err := c.Unmarshal(src, &dst) + return dst, err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go b/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go new file mode 100644 index 0000000..5d5c681 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/batch_results.go @@ -0,0 +1,52 @@ +package pgxpool + +import ( + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +type errBatchResults struct { + err error +} + +func (br errBatchResults) Exec() (pgconn.CommandTag, error) { + return pgconn.CommandTag{}, br.err +} + +func (br errBatchResults) Query() (pgx.Rows, error) { + return errRows{err: br.err}, br.err +} + +func (br errBatchResults) QueryRow() pgx.Row { + return errRow{err: br.err} +} + +func (br errBatchResults) Close() error { + return br.err +} + +type poolBatchResults struct { + br pgx.BatchResults + c *Conn +} + +func (br *poolBatchResults) Exec() (pgconn.CommandTag, error) { + return br.br.Exec() +} + +func (br *poolBatchResults) Query() (pgx.Rows, error) { + return br.br.Query() +} + +func (br *poolBatchResults) QueryRow() pgx.Row { + return br.br.QueryRow() +} + +func (br *poolBatchResults) Close() error { + err := br.br.Close() + if br.c != nil { + br.c.Release() + br.c = nil + } + return err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/conn.go b/vendor/github.com/jackc/pgx/v5/pgxpool/conn.go new file mode 100644 index 0000000..b4f9060 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/conn.go @@ -0,0 +1,133 @@ +package pgxpool + +import ( + "context" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/puddle/v2" +) + +// Conn is an acquired *pgx.Conn from a Pool. +type Conn struct { + res *puddle.Resource[*connResource] + p *Pool +} + +// Release returns c to the pool it was acquired from. Once Release has been called, other methods must not be called. +// However, it is safe to call Release multiple times. Subsequent calls after the first will be ignored. +func (c *Conn) Release() { + if c.res == nil { + return + } + + conn := c.Conn() + res := c.res + c.res = nil + + if c.p.releaseTracer != nil { + c.p.releaseTracer.TraceRelease(c.p, TraceReleaseData{Conn: conn}) + } + + if conn.IsClosed() || conn.PgConn().IsBusy() || conn.PgConn().TxStatus() != 'I' { + res.Destroy() + // Signal to the health check to run since we just destroyed a connections + // and we might be below minConns now + c.p.triggerHealthCheck() + return + } + + // If the pool is consistently being used, we might never get to check the + // lifetime of a connection since we only check idle connections in checkConnsHealth + // so we also check the lifetime here and force a health check + if c.p.isExpired(res) { + c.p.lifetimeDestroyCount.Add(1) + res.Destroy() + // Signal to the health check to run since we just destroyed a connections + // and we might be below minConns now + c.p.triggerHealthCheck() + return + } + + if c.p.afterRelease == nil { + res.Release() + return + } + + go func() { + if c.p.afterRelease(conn) { + res.Release() + } else { + res.Destroy() + // Signal to the health check to run since we just destroyed a connections + // and we might be below minConns now + c.p.triggerHealthCheck() + } + }() +} + +// Hijack assumes ownership of the connection from the pool. Caller is responsible for closing the connection. Hijack +// will panic if called on an already released or hijacked connection. +func (c *Conn) Hijack() *pgx.Conn { + if c.res == nil { + panic("cannot hijack already released or hijacked connection") + } + + conn := c.Conn() + res := c.res + c.res = nil + + res.Hijack() + + return conn +} + +func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { + return c.Conn().Exec(ctx, sql, arguments...) +} + +func (c *Conn) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { + return c.Conn().Query(ctx, sql, args...) +} + +func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { + return c.Conn().QueryRow(ctx, sql, args...) +} + +func (c *Conn) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { + return c.Conn().SendBatch(ctx, b) +} + +func (c *Conn) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { + return c.Conn().CopyFrom(ctx, tableName, columnNames, rowSrc) +} + +// Begin starts a transaction block from the *Conn without explicitly setting a transaction mode (see BeginTx with TxOptions if transaction mode is required). +func (c *Conn) Begin(ctx context.Context) (pgx.Tx, error) { + return c.Conn().Begin(ctx) +} + +// BeginTx starts a transaction block from the *Conn with txOptions determining the transaction mode. +func (c *Conn) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) { + return c.Conn().BeginTx(ctx, txOptions) +} + +func (c *Conn) Ping(ctx context.Context) error { + return c.Conn().Ping(ctx) +} + +func (c *Conn) Conn() *pgx.Conn { + return c.connResource().conn +} + +func (c *Conn) connResource() *connResource { + return c.res.Value() +} + +func (c *Conn) getPoolRow(r pgx.Row) *poolRow { + return c.connResource().getPoolRow(c, r) +} + +func (c *Conn) getPoolRows(r pgx.Rows) *poolRows { + return c.connResource().getPoolRows(c, r) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/doc.go b/vendor/github.com/jackc/pgx/v5/pgxpool/doc.go new file mode 100644 index 0000000..099443b --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/doc.go @@ -0,0 +1,27 @@ +// Package pgxpool is a concurrency-safe connection pool for pgx. +/* +pgxpool implements a nearly identical interface to pgx connections. + +Creating a Pool + +The primary way of creating a pool is with [pgxpool.New]: + + pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL")) + +The database connection string can be in URL or keyword/value format. PostgreSQL settings, pgx settings, and pool settings can be +specified here. In addition, a config struct can be created by [ParseConfig]. + + config, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL")) + if err != nil { + // ... + } + config.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error { + // do something with every new connection + } + + pool, err := pgxpool.NewWithConfig(context.Background(), config) + +A pool returns without waiting for any connections to be established. Acquire a connection immediately after creating +the pool to check if a connection can successfully be established. +*/ +package pgxpool diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go new file mode 100644 index 0000000..5c740b1 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/pool.go @@ -0,0 +1,840 @@ +package pgxpool + +import ( + "context" + "errors" + "math/rand/v2" + "runtime" + "strconv" + "sync" + "sync/atomic" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/puddle/v2" +) + +var ( + defaultMaxConns = int32(4) + defaultMinConns = int32(0) + defaultMinIdleConns = int32(0) + defaultMaxConnLifetime = time.Hour + defaultMaxConnIdleTime = time.Minute * 30 + defaultHealthCheckPeriod = time.Minute +) + +type connResource struct { + conn *pgx.Conn + conns []Conn + poolRows []poolRow + poolRowss []poolRows + maxAgeTime time.Time +} + +func (cr *connResource) getConn(p *Pool, res *puddle.Resource[*connResource]) *Conn { + if len(cr.conns) == 0 { + cr.conns = make([]Conn, 128) + } + + c := &cr.conns[len(cr.conns)-1] + cr.conns = cr.conns[0 : len(cr.conns)-1] + + c.res = res + c.p = p + + return c +} + +func (cr *connResource) getPoolRow(c *Conn, r pgx.Row) *poolRow { + if len(cr.poolRows) == 0 { + cr.poolRows = make([]poolRow, 128) + } + + pr := &cr.poolRows[len(cr.poolRows)-1] + cr.poolRows = cr.poolRows[0 : len(cr.poolRows)-1] + + pr.c = c + pr.r = r + + return pr +} + +func (cr *connResource) getPoolRows(c *Conn, r pgx.Rows) *poolRows { + if len(cr.poolRowss) == 0 { + cr.poolRowss = make([]poolRows, 128) + } + + pr := &cr.poolRowss[len(cr.poolRowss)-1] + cr.poolRowss = cr.poolRowss[0 : len(cr.poolRowss)-1] + + pr.c = c + pr.r = r + + return pr +} + +// Pool allows for connection reuse. +type Pool struct { + newConnsCount atomic.Int64 + lifetimeDestroyCount atomic.Int64 + idleDestroyCount atomic.Int64 + + p *puddle.Pool[*connResource] + config *Config + beforeConnect func(context.Context, *pgx.ConnConfig) error + afterConnect func(context.Context, *pgx.Conn) error + prepareConn func(context.Context, *pgx.Conn) (bool, error) + afterRelease func(*pgx.Conn) bool + beforeClose func(*pgx.Conn) + shouldPing func(context.Context, ShouldPingParams) bool + minConns int32 + minIdleConns int32 + maxConns int32 + maxConnLifetime time.Duration + maxConnLifetimeJitter time.Duration + maxConnIdleTime time.Duration + healthCheckPeriod time.Duration + pingTimeout time.Duration + + healthCheckMu sync.Mutex + healthCheckTimer *time.Timer + + healthCheckChan chan struct{} + + acquireTracer AcquireTracer + releaseTracer ReleaseTracer + + closeOnce sync.Once + closeChan chan struct{} +} + +// ShouldPingParams are the parameters passed to ShouldPing. +type ShouldPingParams struct { + Conn *pgx.Conn + IdleDuration time.Duration +} + +// Config is the configuration struct for creating a pool. It must be created by [ParseConfig] and then it can be +// modified. +type Config struct { + ConnConfig *pgx.ConnConfig + + // BeforeConnect is called before a new connection is made. It is passed a copy of the underlying [pgx.ConnConfig] and + // will not impact any existing open connections. + BeforeConnect func(context.Context, *pgx.ConnConfig) error + + // AfterConnect is called after a connection is established, but before it is added to the pool. + AfterConnect func(context.Context, *pgx.Conn) error + + // BeforeAcquire is called before a connection is acquired from the pool. It must return true to allow the + // acquisition or false to indicate that the connection should be destroyed and a different connection should be + // acquired. + // + // Deprecated: Use PrepareConn instead. If both PrepareConn and BeforeAcquire are set, PrepareConn will take + // precedence, ignoring BeforeAcquire. + BeforeAcquire func(context.Context, *pgx.Conn) bool + + // PrepareConn is called before a connection is acquired from the pool. If this function returns true, the connection + // is considered valid, otherwise the connection is destroyed. If the function returns a non-nil error, the instigating + // query will fail with the returned error. + // + // Specifically, this means that: + // + // - If it returns true and a nil error, the query proceeds as normal. + // - If it returns true and an error, the connection will be returned to the pool, and the instigating query will fail with the returned error. + // - If it returns false, and an error, the connection will be destroyed, and the query will fail with the returned error. + // - If it returns false and a nil error, the connection will be destroyed, and the instigating query will be retried on a new connection. + PrepareConn func(context.Context, *pgx.Conn) (bool, error) + + // AfterRelease is called after a connection is released, but before it is returned to the pool. It must return true to + // return the connection to the pool or false to destroy the connection. + AfterRelease func(*pgx.Conn) bool + + // BeforeClose is called right before a connection is closed and removed from the pool. + BeforeClose func(*pgx.Conn) + + // ShouldPing is called after a connection is acquired from the pool. If it returns true, the connection is pinged to check for liveness. + // If this func is not set, the default behavior is to ping connections that have been idle for at least 1 second. + ShouldPing func(context.Context, ShouldPingParams) bool + + // MaxConnLifetime is the duration since creation after which a connection will be automatically closed. + MaxConnLifetime time.Duration + + // MaxConnLifetimeJitter is the duration after MaxConnLifetime to randomly decide to close a connection. + // This helps prevent all connections from being closed at the exact same time, starving the pool. + MaxConnLifetimeJitter time.Duration + + // MaxConnIdleTime is the duration after which an idle connection will be automatically closed by the health check. + MaxConnIdleTime time.Duration + + // PingTimeout is the maximum amount of time to wait for a connection to pong before considering it as unhealthy and + // destroying it. If zero, the default is no timeout. + PingTimeout time.Duration + + // MaxConns is the maximum size of the pool. The default is the greater of 4 or runtime.NumCPU(). + MaxConns int32 + + // MinConns is the minimum size of the pool. After connection closes, the pool might dip below MinConns. A low + // number of MinConns might mean the pool is empty after MaxConnLifetime until the health check has a chance + // to create new connections. + MinConns int32 + + // MinIdleConns is the minimum number of idle connections in the pool. You can increase this to ensure that + // there are always idle connections available. This can help reduce tail latencies during request processing, + // as you can avoid the latency of establishing a new connection while handling requests. It is superior + // to MinConns for this purpose. + // Similar to MinConns, the pool might temporarily dip below MinIdleConns after connection closes. + MinIdleConns int32 + + // HealthCheckPeriod is the duration between checks of the health of idle connections. + HealthCheckPeriod time.Duration + + createdByParseConfig bool // Used to enforce created by ParseConfig rule. +} + +// Copy returns a deep copy of the config that is safe to use and modify. +// The only exception is the tls.Config: +// according to the tls.Config docs it must not be modified after creation. +func (c *Config) Copy() *Config { + newConfig := new(Config) + *newConfig = *c + newConfig.ConnConfig = c.ConnConfig.Copy() + return newConfig +} + +// ConnString returns the connection string as parsed by pgxpool.ParseConfig into pgxpool.Config. +func (c *Config) ConnString() string { return c.ConnConfig.ConnString() } + +// New creates a new Pool. See [ParseConfig] for information on connString format. +func New(ctx context.Context, connString string) (*Pool, error) { + config, err := ParseConfig(connString) + if err != nil { + return nil, err + } + + return NewWithConfig(ctx, config) +} + +// NewWithConfig creates a new [Pool]. config must have been created by [ParseConfig]. +func NewWithConfig(ctx context.Context, config *Config) (*Pool, error) { + // Default values are set in ParseConfig. Enforce initial creation by ParseConfig rather than setting defaults from + // zero values. + if !config.createdByParseConfig { + panic("config must be created by ParseConfig") + } + + prepareConn := config.PrepareConn + if prepareConn == nil && config.BeforeAcquire != nil { + prepareConn = func(ctx context.Context, conn *pgx.Conn) (bool, error) { + return config.BeforeAcquire(ctx, conn), nil + } + } + + p := &Pool{ + config: config, + beforeConnect: config.BeforeConnect, + afterConnect: config.AfterConnect, + prepareConn: prepareConn, + afterRelease: config.AfterRelease, + beforeClose: config.BeforeClose, + minConns: config.MinConns, + minIdleConns: config.MinIdleConns, + maxConns: config.MaxConns, + maxConnLifetime: config.MaxConnLifetime, + maxConnLifetimeJitter: config.MaxConnLifetimeJitter, + maxConnIdleTime: config.MaxConnIdleTime, + pingTimeout: config.PingTimeout, + healthCheckPeriod: config.HealthCheckPeriod, + healthCheckChan: make(chan struct{}, 1), + closeChan: make(chan struct{}), + } + + if t, ok := config.ConnConfig.Tracer.(AcquireTracer); ok { + p.acquireTracer = t + } + + if t, ok := config.ConnConfig.Tracer.(ReleaseTracer); ok { + p.releaseTracer = t + } + + if config.ShouldPing != nil { + p.shouldPing = config.ShouldPing + } else { + p.shouldPing = func(ctx context.Context, params ShouldPingParams) bool { + return params.IdleDuration > time.Second + } + } + + var err error + p.p, err = puddle.NewPool( + &puddle.Config[*connResource]{ + Constructor: func(ctx context.Context) (*connResource, error) { + p.newConnsCount.Add(1) + connConfig := p.config.ConnConfig.Copy() + + // Connection will continue in background even if Acquire is canceled. Ensure that a connect won't hang forever. + if connConfig.ConnectTimeout <= 0 { + connConfig.ConnectTimeout = 2 * time.Minute + } + + if p.beforeConnect != nil { + if err := p.beforeConnect(ctx, connConfig); err != nil { + return nil, err + } + } + + conn, err := pgx.ConnectConfig(ctx, connConfig) + if err != nil { + return nil, err + } + + if p.afterConnect != nil { + err = p.afterConnect(ctx, conn) + if err != nil { + conn.Close(ctx) + return nil, err + } + } + + jitterSecs := rand.Float64() * config.MaxConnLifetimeJitter.Seconds() + maxAgeTime := time.Now().Add(config.MaxConnLifetime).Add(time.Duration(jitterSecs) * time.Second) + + cr := &connResource{ + conn: conn, + conns: make([]Conn, 64), + poolRows: make([]poolRow, 64), + poolRowss: make([]poolRows, 64), + maxAgeTime: maxAgeTime, + } + + return cr, nil + }, + Destructor: func(value *connResource) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + conn := value.conn + if p.beforeClose != nil { + p.beforeClose(conn) + } + conn.Close(ctx) + select { + case <-conn.PgConn().CleanupDone(): + case <-ctx.Done(): + } + cancel() + }, + MaxSize: config.MaxConns, + }, + ) + if err != nil { + return nil, err + } + + go func() { + targetIdleResources := max(int(p.minConns), int(p.minIdleConns)) + p.createIdleResources(ctx, targetIdleResources) + p.backgroundHealthCheck() + }() + + return p, nil +} + +// ParseConfig builds a Config from connString. It parses connString with the same behavior as [pgx.ParseConfig] with the +// addition of the following variables: +// +// - pool_max_conns: integer greater than 0 (default 4) +// - pool_min_conns: integer 0 or greater (default 0) +// - pool_max_conn_lifetime: duration string (default 1 hour) +// - pool_max_conn_idle_time: duration string (default 30 minutes) +// - pool_health_check_period: duration string (default 1 minute) +// - pool_max_conn_lifetime_jitter: duration string (default 0) +// +// See Config for definitions of these arguments. +// +// # Example Keyword/Value +// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-ca pool_max_conns=10 pool_max_conn_lifetime=1h30m +// +// # Example URL +// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca&pool_max_conns=10&pool_max_conn_lifetime=1h30m +func ParseConfig(connString string) (*Config, error) { + connConfig, err := pgx.ParseConfig(connString) + if err != nil { + return nil, err + } + + config := &Config{ + ConnConfig: connConfig, + createdByParseConfig: true, + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conns"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_max_conns") + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conns", err) + } + if n < 1 { + return nil, pgconn.NewParseConfigError(connString, "pool_max_conns too small", err) + } + config.MaxConns = int32(n) + } else { + config.MaxConns = defaultMaxConns + if numCPU := int32(runtime.NumCPU()); numCPU > config.MaxConns { + config.MaxConns = numCPU + } + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_min_conns"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_min_conns") + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_min_conns", err) + } + config.MinConns = int32(n) + } else { + config.MinConns = defaultMinConns + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_min_idle_conns"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_min_idle_conns") + n, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_min_idle_conns", err) + } + config.MinIdleConns = int32(n) + } else { + config.MinIdleConns = defaultMinIdleConns + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_lifetime"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_max_conn_lifetime") + d, err := time.ParseDuration(s) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conn_lifetime", err) + } + config.MaxConnLifetime = d + } else { + config.MaxConnLifetime = defaultMaxConnLifetime + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_idle_time"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_max_conn_idle_time") + d, err := time.ParseDuration(s) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conn_idle_time", err) + } + config.MaxConnIdleTime = d + } else { + config.MaxConnIdleTime = defaultMaxConnIdleTime + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_health_check_period"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_health_check_period") + d, err := time.ParseDuration(s) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_health_check_period", err) + } + config.HealthCheckPeriod = d + } else { + config.HealthCheckPeriod = defaultHealthCheckPeriod + } + + if s, ok := config.ConnConfig.Config.RuntimeParams["pool_max_conn_lifetime_jitter"]; ok { + delete(connConfig.Config.RuntimeParams, "pool_max_conn_lifetime_jitter") + d, err := time.ParseDuration(s) + if err != nil { + return nil, pgconn.NewParseConfigError(connString, "cannot parse pool_max_conn_lifetime_jitter", err) + } + config.MaxConnLifetimeJitter = d + } + + return config, nil +} + +// Close closes all connections in the pool and rejects future [Pool.Acquire] calls. Blocks until all connections are returned +// to pool and closed. +func (p *Pool) Close() { + p.closeOnce.Do(func() { + close(p.closeChan) + p.p.Close() + }) +} + +func (p *Pool) isExpired(res *puddle.Resource[*connResource]) bool { + return time.Now().After(res.Value().maxAgeTime) +} + +func (p *Pool) triggerHealthCheck() { + const healthCheckDelay = 500 * time.Millisecond + + p.healthCheckMu.Lock() + defer p.healthCheckMu.Unlock() + + if p.healthCheckTimer == nil { + // Destroy is asynchronous so we give it time to actually remove itself from + // the pool otherwise we might try to check the pool size too soon + p.healthCheckTimer = time.AfterFunc(healthCheckDelay, func() { + select { + case <-p.closeChan: + case p.healthCheckChan <- struct{}{}: + default: + } + }) + return + } + + p.healthCheckTimer.Reset(healthCheckDelay) +} + +func (p *Pool) backgroundHealthCheck() { + ticker := time.NewTicker(p.healthCheckPeriod) + defer ticker.Stop() + for { + select { + case <-p.closeChan: + return + case <-p.healthCheckChan: + p.checkHealth() + case <-ticker.C: + p.checkHealth() + } + } +} + +func (p *Pool) checkHealth() { + for { + // If checkMinConns failed we don't destroy any connections since we couldn't + // even get to minConns + if err := p.checkMinConns(); err != nil { + // Should we log this error somewhere? + break + } + if !p.checkConnsHealth() { + // Since we didn't destroy any connections we can stop looping + break + } + // Technically Destroy is asynchronous but 500ms should be enough for it to + // remove it from the underlying pool + select { + case <-p.closeChan: + return + case <-time.After(500 * time.Millisecond): + } + } +} + +// checkConnsHealth will check all idle connections, destroy a connection if +// it's idle or too old, and returns true if any were destroyed +func (p *Pool) checkConnsHealth() bool { + var destroyed bool + totalConns := p.Stat().TotalConns() + resources := p.p.AcquireAllIdle() + for _, res := range resources { + switch { + // We're okay going under minConns if the lifetime is up + case p.isExpired(res) && totalConns >= p.minConns: + p.lifetimeDestroyCount.Add(1) + res.Destroy() + destroyed = true + // Since Destroy is async we manually decrement totalConns. + totalConns-- + case res.IdleDuration() > p.maxConnIdleTime && totalConns > p.minConns: + p.idleDestroyCount.Add(1) + res.Destroy() + destroyed = true + // Since Destroy is async we manually decrement totalConns. + totalConns-- + default: + res.ReleaseUnused() + } + } + return destroyed +} + +func (p *Pool) checkMinConns() error { + // TotalConns can include ones that are being destroyed but we should have + // sleep(500ms) around all of the destroys to help prevent that from throwing + // off this check + + // Create the number of connections needed to get to both minConns and minIdleConns + stat := p.Stat() + toCreate := max(p.minConns-stat.TotalConns(), p.minIdleConns-stat.IdleConns()) + if toCreate > 0 { + return p.createIdleResources(context.Background(), int(toCreate)) + } + return nil +} + +func (p *Pool) createIdleResources(parentCtx context.Context, targetResources int) error { + ctx, cancel := context.WithCancel(parentCtx) + defer cancel() + + errs := make(chan error, targetResources) + + for range targetResources { + go func() { + err := p.p.CreateResource(ctx) + // Ignore ErrNotAvailable since it means that the pool has become full since we started creating resource. + if err == puddle.ErrNotAvailable { + err = nil + } + errs <- err + }() + } + + var firstError error + for range targetResources { + err := <-errs + if err != nil && firstError == nil { + cancel() + firstError = err + } + } + + return firstError +} + +// Acquire returns a connection ([Conn]) from the [Pool]. +func (p *Pool) Acquire(ctx context.Context) (c *Conn, err error) { + if p.acquireTracer != nil { + ctx = p.acquireTracer.TraceAcquireStart(ctx, p, TraceAcquireStartData{}) + defer func() { + var conn *pgx.Conn + if c != nil { + conn = c.Conn() + } + p.acquireTracer.TraceAcquireEnd(ctx, p, TraceAcquireEndData{Conn: conn, Err: err}) + }() + } + + // Try to acquire from the connection pool up to maxConns + 1 times, so that + // any that fatal errors would empty the pool and still at least try 1 fresh + // connection. + for range int(p.maxConns) + 1 { + res, err := p.p.Acquire(ctx) + if err != nil { + return nil, err + } + + cr := res.Value() + + // Destroy expired connections before doing any further work (such as + // pinging) on them. This enforces MaxConnLifetime at acquire time so that + // a connection that expired while idle on a busy pool is not handed out. + if p.isExpired(res) { + p.lifetimeDestroyCount.Add(1) + res.Destroy() + continue + } + + shouldPingParams := ShouldPingParams{Conn: cr.conn, IdleDuration: res.IdleDuration()} + if p.shouldPing(ctx, shouldPingParams) { + err := func() error { + pingCtx := ctx + if p.pingTimeout > 0 { + var cancel context.CancelFunc + pingCtx, cancel = context.WithTimeout(ctx, p.pingTimeout) + defer cancel() + } + return cr.conn.Ping(pingCtx) + }() + if err != nil { + res.Destroy() + continue + } + } + + if p.prepareConn != nil { + ok, err := p.prepareConn(ctx, cr.conn) + if !ok { + res.Destroy() + } + if err != nil { + if ok { + res.Release() + } + return nil, err + } + if !ok { + continue + } + } + + return cr.getConn(p, res), nil + } + return nil, errors.New("pgxpool: too many failed attempts acquiring connection; likely bug in PrepareConn, BeforeAcquire, or ShouldPing hook") +} + +// AcquireFunc acquires a [Conn] and calls f with that [Conn]. ctx will only affect the [Pool.Acquire]. It has no effect on the +// call of f. The return value is either an error acquiring the [Conn] or the return value of f. The [Conn] is +// automatically released after the call of f. +func (p *Pool) AcquireFunc(ctx context.Context, f func(*Conn) error) error { + conn, err := p.Acquire(ctx) + if err != nil { + return err + } + defer conn.Release() + + return f(conn) +} + +// AcquireAllIdle atomically acquires all currently idle connections. Its intended use is for health check and +// keep-alive functionality. It does not update pool statistics. +func (p *Pool) AcquireAllIdle(ctx context.Context) []*Conn { + resources := p.p.AcquireAllIdle() + conns := make([]*Conn, 0, len(resources)) + for _, res := range resources { + cr := res.Value() + if p.prepareConn != nil { + ok, err := p.prepareConn(ctx, cr.conn) + if !ok || err != nil { + res.Destroy() + continue + } + } + conns = append(conns, cr.getConn(p, res)) + } + + return conns +} + +// Reset closes all connections, but leaves the pool open. It is intended for use when an error is detected that would +// disrupt all connections (such as a network interruption or a server state change). +// +// It is safe to reset a pool while connections are checked out. Those connections will be closed when they are returned +// to the pool. +func (p *Pool) Reset() { + p.p.Reset() +} + +// Config returns a copy of config that was used to initialize this [Pool]. +func (p *Pool) Config() *Config { return p.config.Copy() } + +// Stat returns a pgxpool.Stat struct with a snapshot of Pool statistics. +func (p *Pool) Stat() *Stat { + return &Stat{ + s: p.p.Stat(), + newConnsCount: p.newConnsCount.Load(), + lifetimeDestroyCount: p.lifetimeDestroyCount.Load(), + idleDestroyCount: p.idleDestroyCount.Load(), + } +} + +// Exec acquires a connection from the [Pool] and executes the given SQL. +// SQL can be either a prepared statement name or an SQL string. +// Arguments should be referenced positionally from the SQL string as $1, $2, etc. +// The acquired connection is returned to the pool when the [Pool.Exec] function returns. +func (p *Pool) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { + c, err := p.Acquire(ctx) + if err != nil { + return pgconn.CommandTag{}, err + } + defer c.Release() + + return c.Exec(ctx, sql, arguments...) +} + +// Query acquires a connection and executes a query that returns [pgx.Rows]. +// Arguments should be referenced positionally from the SQL string as $1, $2, etc. +// See [pgx.Rows] documentation to close the returned [pgx.Rows] and return the acquired connection to the [Pool]. +// +// If there is an error, the returned [pgx.Rows] will be returned in an error state. +// If preferred, ignore the error returned from [Pool.Query] and handle errors using the returned [pgx.Rows]. +// +// For extra control over how the query is executed, the types [pgx.QueryExecMode], [pgx.QueryResultFormats], and +// [pgx.QueryResultFormatsByOID] may be used as the first args to control exactly how the query is executed. This is rarely +// needed. See the documentation for those types for details. +func (p *Pool) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { + c, err := p.Acquire(ctx) + if err != nil { + return errRows{err: err}, err + } + + rows, err := c.Query(ctx, sql, args...) + if err != nil { + c.Release() + return errRows{err: err}, err + } + + return c.getPoolRows(rows), nil +} + +// QueryRow acquires a connection and executes a query that is expected +// to return at most one row ([pgx.Row]). Errors are deferred until [pgx.Row]'s +// Scan method is called. If the query selects no rows, [pgx.Row]'s Scan will +// return [pgx.ErrNoRows]. Otherwise, [pgx.Row]'s Scan scans the first selected row +// and discards the rest. The acquired connection is returned to the [Pool] when +// [pgx.Row]'s Scan method is called. +// +// Arguments should be referenced positionally from the SQL string as $1, $2, etc. +// +// For extra control over how the query is executed, the types [pgx.QueryExecMode], [pgx.QueryResultFormats], and +// [pgx.QueryResultFormatsByOID] may be used as the first args to control exactly how the query is executed. This is rarely +// needed. See the documentation for those types for details. +func (p *Pool) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { + c, err := p.Acquire(ctx) + if err != nil { + return errRow{err: err} + } + + row := c.QueryRow(ctx, sql, args...) + return c.getPoolRow(row) +} + +func (p *Pool) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { + c, err := p.Acquire(ctx) + if err != nil { + return errBatchResults{err: err} + } + + br := c.SendBatch(ctx, b) + return &poolBatchResults{br: br, c: c} +} + +// Begin acquires a connection from the [Pool] and starts a transaction. Unlike [database/sql], the context only affects the begin command. i.e. there is no +// auto-rollback on context cancellation. Begin initiates a transaction block without explicitly setting a transaction mode for the block (see [Pool.BeginTx] with [pgx.TxOptions] if transaction mode is required). +// [*Tx] is returned, which implements the [pgx.Tx] interface. +// [Tx.Commit] or [Tx.Rollback] must be called on the returned transaction to finalize the transaction block. +func (p *Pool) Begin(ctx context.Context) (pgx.Tx, error) { + return p.BeginTx(ctx, pgx.TxOptions{}) +} + +// BeginTx acquires a connection from the [Pool] and starts a transaction with [pgx.TxOptions] determining the transaction mode. +// Unlike [database/sql], the context only affects the begin command. i.e. there is no auto-rollback on context cancellation. +// [*Tx] is returned, which implements the [pgx.Tx] interface. +// [Tx.Commit] or [Tx.Rollback] must be called on the returned transaction to finalize the transaction block. +func (p *Pool) BeginTx(ctx context.Context, txOptions pgx.TxOptions) (pgx.Tx, error) { + c, err := p.Acquire(ctx) + if err != nil { + return nil, err + } + + t, err := c.BeginTx(ctx, txOptions) + if err != nil { + c.Release() + return nil, err + } + + return &Tx{t: t, c: c}, nil +} + +func (p *Pool) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { + c, err := p.Acquire(ctx) + if err != nil { + return 0, err + } + defer c.Release() + + return c.Conn().CopyFrom(ctx, tableName, columnNames, rowSrc) +} + +// Ping acquires a connection from the [Pool] and executes an empty sql statement against it. +// If the sql returns without error, the database [Pool.Ping] is considered successful, otherwise, the error is returned. +func (p *Pool) Ping(ctx context.Context) error { + c, err := p.Acquire(ctx) + if err != nil { + return err + } + defer c.Release() + return c.Ping(ctx) +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go new file mode 100644 index 0000000..f834b7e --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/rows.go @@ -0,0 +1,116 @@ +package pgxpool + +import ( + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +type errRows struct { + err error +} + +func (errRows) Close() {} +func (e errRows) Err() error { return e.err } +func (errRows) CommandTag() pgconn.CommandTag { return pgconn.CommandTag{} } +func (errRows) FieldDescriptions() []pgconn.FieldDescription { return nil } +func (errRows) Next() bool { return false } +func (e errRows) Scan(dest ...any) error { return e.err } +func (e errRows) Values() ([]any, error) { return nil, e.err } +func (e errRows) RawValues() [][]byte { return nil } +func (e errRows) Conn() *pgx.Conn { return nil } + +type errRow struct { + err error +} + +func (e errRow) Scan(dest ...any) error { return e.err } + +type poolRows struct { + r pgx.Rows + c *Conn + err error +} + +func (rows *poolRows) Close() { + rows.r.Close() + if rows.c != nil { + rows.c.Release() + rows.c = nil + } +} + +func (rows *poolRows) Err() error { + if rows.err != nil { + return rows.err + } + return rows.r.Err() +} + +func (rows *poolRows) CommandTag() pgconn.CommandTag { + return rows.r.CommandTag() +} + +func (rows *poolRows) FieldDescriptions() []pgconn.FieldDescription { + return rows.r.FieldDescriptions() +} + +func (rows *poolRows) Next() bool { + if rows.err != nil { + return false + } + + n := rows.r.Next() + if !n { + rows.Close() + } + return n +} + +func (rows *poolRows) Scan(dest ...any) error { + err := rows.r.Scan(dest...) + if err != nil { + rows.Close() + } + return err +} + +func (rows *poolRows) Values() ([]any, error) { + values, err := rows.r.Values() + if err != nil { + rows.Close() + } + return values, err +} + +func (rows *poolRows) RawValues() [][]byte { + return rows.r.RawValues() +} + +func (rows *poolRows) Conn() *pgx.Conn { + return rows.r.Conn() +} + +type poolRow struct { + r pgx.Row + c *Conn + err error +} + +func (row *poolRow) Scan(dest ...any) error { + if row.err != nil { + return row.err + } + + panicked := true + defer func() { + if panicked && row.c != nil { + row.c.Release() + } + }() + err := row.r.Scan(dest...) + panicked = false + if row.c != nil { + row.c.Release() + } + return err +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/stat.go b/vendor/github.com/jackc/pgx/v5/pgxpool/stat.go new file mode 100644 index 0000000..e02b6ac --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/stat.go @@ -0,0 +1,91 @@ +package pgxpool + +import ( + "time" + + "github.com/jackc/puddle/v2" +) + +// Stat is a snapshot of Pool statistics. +type Stat struct { + s *puddle.Stat + newConnsCount int64 + lifetimeDestroyCount int64 + idleDestroyCount int64 +} + +// AcquireCount returns the cumulative count of successful acquires from the pool. +func (s *Stat) AcquireCount() int64 { + return s.s.AcquireCount() +} + +// AcquireDuration returns the total duration of all successful acquires from +// the pool. +func (s *Stat) AcquireDuration() time.Duration { + return s.s.AcquireDuration() +} + +// AcquiredConns returns the number of currently acquired connections in the pool. +func (s *Stat) AcquiredConns() int32 { + return s.s.AcquiredResources() +} + +// CanceledAcquireCount returns the cumulative count of acquires from the pool +// that were canceled by a context. +func (s *Stat) CanceledAcquireCount() int64 { + return s.s.CanceledAcquireCount() +} + +// ConstructingConns returns the number of conns with construction in progress in +// the pool. +func (s *Stat) ConstructingConns() int32 { + return s.s.ConstructingResources() +} + +// EmptyAcquireCount returns the cumulative count of successful acquires from the pool +// that waited for a resource to be released or constructed because the pool was +// empty. +func (s *Stat) EmptyAcquireCount() int64 { + return s.s.EmptyAcquireCount() +} + +// IdleConns returns the number of currently idle conns in the pool. +func (s *Stat) IdleConns() int32 { + return s.s.IdleResources() +} + +// MaxConns returns the maximum size of the pool. +func (s *Stat) MaxConns() int32 { + return s.s.MaxResources() +} + +// TotalConns returns the total number of resources currently in the pool. +// The value is the sum of ConstructingConns, AcquiredConns, and +// IdleConns. +func (s *Stat) TotalConns() int32 { + return s.s.TotalResources() +} + +// NewConnsCount returns the cumulative count of new connections opened. +func (s *Stat) NewConnsCount() int64 { + return s.newConnsCount +} + +// MaxLifetimeDestroyCount returns the cumulative count of connections destroyed +// because they exceeded MaxConnLifetime. +func (s *Stat) MaxLifetimeDestroyCount() int64 { + return s.lifetimeDestroyCount +} + +// MaxIdleDestroyCount returns the cumulative count of connections destroyed because +// they exceeded MaxConnIdleTime. +func (s *Stat) MaxIdleDestroyCount() int64 { + return s.idleDestroyCount +} + +// EmptyAcquireWaitTime returns the cumulative time waited for successful acquires +// from the pool for a resource to be released or constructed because the pool was +// empty. +func (s *Stat) EmptyAcquireWaitTime() time.Duration { + return s.s.EmptyAcquireWaitTime() +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go b/vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go new file mode 100644 index 0000000..78b9d15 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/tracer.go @@ -0,0 +1,33 @@ +package pgxpool + +import ( + "context" + + "github.com/jackc/pgx/v5" +) + +// AcquireTracer traces Acquire. +type AcquireTracer interface { + // TraceAcquireStart is called at the beginning of Acquire. + // The returned context is used for the rest of the call and will be passed to the TraceAcquireEnd. + TraceAcquireStart(ctx context.Context, pool *Pool, data TraceAcquireStartData) context.Context + // TraceAcquireEnd is called when a connection has been acquired. + TraceAcquireEnd(ctx context.Context, pool *Pool, data TraceAcquireEndData) +} + +type TraceAcquireStartData struct{} + +type TraceAcquireEndData struct { + Conn *pgx.Conn + Err error +} + +// ReleaseTracer traces Release. +type ReleaseTracer interface { + // TraceRelease is called at the beginning of Release. + TraceRelease(pool *Pool, data TraceReleaseData) +} + +type TraceReleaseData struct { + Conn *pgx.Conn +} diff --git a/vendor/github.com/jackc/pgx/v5/pgxpool/tx.go b/vendor/github.com/jackc/pgx/v5/pgxpool/tx.go new file mode 100644 index 0000000..b49e7f4 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/pgxpool/tx.go @@ -0,0 +1,83 @@ +package pgxpool + +import ( + "context" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +// Tx represents a database transaction acquired from a Pool. +type Tx struct { + t pgx.Tx + c *Conn +} + +// Begin starts a pseudo nested transaction implemented with a savepoint. +func (tx *Tx) Begin(ctx context.Context) (pgx.Tx, error) { + return tx.t.Begin(ctx) +} + +// Commit commits the transaction and returns the associated connection back to the Pool. Commit will return an error +// where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is otherwise safe to call multiple times. If +// the commit fails with a rollback status (e.g. the transaction was already in a broken state) then ErrTxCommitRollback +// will be returned. +func (tx *Tx) Commit(ctx context.Context) error { + err := tx.t.Commit(ctx) + if tx.c != nil { + tx.c.Release() + tx.c = nil + } + return err +} + +// Rollback rolls back the transaction and returns the associated connection back to the Pool. Rollback will return +// where an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is otherwise safe to call +// multiple times. Hence, defer tx.Rollback() is safe even if tx.Commit() will be called first in a non-error condition. +func (tx *Tx) Rollback(ctx context.Context) error { + err := tx.t.Rollback(ctx) + if tx.c != nil { + tx.c.Release() + tx.c = nil + } + return err +} + +func (tx *Tx) CopyFrom(ctx context.Context, tableName pgx.Identifier, columnNames []string, rowSrc pgx.CopyFromSource) (int64, error) { + return tx.t.CopyFrom(ctx, tableName, columnNames, rowSrc) +} + +func (tx *Tx) SendBatch(ctx context.Context, b *pgx.Batch) pgx.BatchResults { + return tx.t.SendBatch(ctx, b) +} + +func (tx *Tx) LargeObjects() pgx.LargeObjects { + return tx.t.LargeObjects() +} + +// Prepare creates a prepared statement with name and sql. If the name is empty, +// an anonymous prepared statement will be used. sql can contain placeholders +// for bound parameters. These placeholders are referenced positionally as $1, $2, etc. +// +// Prepare is idempotent; i.e. it is safe to call Prepare multiple times with the same +// name and sql arguments. This allows a code path to Prepare and Query/Exec without +// needing to first check whether the statement has already been prepared. +func (tx *Tx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) { + return tx.t.Prepare(ctx, name, sql) +} + +func (tx *Tx) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) { + return tx.t.Exec(ctx, sql, arguments...) +} + +func (tx *Tx) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) { + return tx.t.Query(ctx, sql, args...) +} + +func (tx *Tx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row { + return tx.t.QueryRow(ctx, sql, args...) +} + +func (tx *Tx) Conn() *pgx.Conn { + return tx.t.Conn() +} diff --git a/vendor/github.com/jackc/pgx/v5/rows.go b/vendor/github.com/jackc/pgx/v5/rows.go new file mode 100644 index 0000000..4e5cf95 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/rows.go @@ -0,0 +1,871 @@ +package pgx + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" +) + +// Rows is the result set returned from [Conn.Query]. Rows must be closed before +// the [Conn] can be used again. Rows are closed by explicitly calling [Rows.Close], +// calling [Rows.Next] until it returns false, or when a fatal error occurs. +// +// Once a Rows is closed the only methods that may be called are [Rows.Close], [Rows.Err], +// and [Rows.CommandTag]. +// +// Rows is an interface instead of a struct to allow tests to mock Query. However, +// adding a method to an interface is technically a breaking change. Because of this +// the Rows interface is partially excluded from semantic version requirements. +// Methods will not be removed or changed, but new methods may be added. +type Rows interface { + // Close closes the rows, making the connection ready for use again. It is safe + // to call Close after rows is already closed. + Close() + + // Err returns any error that occurred while executing a query or reading its results. Err must be called after the + // Rows is closed (either by calling Close or by Next returning false) to check if the query was successful. If it is + // called before the Rows is closed it may return nil even if the query failed on the server. + Err() error + + // CommandTag returns the command tag from this query. It is only available after Rows is closed. + CommandTag() pgconn.CommandTag + + // FieldDescriptions returns the field descriptions of the columns. It may return nil. In particular this can occur + // when there was an error executing the query. + FieldDescriptions() []pgconn.FieldDescription + + // Next prepares the next row for reading. It returns true if there is another row and false if no more rows are + // available or a fatal error has occurred. It automatically closes rows upon returning false (whether due to all rows + // having been read or due to an error). + // + // Callers should check rows.Err() after rows.Next() returns false to detect whether result-set reading ended + // prematurely due to an error. See [Conn.Query] for details. + // + // For simpler error handling, consider using the higher-level pgx v5 [CollectRows()] and [ForEachRow()] helpers instead. + Next() bool + + // Scan reads the values from the current row into dest values positionally. dest can include pointers to core types, + // values implementing the Scanner interface, and nil. nil will skip the value entirely. It is an error to call Scan + // without first calling Next() and checking that it returned true. Rows is automatically closed upon error. + Scan(dest ...any) error + + // Values returns the decoded row values. As with Scan(), it is an error to + // call Values without first calling Next() and checking that it returned + // true. + Values() ([]any, error) + + // RawValues returns the unparsed bytes of the row values. The returned data is only valid until the next Next + // call or the Rows is closed. + RawValues() [][]byte + + // Conn returns the underlying *Conn on which the query was executed. This may return nil if Rows did not come from a + // *Conn (e.g. if it was created by RowsFromResultReader) + Conn() *Conn +} + +// Row is a convenience wrapper over [Rows] that is returned by [Conn.QueryRow]. +// +// Row is an interface instead of a struct to allow tests to mock QueryRow. However, +// adding a method to an interface is technically a breaking change. Because of this +// the Row interface is partially excluded from semantic version requirements. +// Methods will not be removed or changed, but new methods may be added. +type Row interface { + // Scan works the same as Rows. with the following exceptions. If no + // rows were found it returns ErrNoRows. If multiple rows are returned it + // ignores all but the first. + Scan(dest ...any) error +} + +// RowScanner scans an entire row at a time into the RowScanner. +type RowScanner interface { + // ScanRows scans the row. + ScanRow(rows Rows) error +} + +// connRow implements the Row interface for Conn.QueryRow. +type connRow baseRows + +func (r *connRow) Scan(dest ...any) (err error) { + rows := (*baseRows)(r) + + if rows.Err() != nil { + return rows.Err() + } + + for _, d := range dest { + if _, ok := d.(*pgtype.DriverBytes); ok { + rows.Close() + return fmt.Errorf("cannot scan into *pgtype.DriverBytes from QueryRow") + } + } + + if !rows.Next() { + if rows.Err() == nil { + return ErrNoRows + } + return rows.Err() + } + + rows.Scan(dest...) + rows.Close() + return rows.Err() +} + +// baseRows implements the Rows interface for Conn.Query. +type baseRows struct { + typeMap *pgtype.Map + resultReader *pgconn.ResultReader + + values [][]byte + + commandTag pgconn.CommandTag + err error + closed bool + + scanPlans []pgtype.ScanPlan + scanTypes []reflect.Type + + conn *Conn + multiResultReader *pgconn.MultiResultReader + + queryTracer QueryTracer + batchTracer BatchTracer + ctx context.Context + startTime time.Time + sql string + args []any + rowCount int +} + +func (rows *baseRows) FieldDescriptions() []pgconn.FieldDescription { + return rows.resultReader.FieldDescriptions() +} + +func (rows *baseRows) Close() { + if rows.closed { + return + } + + rows.closed = true + + if rows.resultReader != nil { + var closeErr error + rows.commandTag, closeErr = rows.resultReader.Close() + if rows.err == nil { + rows.err = closeErr + } + } + + if rows.multiResultReader != nil { + closeErr := rows.multiResultReader.Close() + if rows.err == nil { + rows.err = closeErr + } + } + + if rows.err != nil && rows.conn != nil && rows.sql != "" { + if sc := rows.conn.statementCache; sc != nil { + sc.Invalidate(rows.sql) + } + + if sc := rows.conn.descriptionCache; sc != nil { + sc.Invalidate(rows.sql) + } + } + + if rows.batchTracer != nil { + rows.batchTracer.TraceBatchQuery(rows.ctx, rows.conn, TraceBatchQueryData{SQL: rows.sql, Args: rows.args, CommandTag: rows.commandTag, Err: rows.err}) + } else if rows.queryTracer != nil { + rows.queryTracer.TraceQueryEnd(rows.ctx, rows.conn, TraceQueryEndData{rows.commandTag, rows.err}) + } + + // Zero references to other memory allocations. This allows them to be GC'd even when the Rows still referenced. In + // particular, when using pgxpool GC could be delayed as pgxpool.poolRows are allocated in large slices. + // + // https://github.com/jackc/pgx/pull/2269 + rows.values = nil + rows.scanPlans = nil + rows.scanTypes = nil + rows.ctx = nil + rows.sql = "" + rows.args = nil +} + +func (rows *baseRows) CommandTag() pgconn.CommandTag { + return rows.commandTag +} + +func (rows *baseRows) Err() error { + return rows.err +} + +// fatal signals an error occurred after the query was sent to the server. It +// closes the rows automatically. +func (rows *baseRows) fatal(err error) { + if rows.err != nil { + return + } + + rows.err = err + rows.Close() +} + +func (rows *baseRows) Next() bool { + if rows.closed { + return false + } + + if rows.resultReader.NextRow() { + rows.rowCount++ + rows.values = rows.resultReader.Values() + return true + } else { + rows.Close() + return false + } +} + +func (rows *baseRows) Scan(dest ...any) error { + m := rows.typeMap + fieldDescriptions := rows.FieldDescriptions() + values := rows.values + + if len(fieldDescriptions) != len(values) { + err := fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(values)) + rows.fatal(err) + return err + } + + if len(dest) == 1 { + if rc, ok := dest[0].(RowScanner); ok { + err := rc.ScanRow(rows) + if err != nil { + rows.fatal(err) + } + return err + } + } + + if len(fieldDescriptions) != len(dest) { + err := fmt.Errorf("number of field descriptions must equal number of destinations, got %d and %d", len(fieldDescriptions), len(dest)) + rows.fatal(err) + return err + } + + if rows.scanPlans == nil { + rows.scanPlans = make([]pgtype.ScanPlan, len(values)) + rows.scanTypes = make([]reflect.Type, len(values)) + for i := range dest { + rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i]) + rows.scanTypes[i] = reflect.TypeOf(dest[i]) + } + } + + for i, dst := range dest { + if dst == nil { + continue + } + + if rows.scanTypes[i] != reflect.TypeOf(dst) { + rows.scanPlans[i] = m.PlanScan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, dest[i]) + rows.scanTypes[i] = reflect.TypeOf(dest[i]) + } + + err := rows.scanPlans[i].Scan(values[i], dst) + if err != nil { + err = ScanArgError{ColumnIndex: i, FieldName: fieldDescriptions[i].Name, Err: err} + rows.fatal(err) + return err + } + } + + return nil +} + +func (rows *baseRows) Values() ([]any, error) { + if rows.closed { + return nil, errors.New("rows is closed") + } + + values := make([]any, 0, len(rows.FieldDescriptions())) + + for i := range rows.FieldDescriptions() { + buf := rows.values[i] + fd := &rows.FieldDescriptions()[i] + + if buf == nil { + values = append(values, nil) + continue + } + + if dt, ok := rows.typeMap.TypeForOID(fd.DataTypeOID); ok { + value, err := dt.Codec.DecodeValue(rows.typeMap, fd.DataTypeOID, fd.Format, buf) + if err != nil { + rows.fatal(err) + } + values = append(values, value) + } else { + switch fd.Format { + case TextFormatCode: + values = append(values, string(buf)) + case BinaryFormatCode: + newBuf := make([]byte, len(buf)) + copy(newBuf, buf) + values = append(values, newBuf) + default: + rows.fatal(errors.New("unknown format code")) + } + } + + if rows.Err() != nil { + return nil, rows.Err() + } + } + + return values, rows.Err() +} + +func (rows *baseRows) RawValues() [][]byte { + return rows.values +} + +func (rows *baseRows) Conn() *Conn { + return rows.conn +} + +type ScanArgError struct { + ColumnIndex int + FieldName string + Err error +} + +func (e ScanArgError) Error() string { + if e.FieldName == "?column?" { // Don't include the fieldname if it's unknown + return fmt.Sprintf("can't scan into dest[%d]: %v", e.ColumnIndex, e.Err) + } + + return fmt.Sprintf("can't scan into dest[%d] (col: %s): %v", e.ColumnIndex, e.FieldName, e.Err) +} + +func (e ScanArgError) Unwrap() error { + return e.Err +} + +// ScanRow decodes raw row data into dest. It can be used to scan rows read from the lower level [pgconn] interface. +// +// typeMap - OID to Go type mapping. +// fieldDescriptions - OID and format of values +// values - the raw data as returned from the PostgreSQL server +// dest - the destination that values will be decoded into +func ScanRow(typeMap *pgtype.Map, fieldDescriptions []pgconn.FieldDescription, values [][]byte, dest ...any) error { + if len(fieldDescriptions) != len(values) { + return fmt.Errorf("number of field descriptions must equal number of values, got %d and %d", len(fieldDescriptions), len(values)) + } + if len(fieldDescriptions) != len(dest) { + return fmt.Errorf("number of field descriptions must equal number of destinations, got %d and %d", len(fieldDescriptions), len(dest)) + } + + for i, d := range dest { + if d == nil { + continue + } + + err := typeMap.Scan(fieldDescriptions[i].DataTypeOID, fieldDescriptions[i].Format, values[i], d) + if err != nil { + return ScanArgError{ColumnIndex: i, FieldName: fieldDescriptions[i].Name, Err: err} + } + } + + return nil +} + +// RowsFromResultReader returns a [Rows] that will read from values resultReader and decode with typeMap. It can be used +// to read from the lower level [pgconn] interface. +func RowsFromResultReader(typeMap *pgtype.Map, resultReader *pgconn.ResultReader) Rows { + return &baseRows{ + typeMap: typeMap, + resultReader: resultReader, + } +} + +// ForEachRow iterates through rows. For each row it scans into the elements of scans and calls fn. If any row +// fails to scan or fn returns an error the query will be aborted and the error will be returned. Rows will be closed +// when ForEachRow returns. +func ForEachRow(rows Rows, scans []any, fn func() error) (pgconn.CommandTag, error) { + defer rows.Close() + + for rows.Next() { + err := rows.Scan(scans...) + if err != nil { + return pgconn.CommandTag{}, err + } + + err = fn() + if err != nil { + return pgconn.CommandTag{}, err + } + } + + if err := rows.Err(); err != nil { + return pgconn.CommandTag{}, err + } + + return rows.CommandTag(), nil +} + +// CollectableRow is the subset of Rows methods that a RowToFunc is allowed to call. +type CollectableRow interface { + FieldDescriptions() []pgconn.FieldDescription + Scan(dest ...any) error + Values() ([]any, error) + RawValues() [][]byte +} + +// RowToFunc is a function that scans or otherwise converts row to a T. +type RowToFunc[T any] func(row CollectableRow) (T, error) + +// AppendRows iterates through rows, calling fn for each row, and appending the results into a slice of T. +// +// This function closes the rows automatically on return. +func AppendRows[T any, S ~[]T](slice S, rows Rows, fn RowToFunc[T]) (S, error) { + defer rows.Close() + + for rows.Next() { + value, err := fn(rows) + if err != nil { + return nil, err + } + slice = append(slice, value) + } + + if err := rows.Err(); err != nil { + return nil, err + } + + return slice, nil +} + +// CollectRows iterates through rows, calling fn for each row, and collecting the results into a slice of T. +// +// This function closes the rows automatically on return. +func CollectRows[T any](rows Rows, fn RowToFunc[T]) ([]T, error) { + return AppendRows([]T{}, rows, fn) +} + +// CollectOneRow calls fn for the first row in rows and returns the result. If no rows are found returns an error where errors.Is(ErrNoRows) is true. +// CollectOneRow is to [CollectRows] as [Conn.QueryRow] is to [Conn.Query]. +// +// This function closes the rows automatically on return. +func CollectOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) { + defer rows.Close() + + var value T + var err error + + if !rows.Next() { + if err = rows.Err(); err != nil { + return value, err + } + return value, ErrNoRows + } + + value, err = fn(rows) + if err != nil { + return value, err + } + + // The defer rows.Close() won't have executed yet. If the query returned more than one row, rows would still be open. + // rows.Close() must be called before rows.Err() so we explicitly call it here. + rows.Close() + return value, rows.Err() +} + +// CollectExactlyOneRow calls fn for the first row in rows and returns the result. +// - If no rows are found returns an error where errors.Is(ErrNoRows) is true. +// - If more than 1 row is found returns an error where errors.Is(ErrTooManyRows) is true. +// +// This function closes the rows automatically on return. +func CollectExactlyOneRow[T any](rows Rows, fn RowToFunc[T]) (T, error) { + defer rows.Close() + + var ( + err error + value T + ) + + if !rows.Next() { + if err = rows.Err(); err != nil { + return value, err + } + + return value, ErrNoRows + } + + value, err = fn(rows) + if err != nil { + return value, err + } + + if rows.Next() { + var zero T + + return zero, ErrTooManyRows + } + + return value, rows.Err() +} + +// RowTo returns a T scanned from row. +func RowTo[T any](row CollectableRow) (T, error) { + var value T + err := row.Scan(&value) + return value, err +} + +// RowToAddrOf returns the address of a T scanned from row. +func RowToAddrOf[T any](row CollectableRow) (*T, error) { + var value T + err := row.Scan(&value) + return &value, err +} + +// RowToMap returns a map scanned from row. +func RowToMap(row CollectableRow) (map[string]any, error) { + var value map[string]any + err := row.Scan((*mapRowScanner)(&value)) + return value, err +} + +type mapRowScanner map[string]any + +func (rs *mapRowScanner) ScanRow(rows Rows) error { + values, err := rows.Values() + if err != nil { + return err + } + + *rs = make(mapRowScanner, len(values)) + + for i := range values { + (*rs)[rows.FieldDescriptions()[i].Name] = values[i] + } + + return nil +} + +// RowToStructByPos returns a T scanned from row. T must be a struct. T must have the same number of public fields as row +// has fields. The row and T fields will be matched by position. If the "db" struct tag is "-" then the field will be +// ignored. +func RowToStructByPos[T any](row CollectableRow) (T, error) { + var value T + err := (&positionalStructRowScanner{ptrToStruct: &value}).ScanRow(row) + return value, err +} + +// RowToAddrOfStructByPos returns the address of a T scanned from row. T must be a struct. T must have the same number a +// public fields as row has fields. The row and T fields will be matched by position. If the "db" struct tag is "-" then +// the field will be ignored. +func RowToAddrOfStructByPos[T any](row CollectableRow) (*T, error) { + var value T + err := (&positionalStructRowScanner{ptrToStruct: &value}).ScanRow(row) + return &value, err +} + +type positionalStructRowScanner struct { + ptrToStruct any +} + +func (rs *positionalStructRowScanner) ScanRow(rows CollectableRow) error { + typ := reflect.TypeOf(rs.ptrToStruct).Elem() + fields := lookupStructFields(typ) + if len(rows.RawValues()) > len(fields) { + return fmt.Errorf( + "got %d values, but dst struct has only %d fields", + len(rows.RawValues()), + len(fields), + ) + } + scanTargets := setupStructScanTargets(rs.ptrToStruct, fields) + return rows.Scan(scanTargets...) +} + +// Map from reflect.Type -> []structRowField +var positionalStructFieldMap sync.Map + +func lookupStructFields(t reflect.Type) []structRowField { + if cached, ok := positionalStructFieldMap.Load(t); ok { + return cached.([]structRowField) + } + + fieldStack := make([]int, 0, 1) + fields := computeStructFields(t, make([]structRowField, 0, t.NumField()), &fieldStack) + fieldsIface, _ := positionalStructFieldMap.LoadOrStore(t, fields) + return fieldsIface.([]structRowField) +} + +func computeStructFields( + t reflect.Type, + fields []structRowField, + fieldStack *[]int, +) []structRowField { + tail := len(*fieldStack) + *fieldStack = append(*fieldStack, 0) + for i := 0; i < t.NumField(); i++ { + sf := t.Field(i) + (*fieldStack)[tail] = i + // Handle anonymous struct embedding, but do not try to handle embedded pointers. + if sf.Anonymous && sf.Type.Kind() == reflect.Struct { + fields = computeStructFields(sf.Type, fields, fieldStack) + } else if sf.PkgPath == "" { + dbTag, _ := sf.Tag.Lookup(structTagKey) + if dbTag == "-" { + // Field is ignored, skip it. + continue + } + fields = append(fields, structRowField{ + path: append([]int(nil), *fieldStack...), + }) + } + } + *fieldStack = (*fieldStack)[:tail] + return fields +} + +// RowToStructByName returns a T scanned from row. T must be a struct. T must have the same number of named public +// fields as row has fields. The row and T fields will be matched by name. The match is case-insensitive. The database +// column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" then the field will be ignored. +func RowToStructByName[T any](row CollectableRow) (T, error) { + var value T + err := (&namedStructRowScanner{ptrToStruct: &value}).ScanRow(row) + return value, err +} + +// RowToAddrOfStructByName returns the address of a T scanned from row. T must be a struct. T must have the same number +// of named public fields as row has fields. The row and T fields will be matched by name. The match is +// case-insensitive. The database column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" +// then the field will be ignored. +func RowToAddrOfStructByName[T any](row CollectableRow) (*T, error) { + var value T + err := (&namedStructRowScanner{ptrToStruct: &value}).ScanRow(row) + return &value, err +} + +// RowToStructByNameLax returns a T scanned from row. T must be a struct. T must have greater than or equal number of named public +// fields as row has fields. The row and T fields will be matched by name. The match is case-insensitive. The database +// column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" then the field will be ignored. +func RowToStructByNameLax[T any](row CollectableRow) (T, error) { + var value T + err := (&namedStructRowScanner{ptrToStruct: &value, lax: true}).ScanRow(row) + return value, err +} + +// RowToAddrOfStructByNameLax returns the address of a T scanned from row. T must be a struct. T must have greater than or +// equal number of named public fields as row has fields. The row and T fields will be matched by name. The match is +// case-insensitive. The database column name can be overridden with a "db" struct tag. If the "db" struct tag is "-" +// then the field will be ignored. +func RowToAddrOfStructByNameLax[T any](row CollectableRow) (*T, error) { + var value T + err := (&namedStructRowScanner{ptrToStruct: &value, lax: true}).ScanRow(row) + return &value, err +} + +type namedStructRowScanner struct { + ptrToStruct any + lax bool +} + +func (rs *namedStructRowScanner) ScanRow(rows CollectableRow) error { + typ := reflect.TypeOf(rs.ptrToStruct).Elem() + fldDescs := rows.FieldDescriptions() + namedStructFields, err := lookupNamedStructFields(typ, fldDescs) + if err != nil { + return err + } + if !rs.lax && namedStructFields.missingField != "" { + return fmt.Errorf("cannot find field %s in returned row", namedStructFields.missingField) + } + fields := namedStructFields.fields + scanTargets := setupStructScanTargets(rs.ptrToStruct, fields) + return rows.Scan(scanTargets...) +} + +// Map from namedStructFieldMap -> *namedStructFields +var namedStructFieldMap sync.Map + +type namedStructFieldsKey struct { + t reflect.Type + colNames string +} + +type namedStructFields struct { + fields []structRowField + // missingField is the first field from the struct without a corresponding row field. + // This is used to construct the correct error message for non-lax queries. + missingField string +} + +func lookupNamedStructFields( + t reflect.Type, + fldDescs []pgconn.FieldDescription, +) (*namedStructFields, error) { + key := namedStructFieldsKey{ + t: t, + colNames: joinFieldNames(fldDescs), + } + if cached, ok := namedStructFieldMap.Load(key); ok { + return cached.(*namedStructFields), nil + } + + // We could probably do two-levels of caching, where we compute the key -> fields mapping + // for a type only once, cache it by type, then use that to compute the column -> fields + // mapping for a given set of columns. + fieldStack := make([]int, 0, 1) + fields, missingField := computeNamedStructFields( + fldDescs, + t, + make([]structRowField, len(fldDescs)), + &fieldStack, + ) + for i, f := range fields { + if f.path == nil { + return nil, fmt.Errorf( + "struct doesn't have corresponding row field %s", + fldDescs[i].Name, + ) + } + } + + fieldsIface, _ := namedStructFieldMap.LoadOrStore( + key, + &namedStructFields{fields: fields, missingField: missingField}, + ) + return fieldsIface.(*namedStructFields), nil +} + +func joinFieldNames(fldDescs []pgconn.FieldDescription) string { + switch len(fldDescs) { + case 0: + return "" + case 1: + return fldDescs[0].Name + } + + totalSize := len(fldDescs) - 1 // Space for separator bytes. + for _, d := range fldDescs { + totalSize += len(d.Name) + } + var b strings.Builder + b.Grow(totalSize) + b.WriteString(fldDescs[0].Name) + for _, d := range fldDescs[1:] { + b.WriteByte(0) // Join with NUL byte as it's (presumably) not a valid column character. + b.WriteString(d.Name) + } + return b.String() +} + +func computeNamedStructFields( + fldDescs []pgconn.FieldDescription, + t reflect.Type, + fields []structRowField, + fieldStack *[]int, +) ([]structRowField, string) { + var missingField string + tail := len(*fieldStack) + *fieldStack = append(*fieldStack, 0) + for i := 0; i < t.NumField(); i++ { + sf := t.Field(i) + (*fieldStack)[tail] = i + if sf.PkgPath != "" && !sf.Anonymous { + // Field is unexported, skip it. + continue + } + // Handle anonymous struct embedding, but do not try to handle embedded pointers. + if sf.Anonymous && sf.Type.Kind() == reflect.Struct { + var missingSubField string + fields, missingSubField = computeNamedStructFields( + fldDescs, + sf.Type, + fields, + fieldStack, + ) + if missingField == "" { + missingField = missingSubField + } + } else { + dbTag, dbTagPresent := sf.Tag.Lookup(structTagKey) + if dbTagPresent { + dbTag, _, _ = strings.Cut(dbTag, ",") + } + if dbTag == "-" { + // Field is ignored, skip it. + continue + } + colName := dbTag + if !dbTagPresent { + colName = sf.Name + } + fpos := fieldPosByName(fldDescs, colName, !dbTagPresent) + if fpos == -1 { + if missingField == "" { + missingField = colName + } + continue + } + fields[fpos] = structRowField{ + path: append([]int(nil), *fieldStack...), + } + } + } + *fieldStack = (*fieldStack)[:tail] + + return fields, missingField +} + +const structTagKey = "db" + +func fieldPosByName(fldDescs []pgconn.FieldDescription, field string, normalize bool) (i int) { + i = -1 + + if normalize { + field = strings.ReplaceAll(field, "_", "") + } + for i, desc := range fldDescs { + if normalize { + if strings.EqualFold(strings.ReplaceAll(desc.Name, "_", ""), field) { + return i + } + } else { + if desc.Name == field { + return i + } + } + } + return i +} + +// structRowField describes a field of a struct. +// +// TODO: It would be a bit more efficient to track the path using the pointer +// offset within the (outermost) struct and use unsafe.Pointer arithmetic to +// construct references when scanning rows. However, it's not clear it's worth +// using unsafe for this. +type structRowField struct { + path []int +} + +func setupStructScanTargets(receiver any, fields []structRowField) []any { + scanTargets := make([]any, len(fields)) + v := reflect.ValueOf(receiver).Elem() + for i, f := range fields { + scanTargets[i] = v.FieldByIndex(f.path).Addr().Interface() + } + return scanTargets +} diff --git a/vendor/github.com/jackc/pgx/v5/stdlib/sql.go b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go new file mode 100644 index 0000000..576d3c6 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/stdlib/sql.go @@ -0,0 +1,909 @@ +// Package stdlib is the compatibility layer from pgx to database/sql. +// +// A database/sql connection can be established through sql.Open. +// +// db, err := sql.Open("pgx", "postgres://pgx_md5:secret@localhost:5432/pgx_test?sslmode=disable") +// if err != nil { +// return err +// } +// +// Or from a keyword/value string. +// +// db, err := sql.Open("pgx", "user=postgres password=secret host=localhost port=5432 dbname=pgx_test sslmode=disable") +// if err != nil { +// return err +// } +// +// Or from a *pgxpool.Pool. +// +// pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL")) +// if err != nil { +// return err +// } +// +// db := stdlib.OpenDBFromPool(pool) +// +// Or a pgx.ConnConfig can be used to set configuration not accessible via connection string. In this case the +// pgx.ConnConfig must first be registered with the driver. This registration returns a connection string which is used +// with sql.Open. +// +// connConfig, _ := pgx.ParseConfig(os.Getenv("DATABASE_URL")) +// connConfig.Tracer = &tracelog.TraceLog{Logger: myLogger, LogLevel: tracelog.LogLevelInfo} +// connStr := stdlib.RegisterConnConfig(connConfig) +// db, _ := sql.Open("pgx", connStr) +// +// pgx uses standard PostgreSQL positional parameters in queries. e.g. $1, $2. It does not support named parameters. +// +// db.QueryRow("select * from users where id=$1", userID) +// +// (*sql.Conn) Raw() can be used to get a *pgx.Conn from the standard database/sql.DB connection pool. This allows +// operations that use pgx specific functionality. +// +// // Given db is a *sql.DB +// conn, err := db.Conn(context.Background()) +// if err != nil { +// // handle error from acquiring connection from DB pool +// } +// +// err = conn.Raw(func(driverConn any) error { +// conn := driverConn.(*stdlib.Conn).Conn() // conn is a *pgx.Conn +// // Do pgx specific stuff with conn +// conn.CopyFrom(...) +// return nil +// }) +// if err != nil { +// // handle error that occurred while using *pgx.Conn +// } +// +// # PostgreSQL Specific Data Types +// +// The pgtype package provides support for PostgreSQL specific types. *pgtype.Map.SQLScanner is an adapter that makes +// these types usable as a sql.Scanner. +// +// m := pgtype.NewMap() +// var a []int64 +// err := db.QueryRow("select '{1,2,3}'::bigint[]").Scan(m.SQLScanner(&a)) +package stdlib + +import ( + "context" + "database/sql" + "database/sql/driver" + "errors" + "fmt" + "io" + "math" + "math/rand/v2" + "reflect" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgtype" + "github.com/jackc/pgx/v5/pgxpool" +) + +// Only intrinsic types should be binary format with database/sql. +var databaseSQLResultFormats pgx.QueryResultFormatsByOID + +var pgxDriver *Driver + +func init() { + pgxDriver = &Driver{ + configs: make(map[string]*pgx.ConnConfig), + } + + // if pgx driver was already registered by different pgx major version then we + // skip registration under the default name. + if !slices.Contains(sql.Drivers(), "pgx") { + sql.Register("pgx", pgxDriver) + } + sql.Register("pgx/v5", pgxDriver) + + databaseSQLResultFormats = pgx.QueryResultFormatsByOID{ + pgtype.BoolOID: 1, + pgtype.ByteaOID: 1, + pgtype.CIDOID: 1, + pgtype.DateOID: 1, + pgtype.Float4OID: 1, + pgtype.Float8OID: 1, + pgtype.Int2OID: 1, + pgtype.Int4OID: 1, + pgtype.Int8OID: 1, + pgtype.OIDOID: 1, + pgtype.TimestampOID: 1, + pgtype.TimestamptzOID: 1, + pgtype.XIDOID: 1, + } +} + +// OptionOpenDB options for configuring the driver when opening a new db pool. +type OptionOpenDB func(*connector) + +// ShouldPingParams are passed to OptionShouldPing to decide whether to ping before reusing a connection. +type ShouldPingParams struct { + // Conn is the underlying pgx connection. + Conn *pgx.Conn + // IdleDuration is how long it has been since ResetSession last ran. + IdleDuration time.Duration +} + +// OptionShouldPing controls whether stdlib should issue a liveness ping before reusing a connection. +// If the function returns true, stdlib will ping. +// If it returns false, stdlib will skip the ping. +// If not provided, default is ping only when IdleDuration > 1s. +func OptionShouldPing(f func(context.Context, ShouldPingParams) bool) OptionOpenDB { + return func(dc *connector) { dc.ShouldPing = f } +} + +// OptionBeforeConnect provides a callback for before connect. It is passed a shallow copy of the ConnConfig that will +// be used to connect, so only its immediate members should be modified. Used only if db is opened with *pgx.ConnConfig. +func OptionBeforeConnect(bc func(context.Context, *pgx.ConnConfig) error) OptionOpenDB { + return func(dc *connector) { + dc.BeforeConnect = bc + } +} + +// OptionAfterConnect provides a callback for after connect. Used only if db is opened with *pgx.ConnConfig. +func OptionAfterConnect(ac func(context.Context, *pgx.Conn) error) OptionOpenDB { + return func(dc *connector) { + dc.AfterConnect = ac + } +} + +// OptionResetSession provides a callback that can be used to add custom logic prior to executing a query on the +// connection if the connection has been used before. +// If ResetSessionFunc returns ErrBadConn error the connection will be discarded. +func OptionResetSession(rs func(context.Context, *pgx.Conn) error) OptionOpenDB { + return func(dc *connector) { + dc.ResetSession = rs + } +} + +// RandomizeHostOrderFunc is a BeforeConnect hook that randomizes the host order in the provided connConfig, so that a +// new host becomes primary each time. This is useful to distribute connections for multi-master databases like +// CockroachDB. If you use this you likely should set https://golang.org/pkg/database/sql/#DB.SetConnMaxLifetime as well +// to ensure that connections are periodically rebalanced across your nodes. +func RandomizeHostOrderFunc(ctx context.Context, connConfig *pgx.ConnConfig) error { + if len(connConfig.Fallbacks) == 0 { + return nil + } + + newFallbacks := append([]*pgconn.FallbackConfig{{ + Host: connConfig.Host, + Port: connConfig.Port, + TLSConfig: connConfig.TLSConfig, + }}, connConfig.Fallbacks...) + + rand.Shuffle(len(newFallbacks), func(i, j int) { + newFallbacks[i], newFallbacks[j] = newFallbacks[j], newFallbacks[i] + }) + + // Use the one that sorted last as the primary and keep the rest as the fallbacks + newPrimary := newFallbacks[len(newFallbacks)-1] + connConfig.Host = newPrimary.Host + connConfig.Port = newPrimary.Port + connConfig.TLSConfig = newPrimary.TLSConfig + connConfig.Fallbacks = newFallbacks[:len(newFallbacks)-1] + return nil +} + +func GetConnector(config pgx.ConnConfig, opts ...OptionOpenDB) driver.Connector { + c := connector{ + ConnConfig: config, + BeforeConnect: func(context.Context, *pgx.ConnConfig) error { return nil }, // noop before connect by default + AfterConnect: func(context.Context, *pgx.Conn) error { return nil }, // noop after connect by default + ResetSession: func(context.Context, *pgx.Conn) error { return nil }, // noop reset session by default + driver: pgxDriver, + } + + for _, opt := range opts { + opt(&c) + } + return c +} + +// GetPoolConnector creates a new driver.Connector from the given *pgxpool.Pool. By using this be sure to set the +// maximum idle connections of the *sql.DB created with this connector to zero since they must be managed from the +// *pgxpool.Pool. This is required to avoid acquiring all the connections from the pgxpool and starving any direct +// users of the pgxpool. +func GetPoolConnector(pool *pgxpool.Pool, opts ...OptionOpenDB) driver.Connector { + c := connector{ + pool: pool, + ResetSession: func(context.Context, *pgx.Conn) error { return nil }, // noop reset session by default + driver: pgxDriver, + } + + for _, opt := range opts { + opt(&c) + } + + return c +} + +func OpenDB(config pgx.ConnConfig, opts ...OptionOpenDB) *sql.DB { + c := GetConnector(config, opts...) + return sql.OpenDB(c) +} + +// OpenDBFromPool creates a new *sql.DB from the given *pgxpool.Pool. Note that this method automatically sets the +// maximum number of idle connections in *sql.DB to zero, since they must be managed from the *pgxpool.Pool. This is +// required to avoid acquiring all the connections from the pgxpool and starving any direct users of the pgxpool. Note +// that closing the returned *sql.DB will not close the *pgxpool.Pool. +func OpenDBFromPool(pool *pgxpool.Pool, opts ...OptionOpenDB) *sql.DB { + c := GetPoolConnector(pool, opts...) + db := sql.OpenDB(c) + db.SetMaxIdleConns(0) + return db +} + +type connector struct { + pgx.ConnConfig + pool *pgxpool.Pool + BeforeConnect func(context.Context, *pgx.ConnConfig) error // function to call before creation of every new connection + AfterConnect func(context.Context, *pgx.Conn) error // function to call after creation of every new connection + ResetSession func(context.Context, *pgx.Conn) error // function is called before a connection is reused + ShouldPing func(context.Context, ShouldPingParams) bool // function to decide if stdlib should ping before reusing a connection + driver *Driver +} + +// Connect implement driver.Connector interface +func (c connector) Connect(ctx context.Context) (driver.Conn, error) { + var ( + connConfig pgx.ConnConfig + conn *pgx.Conn + close func(context.Context) error + err error + ) + + if c.pool == nil { + // Create a shallow copy of the config, so that BeforeConnect can safely modify it + connConfig = c.ConnConfig + + if err = c.BeforeConnect(ctx, &connConfig); err != nil { + return nil, err + } + + if conn, err = pgx.ConnectConfig(ctx, &connConfig); err != nil { + return nil, err + } + + if err = c.AfterConnect(ctx, conn); err != nil { + return nil, err + } + + close = conn.Close + } else { + var pconn *pgxpool.Conn + + pconn, err = c.pool.Acquire(ctx) + if err != nil { + return nil, err + } + + conn = pconn.Conn() + + close = func(_ context.Context) error { + pconn.Release() + return nil + } + } + + return &Conn{ + conn: conn, + close: close, + driver: c.driver, + connConfig: connConfig, + resetSessionFunc: c.ResetSession, + shouldPing: c.ShouldPing, + psRefCounts: make(map[*pgconn.StatementDescription]int), + }, nil +} + +// Driver implement driver.Connector interface +func (c connector) Driver() driver.Driver { + return c.driver +} + +// GetDefaultDriver returns the driver initialized in the init function +// and used when the pgx driver is registered. +func GetDefaultDriver() driver.Driver { + return pgxDriver +} + +type Driver struct { + configMutex sync.Mutex + configs map[string]*pgx.ConnConfig + sequence int +} + +func (d *Driver) Open(name string) (driver.Conn, error) { + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) // Ensure eventual timeout + defer cancel() + + connector, err := d.OpenConnector(name) + if err != nil { + return nil, err + } + return connector.Connect(ctx) +} + +func (d *Driver) OpenConnector(name string) (driver.Connector, error) { + return &driverConnector{driver: d, name: name}, nil +} + +func (d *Driver) registerConnConfig(c *pgx.ConnConfig) string { + d.configMutex.Lock() + connStr := fmt.Sprintf("registeredConnConfig%d", d.sequence) + d.sequence++ + d.configs[connStr] = c + d.configMutex.Unlock() + return connStr +} + +func (d *Driver) unregisterConnConfig(connStr string) { + d.configMutex.Lock() + delete(d.configs, connStr) + d.configMutex.Unlock() +} + +type driverConnector struct { + driver *Driver + name string +} + +func (dc *driverConnector) Connect(ctx context.Context) (driver.Conn, error) { + var connConfig *pgx.ConnConfig + + dc.driver.configMutex.Lock() + connConfig = dc.driver.configs[dc.name] + dc.driver.configMutex.Unlock() + + if connConfig == nil { + var err error + connConfig, err = pgx.ParseConfig(dc.name) + if err != nil { + return nil, err + } + } + + conn, err := pgx.ConnectConfig(ctx, connConfig) + if err != nil { + return nil, err + } + + c := &Conn{ + conn: conn, + close: conn.Close, + driver: dc.driver, + connConfig: *connConfig, + resetSessionFunc: func(context.Context, *pgx.Conn) error { return nil }, + psRefCounts: make(map[*pgconn.StatementDescription]int), + } + + return c, nil +} + +func (dc *driverConnector) Driver() driver.Driver { + return dc.driver +} + +// RegisterConnConfig registers a ConnConfig and returns the connection string to use with Open. +func RegisterConnConfig(c *pgx.ConnConfig) string { + return pgxDriver.registerConnConfig(c) +} + +// UnregisterConnConfig removes the ConnConfig registration for connStr. +func UnregisterConnConfig(connStr string) { + pgxDriver.unregisterConnConfig(connStr) +} + +type Conn struct { + conn *pgx.Conn + close func(context.Context) error + driver *Driver + connConfig pgx.ConnConfig + resetSessionFunc func(context.Context, *pgx.Conn) error // Function is called before a connection is reused + shouldPing func(context.Context, ShouldPingParams) bool // Function to decide if stdlib should ping before reusing a connection + lastResetSessionTime time.Time + + // psRefCounts contains reference counts for prepared statements. Prepare uses the underlying pgx logic to generate + // deterministic statement names from the statement text. If this query has already been prepared then the existing + // *pgconn.StatementDescription will be returned. However, this means that if Close is called on the returned Stmt + // then the underlying prepared statement will be closed even when the underlying prepared statement is still in use + // by another database/sql Stmt. To prevent this psRefCounts keeps track of how many database/sql statements are using + // the same underlying statement and only closes the underlying statement when the reference count reaches 0. + psRefCounts map[*pgconn.StatementDescription]int +} + +// Conn returns the underlying *pgx.Conn +func (c *Conn) Conn() *pgx.Conn { + return c.conn +} + +func (c *Conn) Prepare(query string) (driver.Stmt, error) { + return c.PrepareContext(context.Background(), query) +} + +func (c *Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + if c.conn.IsClosed() { + return nil, driver.ErrBadConn + } + + sd, err := c.conn.Prepare(ctx, query, query) + if err != nil { + return nil, err + } + c.psRefCounts[sd]++ + + return &Stmt{sd: sd, conn: c}, nil +} + +func (c *Conn) Close() error { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + return c.close(ctx) +} + +func (c *Conn) Begin() (driver.Tx, error) { + return c.BeginTx(context.Background(), driver.TxOptions{}) +} + +func (c *Conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { + if c.conn.IsClosed() { + return nil, driver.ErrBadConn + } + + var pgxOpts pgx.TxOptions + switch sql.IsolationLevel(opts.Isolation) { + case sql.LevelDefault: + case sql.LevelReadUncommitted: + pgxOpts.IsoLevel = pgx.ReadUncommitted + case sql.LevelReadCommitted: + pgxOpts.IsoLevel = pgx.ReadCommitted + case sql.LevelRepeatableRead, sql.LevelSnapshot: + pgxOpts.IsoLevel = pgx.RepeatableRead + case sql.LevelSerializable: + pgxOpts.IsoLevel = pgx.Serializable + default: + return nil, fmt.Errorf("unsupported isolation: %v", opts.Isolation) + } + + if opts.ReadOnly { + pgxOpts.AccessMode = pgx.ReadOnly + } + + tx, err := c.conn.BeginTx(ctx, pgxOpts) + if err != nil { + return nil, err + } + + return wrapTx{ctx: ctx, tx: tx}, nil +} + +func (c *Conn) ExecContext(ctx context.Context, query string, argsV []driver.NamedValue) (driver.Result, error) { + if c.conn.IsClosed() { + return nil, driver.ErrBadConn + } + + args := make([]any, len(argsV)) + convertNamedArguments(args, argsV) + + commandTag, err := c.conn.Exec(ctx, query, args...) + // if we got a network error before we had a chance to send the query, retry + if err != nil { + if pgconn.SafeToRetry(err) { + return nil, driver.ErrBadConn + } + } + return driver.RowsAffected(commandTag.RowsAffected()), err +} + +func (c *Conn) QueryContext(ctx context.Context, query string, argsV []driver.NamedValue) (driver.Rows, error) { + if c.conn.IsClosed() { + return nil, driver.ErrBadConn + } + + args := make([]any, 1+len(argsV)) + args[0] = databaseSQLResultFormats + convertNamedArguments(args[1:], argsV) + + rows, err := c.conn.Query(ctx, query, args...) + if err != nil { + if pgconn.SafeToRetry(err) { + return nil, driver.ErrBadConn + } + return nil, err + } + + // Preload first row because otherwise we won't know what columns are available when database/sql asks. + more := rows.Next() + if err = rows.Err(); err != nil { + rows.Close() + return nil, err + } + return &Rows{conn: c, rows: rows, skipNext: true, skipNextMore: more}, nil +} + +func (c *Conn) Ping(ctx context.Context) error { + if c.conn.IsClosed() { + return driver.ErrBadConn + } + + err := c.conn.Ping(ctx) + if err != nil { + // A Ping failure implies some sort of fatal state. The connection is almost certainly already closed by the + // failure, but manually close it just to be sure. + c.Close() + return driver.ErrBadConn + } + + return nil +} + +func (c *Conn) CheckNamedValue(*driver.NamedValue) error { + // Underlying pgx supports sql.Scanner and driver.Valuer interfaces natively. So everything can be passed through directly. + return nil +} + +func (c *Conn) ResetSession(ctx context.Context) error { + if c.conn.IsClosed() { + return driver.ErrBadConn + } + + // Discard connection if it has an open transaction. This can happen if the + // application did not properly commit or rollback a transaction. + if c.conn.PgConn().TxStatus() != 'I' { + return driver.ErrBadConn + } + + now := time.Now() + idle := now.Sub(c.lastResetSessionTime) + + doPing := idle > time.Second // default behavior: ping only if idle > 1s + + if c.shouldPing != nil { + doPing = c.shouldPing(ctx, ShouldPingParams{ + Conn: c.conn, + IdleDuration: idle, + }) + } + + if doPing { + if err := c.conn.PgConn().Ping(ctx); err != nil { + return driver.ErrBadConn + } + } + + c.lastResetSessionTime = now + + return c.resetSessionFunc(ctx, c.conn) +} + +type Stmt struct { + sd *pgconn.StatementDescription + conn *Conn +} + +func (s *Stmt) Close() error { + ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) + defer cancel() + + refCount := s.conn.psRefCounts[s.sd] + if refCount == 1 { + delete(s.conn.psRefCounts, s.sd) + } else { + s.conn.psRefCounts[s.sd]-- + return nil + } + + return s.conn.conn.Deallocate(ctx, s.sd.SQL) +} + +func (s *Stmt) NumInput() int { + return len(s.sd.ParamOIDs) +} + +func (s *Stmt) Exec(argsV []driver.Value) (driver.Result, error) { + return nil, errors.New("Stmt.Exec deprecated and not implemented") +} + +func (s *Stmt) ExecContext(ctx context.Context, argsV []driver.NamedValue) (driver.Result, error) { + return s.conn.ExecContext(ctx, s.sd.SQL, argsV) +} + +func (s *Stmt) Query(argsV []driver.Value) (driver.Rows, error) { + return nil, errors.New("Stmt.Query deprecated and not implemented") +} + +func (s *Stmt) QueryContext(ctx context.Context, argsV []driver.NamedValue) (driver.Rows, error) { + return s.conn.QueryContext(ctx, s.sd.SQL, argsV) +} + +type rowValueFunc func(src []byte) (driver.Value, error) + +type Rows struct { + conn *Conn + rows pgx.Rows + valueFuncs []rowValueFunc + skipNext bool + skipNextMore bool + + columnNames []string +} + +func (r *Rows) Columns() []string { + if r.columnNames == nil { + fields := r.rows.FieldDescriptions() + r.columnNames = make([]string, len(fields)) + for i, fd := range fields { + r.columnNames[i] = fd.Name + } + } + + return r.columnNames +} + +// ColumnTypeDatabaseTypeName returns the database system type name. If the name is unknown the OID is returned. +func (r *Rows) ColumnTypeDatabaseTypeName(index int) string { + if dt, ok := r.conn.conn.TypeMap().TypeForOID(r.rows.FieldDescriptions()[index].DataTypeOID); ok { + return strings.ToUpper(dt.Name) + } + + return strconv.FormatInt(int64(r.rows.FieldDescriptions()[index].DataTypeOID), 10) +} + +const varHeaderSize = 4 + +// ColumnTypeLength returns the length of the column type if the column is a +// variable length type. If the column is not a variable length type ok +// should return false. +func (r *Rows) ColumnTypeLength(index int) (int64, bool) { + fd := r.rows.FieldDescriptions()[index] + + switch fd.DataTypeOID { + case pgtype.TextOID, pgtype.ByteaOID: + return math.MaxInt64, true + case pgtype.VarcharOID, pgtype.BPCharOID: + return int64(fd.TypeModifier - varHeaderSize), true + case pgtype.VarbitOID: + return int64(fd.TypeModifier), true + default: + return 0, false + } +} + +// ColumnTypePrecisionScale should return the precision and scale for decimal +// types. If not applicable, ok should be false. +func (r *Rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { + fd := r.rows.FieldDescriptions()[index] + + switch fd.DataTypeOID { + case pgtype.NumericOID: + mod := fd.TypeModifier - varHeaderSize + precision = int64((mod >> 16) & 0xffff) + scale = int64(mod & 0xffff) + return precision, scale, true + default: + return 0, 0, false + } +} + +// ColumnTypeScanType returns the value type that can be used to scan types into. +func (r *Rows) ColumnTypeScanType(index int) reflect.Type { + fd := r.rows.FieldDescriptions()[index] + + switch fd.DataTypeOID { + case pgtype.Float8OID: + return reflect.TypeFor[float64]() + case pgtype.Float4OID: + return reflect.TypeFor[float32]() + case pgtype.Int8OID: + return reflect.TypeFor[int64]() + case pgtype.Int4OID: + return reflect.TypeFor[int32]() + case pgtype.Int2OID: + return reflect.TypeFor[int16]() + case pgtype.BoolOID: + return reflect.TypeFor[bool]() + case pgtype.NumericOID: + return reflect.TypeFor[float64]() + case pgtype.DateOID, pgtype.TimestampOID, pgtype.TimestamptzOID: + return reflect.TypeFor[time.Time]() + case pgtype.ByteaOID: + return reflect.TypeFor[[]byte]() + default: + return reflect.TypeFor[string]() + } +} + +func (r *Rows) Close() error { + r.rows.Close() + return r.rows.Err() +} + +func (r *Rows) Next(dest []driver.Value) error { + m := r.conn.conn.TypeMap() + fieldDescriptions := r.rows.FieldDescriptions() + + if r.valueFuncs == nil { + r.valueFuncs = make([]rowValueFunc, len(fieldDescriptions)) + + for i, fd := range fieldDescriptions { + dataTypeOID := fd.DataTypeOID + format := fd.Format + + switch fd.DataTypeOID { + case pgtype.BoolOID: + var d bool + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return d, err + } + case pgtype.ByteaOID: + var d []byte + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return d, err + } + case pgtype.CIDOID, pgtype.OIDOID, pgtype.XIDOID: + var d pgtype.Uint32 + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + if err != nil { + return nil, err + } + return d.Value() + } + case pgtype.DateOID: + var d pgtype.Date + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + if err != nil { + return nil, err + } + return d.Value() + } + case pgtype.Float4OID: + var d float32 + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return float64(d), err + } + case pgtype.Float8OID: + var d float64 + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return d, err + } + case pgtype.Int2OID: + var d int16 + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return int64(d), err + } + case pgtype.Int4OID: + var d int32 + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return int64(d), err + } + case pgtype.Int8OID: + var d int64 + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return d, err + } + case pgtype.JSONOID, pgtype.JSONBOID: + var d []byte + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + if err != nil { + return nil, err + } + return d, nil + } + case pgtype.TimestampOID: + var d pgtype.Timestamp + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + if err != nil { + return nil, err + } + return d.Value() + } + case pgtype.TimestamptzOID: + var d pgtype.Timestamptz + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + if err != nil { + return nil, err + } + return d.Value() + } + case pgtype.XMLOID: + var d []byte + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + if err != nil { + return nil, err + } + return d, nil + } + default: + var d string + scanPlan := m.PlanScan(dataTypeOID, format, &d) + r.valueFuncs[i] = func(src []byte) (driver.Value, error) { + err := scanPlan.Scan(src, &d) + return d, err + } + } + } + } + + var more bool + if r.skipNext { + more = r.skipNextMore + r.skipNext = false + } else { + more = r.rows.Next() + } + + if !more { + if r.rows.Err() == nil { + return io.EOF + } else { + return r.rows.Err() + } + } + + for i, rv := range r.rows.RawValues() { + if rv != nil { + var err error + dest[i], err = r.valueFuncs[i](rv) + if err != nil { + return fmt.Errorf("convert field %d failed: %w", i, err) + } + } else { + dest[i] = nil + } + } + + return nil +} + +func convertNamedArguments(args []any, argsV []driver.NamedValue) { + for i, v := range argsV { + if v.Value != nil { + args[i] = v.Value.(any) + } else { + args[i] = nil + } + } +} + +type wrapTx struct { + ctx context.Context + tx pgx.Tx +} + +func (wtx wrapTx) Commit() error { return wtx.tx.Commit(wtx.ctx) } + +func (wtx wrapTx) Rollback() error { return wtx.tx.Rollback(wtx.ctx) } diff --git a/vendor/github.com/jackc/pgx/v5/test.sh b/vendor/github.com/jackc/pgx/v5/test.sh new file mode 100644 index 0000000..8bab2d2 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/test.sh @@ -0,0 +1,170 @@ +#!/usr/bin/env bash +set -euo pipefail + +# test.sh - Run pgx tests against specific database targets +# +# Usage: +# ./test.sh [target] [go test flags...] +# +# Targets: +# pg14 - PostgreSQL 14 (port 5414) +# pg15 - PostgreSQL 15 (port 5415) +# pg16 - PostgreSQL 16 (port 5416) +# pg17 - PostgreSQL 17 (port 5417) +# pg18 - PostgreSQL 18 (port 5432) [default] +# crdb - CockroachDB (port 26257) +# all - Run against all targets sequentially +# +# Examples: +# ./test.sh # Test against PG18 +# ./test.sh pg14 # Test against PG14 +# ./test.sh crdb # Test against CockroachDB +# ./test.sh all # Test against all targets +# ./test.sh pg16 -run TestConnect # Test specific test against PG16 +# ./test.sh pg18 -count=1 -v # Verbose, no cache, PG18 + +# Color output (disabled if not a terminal) +if [ -t 1 ]; then + GREEN='\033[0;32m' + RED='\033[0;31m' + BLUE='\033[0;34m' + NC='\033[0m' +else + GREEN='' + RED='' + BLUE='' + NC='' +fi + +log_info() { echo -e "${BLUE}==> $*${NC}"; } +log_ok() { echo -e "${GREEN}==> $*${NC}"; } +log_err() { echo -e "${RED}==> $*${NC}" >&2; } + +# Wait for a database to accept connections +wait_for_ready() { + local connstr="$1" + local label="$2" + local max_attempts=30 + local attempt=0 + + log_info "Waiting for $label to be ready..." + while ! psql "$connstr" -c "SELECT 1" > /dev/null 2>&1; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + log_err "$label did not become ready after $max_attempts attempts" + return 1 + fi + sleep 1 + done + log_ok "$label is ready" +} + +# Directory containing this script (used to locate testsetup/) +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CERTS_DIR="$SCRIPT_DIR/testsetup/certs" + +# Copy client certificates to /tmp for TLS tests +setup_client_certs() { + if [ -d "$CERTS_DIR" ]; then + base64 -d "$CERTS_DIR/ca.pem.b64" > /tmp/ca.pem + base64 -d "$CERTS_DIR/pgx_sslcert.crt.b64" > /tmp/pgx_sslcert.crt + base64 -d "$CERTS_DIR/pgx_sslcert.key.b64" > /tmp/pgx_sslcert.key + fi +} + +# Initialize CockroachDB (create database if not exists) +init_crdb() { + local connstr="postgresql://root@localhost:26257/?sslmode=disable" + wait_for_ready "$connstr" "CockroachDB" + log_info "Ensuring pgx_test database exists on CockroachDB..." + psql "$connstr" -c "CREATE DATABASE IF NOT EXISTS pgx_test" 2>/dev/null || true +} + +# Run tests against a single target +run_tests() { + local target="$1" + shift + local extra_args=("$@") + + local label="" + local port="" + + case "$target" in + pg14) label="PostgreSQL 14"; port=5414 ;; + pg15) label="PostgreSQL 15"; port=5415 ;; + pg16) label="PostgreSQL 16"; port=5416 ;; + pg17) label="PostgreSQL 17"; port=5417 ;; + pg18) label="PostgreSQL 18"; port=5432 ;; + crdb) + label="CockroachDB (port 26257)" + init_crdb + log_info "Testing against $label" + if ! PGX_TEST_DATABASE="postgresql://root@localhost:26257/pgx_test?sslmode=disable&experimental_enable_temp_tables=on" \ + go test -count=1 "${extra_args[@]}" ./...; then + log_err "Tests FAILED against $label" + return 1 + fi + log_ok "Tests passed against $label" + return 0 + ;; + *) + log_err "Unknown target: $target" + log_err "Valid targets: pg14, pg15, pg16, pg17, pg18, crdb, all" + return 1 + ;; + esac + + setup_client_certs + + log_info "Testing against $label (port $port)" + if ! PGX_TEST_DATABASE="host=localhost port=$port user=postgres password=postgres dbname=pgx_test" \ + PGX_TEST_UNIX_SOCKET_CONN_STRING="host=/var/run/postgresql port=$port user=postgres dbname=pgx_test" \ + PGX_TEST_TCP_CONN_STRING="host=127.0.0.1 port=$port user=pgx_md5 password=secret dbname=pgx_test" \ + PGX_TEST_MD5_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_md5 password=secret dbname=pgx_test" \ + PGX_TEST_SCRAM_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_scram password=secret dbname=pgx_test channel_binding=disable" \ + PGX_TEST_SCRAM_PLUS_CONN_STRING="host=localhost port=$port user=pgx_ssl password=secret sslmode=verify-full sslrootcert=/tmp/ca.pem dbname=pgx_test channel_binding=require" \ + PGX_TEST_PLAIN_PASSWORD_CONN_STRING="host=127.0.0.1 port=$port user=pgx_pw password=secret dbname=pgx_test" \ + PGX_TEST_TLS_CONN_STRING="host=localhost port=$port user=pgx_ssl password=secret sslmode=verify-full sslrootcert=/tmp/ca.pem dbname=pgx_test channel_binding=disable" \ + PGX_TEST_TLS_CLIENT_CONN_STRING="host=localhost port=$port user=pgx_sslcert sslmode=verify-full sslrootcert=/tmp/ca.pem sslcert=/tmp/pgx_sslcert.crt sslkey=/tmp/pgx_sslcert.key dbname=pgx_test" \ + PGX_SSL_PASSWORD=certpw \ + go test -count=1 "${extra_args[@]}" ./...; then + log_err "Tests FAILED against $label" + return 1 + fi + log_ok "Tests passed against $label" +} + +# Main +main() { + local target="${1:-pg18}" + + if [ "$target" = "all" ]; then + shift || true + local targets=(pg14 pg15 pg16 pg17 pg18 crdb) + local failed=() + + for t in "${targets[@]}"; do + echo "" + log_info "==========================================" + log_info "Target: $t" + log_info "==========================================" + if ! run_tests "$t" "$@"; then + failed+=("$t") + log_err "FAILED: $t" + fi + done + + echo "" + if [ ${#failed[@]} -gt 0 ]; then + log_err "Failed targets: ${failed[*]}" + return 1 + else + log_ok "All targets passed" + fi + else + shift || true + run_tests "$target" "$@" + fi +} + +main "$@" diff --git a/vendor/github.com/jackc/pgx/v5/tracer.go b/vendor/github.com/jackc/pgx/v5/tracer.go new file mode 100644 index 0000000..58ca99f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/tracer.go @@ -0,0 +1,107 @@ +package pgx + +import ( + "context" + + "github.com/jackc/pgx/v5/pgconn" +) + +// QueryTracer traces Query, QueryRow, and Exec. +type QueryTracer interface { + // TraceQueryStart is called at the beginning of Query, QueryRow, and Exec calls. The returned context is used for the + // rest of the call and will be passed to TraceQueryEnd. + TraceQueryStart(ctx context.Context, conn *Conn, data TraceQueryStartData) context.Context + + TraceQueryEnd(ctx context.Context, conn *Conn, data TraceQueryEndData) +} + +type TraceQueryStartData struct { + SQL string + Args []any +} + +type TraceQueryEndData struct { + CommandTag pgconn.CommandTag + Err error +} + +// BatchTracer traces SendBatch. +type BatchTracer interface { + // TraceBatchStart is called at the beginning of SendBatch calls. The returned context is used for the + // rest of the call and will be passed to TraceBatchQuery and TraceBatchEnd. + TraceBatchStart(ctx context.Context, conn *Conn, data TraceBatchStartData) context.Context + + TraceBatchQuery(ctx context.Context, conn *Conn, data TraceBatchQueryData) + TraceBatchEnd(ctx context.Context, conn *Conn, data TraceBatchEndData) +} + +type TraceBatchStartData struct { + Batch *Batch +} + +type TraceBatchQueryData struct { + SQL string + Args []any + CommandTag pgconn.CommandTag + Err error +} + +type TraceBatchEndData struct { + Err error +} + +// CopyFromTracer traces CopyFrom. +type CopyFromTracer interface { + // TraceCopyFromStart is called at the beginning of CopyFrom calls. The returned context is used for the + // rest of the call and will be passed to TraceCopyFromEnd. + TraceCopyFromStart(ctx context.Context, conn *Conn, data TraceCopyFromStartData) context.Context + + TraceCopyFromEnd(ctx context.Context, conn *Conn, data TraceCopyFromEndData) +} + +type TraceCopyFromStartData struct { + TableName Identifier + ColumnNames []string +} + +type TraceCopyFromEndData struct { + CommandTag pgconn.CommandTag + Err error +} + +// PrepareTracer traces Prepare. +type PrepareTracer interface { + // TracePrepareStart is called at the beginning of Prepare calls. The returned context is used for the + // rest of the call and will be passed to TracePrepareEnd. + TracePrepareStart(ctx context.Context, conn *Conn, data TracePrepareStartData) context.Context + + TracePrepareEnd(ctx context.Context, conn *Conn, data TracePrepareEndData) +} + +type TracePrepareStartData struct { + Name string + SQL string +} + +type TracePrepareEndData struct { + AlreadyPrepared bool + Err error +} + +// ConnectTracer traces Connect and ConnectConfig. +type ConnectTracer interface { + // TraceConnectStart is called at the beginning of Connect and ConnectConfig calls. The returned context is used for + // the rest of the call and will be passed to TraceConnectEnd. + TraceConnectStart(ctx context.Context, data TraceConnectStartData) context.Context + + TraceConnectEnd(ctx context.Context, data TraceConnectEndData) +} + +type TraceConnectStartData struct { + ConnConfig *ConnConfig +} + +type TraceConnectEndData struct { + Conn *Conn + Err error +} diff --git a/vendor/github.com/jackc/pgx/v5/tx.go b/vendor/github.com/jackc/pgx/v5/tx.go new file mode 100644 index 0000000..3f93a6f --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/tx.go @@ -0,0 +1,442 @@ +package pgx + +import ( + "context" + "errors" + "strconv" + "strings" + + "github.com/jackc/pgx/v5/pgconn" +) + +// TxIsoLevel is the transaction isolation level (serializable, repeatable read, read committed or read uncommitted) +type TxIsoLevel string + +// Transaction isolation levels +const ( + Serializable TxIsoLevel = "serializable" + RepeatableRead TxIsoLevel = "repeatable read" + ReadCommitted TxIsoLevel = "read committed" + ReadUncommitted TxIsoLevel = "read uncommitted" +) + +// TxAccessMode is the transaction access mode (read write or read only) +type TxAccessMode string + +// Transaction access modes +const ( + ReadWrite TxAccessMode = "read write" + ReadOnly TxAccessMode = "read only" +) + +// TxDeferrableMode is the transaction deferrable mode (deferrable or not deferrable) +type TxDeferrableMode string + +// Transaction deferrable modes +const ( + Deferrable TxDeferrableMode = "deferrable" + NotDeferrable TxDeferrableMode = "not deferrable" +) + +// TxOptions are transaction modes within a transaction block +type TxOptions struct { + IsoLevel TxIsoLevel + AccessMode TxAccessMode + DeferrableMode TxDeferrableMode + + // BeginQuery is the SQL query that will be executed to begin the transaction. This allows using non-standard syntax + // such as BEGIN PRIORITY HIGH with CockroachDB. If set this will override the other settings. + BeginQuery string + // CommitQuery is the SQL query that will be executed to commit the transaction. + CommitQuery string +} + +var emptyTxOptions TxOptions + +func (txOptions TxOptions) beginSQL() string { + if txOptions == emptyTxOptions { + return "begin" + } + + if txOptions.BeginQuery != "" { + return txOptions.BeginQuery + } + + var buf strings.Builder + buf.Grow(64) // 64 - maximum length of string with available options + buf.WriteString("begin") + + if txOptions.IsoLevel != "" { + buf.WriteString(" isolation level ") + buf.WriteString(string(txOptions.IsoLevel)) + } + if txOptions.AccessMode != "" { + buf.WriteByte(' ') + buf.WriteString(string(txOptions.AccessMode)) + } + if txOptions.DeferrableMode != "" { + buf.WriteByte(' ') + buf.WriteString(string(txOptions.DeferrableMode)) + } + + return buf.String() +} + +var ErrTxClosed = errors.New("tx is closed") + +// ErrTxCommitRollback occurs when an error has occurred in a transaction and +// Commit() is called. PostgreSQL accepts COMMIT on aborted transactions, but +// it is treated as ROLLBACK. +var ErrTxCommitRollback = errors.New("commit unexpectedly resulted in rollback") + +// Begin starts a transaction. Unlike [database/sql], the context only affects the begin command. i.e. there is no +// auto-rollback on context cancellation. +func (c *Conn) Begin(ctx context.Context) (Tx, error) { + return c.BeginTx(ctx, TxOptions{}) +} + +// BeginTx starts a transaction with txOptions determining the transaction mode. Unlike [database/sql], the context only +// affects the begin command. i.e. there is no auto-rollback on context cancellation. +func (c *Conn) BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) { + _, err := c.Exec(ctx, txOptions.beginSQL()) + if err != nil { + // begin should never fail unless there is an underlying connection issue or + // a context timeout. In either case, the connection is possibly broken. + c.die() + return nil, err + } + + return &dbTx{ + conn: c, + commitQuery: txOptions.CommitQuery, + }, nil +} + +// Tx represents a database transaction. +// +// Tx is an interface instead of a struct to enable connection pools to be implemented without relying on internal pgx +// state, to support pseudo-nested transactions with savepoints, and to allow tests to mock transactions. However, +// adding a method to an interface is technically a breaking change. If new methods are added to Conn it may be +// desirable to add them to Tx as well. Because of this the Tx interface is partially excluded from semantic version +// requirements. Methods will not be removed or changed, but new methods may be added. +type Tx interface { + // Begin starts a pseudo nested transaction. + Begin(ctx context.Context) (Tx, error) + + // Commit commits the transaction if this is a real transaction or releases the savepoint if this is a pseudo nested + // transaction. Commit will return an error where errors.Is(ErrTxClosed) is true if the Tx is already closed, but is + // otherwise safe to call multiple times. If the commit fails with a rollback status (e.g. the transaction was already + // in a broken state) then an error where errors.Is(ErrTxCommitRollback) is true will be returned. + Commit(ctx context.Context) error + + // Rollback rolls back the transaction if this is a real transaction or rolls back to the savepoint if this is a + // pseudo nested transaction. Rollback will return an error where errors.Is(ErrTxClosed) is true if the Tx is already + // closed, but is otherwise safe to call multiple times. Hence, a defer tx.Rollback() is safe even if tx.Commit() will + // be called first in a non-error condition. Any other failure of a real transaction will result in the connection + // being closed. + Rollback(ctx context.Context) error + + CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) + SendBatch(ctx context.Context, b *Batch) BatchResults + LargeObjects() LargeObjects + + Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) + + Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) + Query(ctx context.Context, sql string, args ...any) (Rows, error) + QueryRow(ctx context.Context, sql string, args ...any) Row + + // Conn returns the underlying *Conn that on which this transaction is executing. + Conn() *Conn +} + +// dbTx represents a database transaction. +// +// All dbTx methods return ErrTxClosed if Commit or Rollback has already been +// called on the dbTx. +type dbTx struct { + conn *Conn + savepointNum int64 + closed bool + commitQuery string +} + +// Begin starts a pseudo nested transaction implemented with a savepoint. +func (tx *dbTx) Begin(ctx context.Context) (Tx, error) { + if tx.closed { + return nil, ErrTxClosed + } + + tx.savepointNum++ + _, err := tx.conn.Exec(ctx, "savepoint sp_"+strconv.FormatInt(tx.savepointNum, 10)) + if err != nil { + return nil, err + } + + return &dbSimulatedNestedTx{tx: tx, savepointNum: tx.savepointNum}, nil +} + +// Commit commits the transaction. +func (tx *dbTx) Commit(ctx context.Context) error { + if tx.closed { + return ErrTxClosed + } + + commandSQL := "commit" + if tx.commitQuery != "" { + commandSQL = tx.commitQuery + } + + commandTag, err := tx.conn.Exec(ctx, commandSQL) + tx.closed = true + if err != nil { + if tx.conn.PgConn().TxStatus() != 'I' { + _ = tx.conn.Close(ctx) // already have error to return + } + return err + } + if commandTag.String() == "ROLLBACK" { + return ErrTxCommitRollback + } + + return nil +} + +// Rollback rolls back the transaction. Rollback will return ErrTxClosed if the +// Tx is already closed, but is otherwise safe to call multiple times. Hence, a +// defer tx.Rollback() is safe even if tx.Commit() will be called first in a +// non-error condition. +func (tx *dbTx) Rollback(ctx context.Context) error { + if tx.closed { + return ErrTxClosed + } + + _, err := tx.conn.Exec(ctx, "rollback") + tx.closed = true + if err != nil { + // A rollback failure leaves the connection in an undefined state + tx.conn.die() + return err + } + + return nil +} + +// Exec delegates to the underlying *Conn +func (tx *dbTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) { + if tx.closed { + return pgconn.CommandTag{}, ErrTxClosed + } + + return tx.conn.Exec(ctx, sql, arguments...) +} + +// Prepare delegates to the underlying *Conn +func (tx *dbTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) { + if tx.closed { + return nil, ErrTxClosed + } + + return tx.conn.Prepare(ctx, name, sql) +} + +// Query delegates to the underlying *Conn +func (tx *dbTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) { + if tx.closed { + // Because checking for errors can be deferred to the *Rows, build one with the error + err := ErrTxClosed + return &baseRows{closed: true, err: err}, err + } + + return tx.conn.Query(ctx, sql, args...) +} + +// QueryRow delegates to the underlying *Conn +func (tx *dbTx) QueryRow(ctx context.Context, sql string, args ...any) Row { + rows, _ := tx.Query(ctx, sql, args...) + return (*connRow)(rows.(*baseRows)) +} + +// CopyFrom delegates to the underlying *Conn +func (tx *dbTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { + if tx.closed { + return 0, ErrTxClosed + } + + return tx.conn.CopyFrom(ctx, tableName, columnNames, rowSrc) +} + +// SendBatch delegates to the underlying *Conn +func (tx *dbTx) SendBatch(ctx context.Context, b *Batch) BatchResults { + if tx.closed { + return &batchResults{err: ErrTxClosed} + } + + return tx.conn.SendBatch(ctx, b) +} + +// LargeObjects returns a LargeObjects instance for the transaction. +func (tx *dbTx) LargeObjects() LargeObjects { + return LargeObjects{tx: tx} +} + +func (tx *dbTx) Conn() *Conn { + return tx.conn +} + +// dbSimulatedNestedTx represents a simulated nested transaction implemented by a savepoint. +type dbSimulatedNestedTx struct { + tx Tx + savepointNum int64 + closed bool +} + +// Begin starts a pseudo nested transaction implemented with a savepoint. +func (sp *dbSimulatedNestedTx) Begin(ctx context.Context) (Tx, error) { + if sp.closed { + return nil, ErrTxClosed + } + + return sp.tx.Begin(ctx) +} + +// Commit releases the savepoint essentially committing the pseudo nested transaction. +func (sp *dbSimulatedNestedTx) Commit(ctx context.Context) error { + if sp.closed { + return ErrTxClosed + } + + _, err := sp.Exec(ctx, "release savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10)) + sp.closed = true + return err +} + +// Rollback rolls back to the savepoint essentially rolling back the pseudo nested transaction. Rollback will return +// ErrTxClosed if the dbSavepoint is already closed, but is otherwise safe to call multiple times. Hence, a defer sp.Rollback() +// is safe even if sp.Commit() will be called first in a non-error condition. +func (sp *dbSimulatedNestedTx) Rollback(ctx context.Context) error { + if sp.closed { + return ErrTxClosed + } + + _, err := sp.Exec(ctx, "rollback to savepoint sp_"+strconv.FormatInt(sp.savepointNum, 10)) + sp.closed = true + return err +} + +// Exec delegates to the underlying Tx +func (sp *dbSimulatedNestedTx) Exec(ctx context.Context, sql string, arguments ...any) (commandTag pgconn.CommandTag, err error) { + if sp.closed { + return pgconn.CommandTag{}, ErrTxClosed + } + + return sp.tx.Exec(ctx, sql, arguments...) +} + +// Prepare delegates to the underlying Tx +func (sp *dbSimulatedNestedTx) Prepare(ctx context.Context, name, sql string) (*pgconn.StatementDescription, error) { + if sp.closed { + return nil, ErrTxClosed + } + + return sp.tx.Prepare(ctx, name, sql) +} + +// Query delegates to the underlying Tx +func (sp *dbSimulatedNestedTx) Query(ctx context.Context, sql string, args ...any) (Rows, error) { + if sp.closed { + // Because checking for errors can be deferred to the *Rows, build one with the error + err := ErrTxClosed + return &baseRows{closed: true, err: err}, err + } + + return sp.tx.Query(ctx, sql, args...) +} + +// QueryRow delegates to the underlying Tx +func (sp *dbSimulatedNestedTx) QueryRow(ctx context.Context, sql string, args ...any) Row { + rows, _ := sp.Query(ctx, sql, args...) + return (*connRow)(rows.(*baseRows)) +} + +// CopyFrom delegates to the underlying *Conn +func (sp *dbSimulatedNestedTx) CopyFrom(ctx context.Context, tableName Identifier, columnNames []string, rowSrc CopyFromSource) (int64, error) { + if sp.closed { + return 0, ErrTxClosed + } + + return sp.tx.CopyFrom(ctx, tableName, columnNames, rowSrc) +} + +// SendBatch delegates to the underlying *Conn +func (sp *dbSimulatedNestedTx) SendBatch(ctx context.Context, b *Batch) BatchResults { + if sp.closed { + return &batchResults{err: ErrTxClosed} + } + + return sp.tx.SendBatch(ctx, b) +} + +func (sp *dbSimulatedNestedTx) LargeObjects() LargeObjects { + return LargeObjects{tx: sp} +} + +func (sp *dbSimulatedNestedTx) Conn() *Conn { + return sp.tx.Conn() +} + +// BeginFunc calls Begin on db and then calls fn. If fn does not return an error then it calls [Tx.Commit] on db. If fn +// returns an error it calls [Tx.Rollback] on db. The context will be used when executing the transaction control statements +// (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn. +func BeginFunc( + ctx context.Context, + db interface { + Begin(ctx context.Context) (Tx, error) + }, + fn func(Tx) error, +) (err error) { + var tx Tx + tx, err = db.Begin(ctx) + if err != nil { + return err + } + + return beginFuncExec(ctx, tx, fn) +} + +// BeginTxFunc calls BeginTx on db and then calls fn. If fn does not return an error then it calls [Tx.Commit] on db. If fn +// returns an error it calls [Tx.Rollback] on db. The context will be used when executing the transaction control statements +// (BEGIN, ROLLBACK, and COMMIT) but does not otherwise affect the execution of fn. +func BeginTxFunc( + ctx context.Context, + db interface { + BeginTx(ctx context.Context, txOptions TxOptions) (Tx, error) + }, + txOptions TxOptions, + fn func(Tx) error, +) (err error) { + var tx Tx + tx, err = db.BeginTx(ctx, txOptions) + if err != nil { + return err + } + + return beginFuncExec(ctx, tx, fn) +} + +func beginFuncExec(ctx context.Context, tx Tx, fn func(Tx) error) (err error) { + defer func() { + rollbackErr := tx.Rollback(ctx) + if rollbackErr != nil && !errors.Is(rollbackErr, ErrTxClosed) { + err = rollbackErr + } + }() + + fErr := fn(tx) + if fErr != nil { + _ = tx.Rollback(ctx) // ignore rollback error as there is already an error to return + return fErr + } + + return tx.Commit(ctx) +} diff --git a/vendor/github.com/jackc/pgx/v5/values.go b/vendor/github.com/jackc/pgx/v5/values.go new file mode 100644 index 0000000..6e2ff30 --- /dev/null +++ b/vendor/github.com/jackc/pgx/v5/values.go @@ -0,0 +1,63 @@ +package pgx + +import ( + "errors" + + "github.com/jackc/pgx/v5/internal/pgio" + "github.com/jackc/pgx/v5/pgtype" +) + +// PostgreSQL format codes +const ( + TextFormatCode = 0 + BinaryFormatCode = 1 +) + +func convertSimpleArgument(m *pgtype.Map, arg any) (any, error) { + buf, err := m.Encode(0, TextFormatCode, arg, []byte{}) + if err != nil { + return nil, err + } + if buf == nil { + return nil, nil + } + return string(buf), nil +} + +func encodeCopyValue(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) { + sp := len(buf) + buf = pgio.AppendInt32(buf, -1) + argBuf, err := m.Encode(oid, BinaryFormatCode, arg, buf) + if err != nil { + if argBuf2, err2 := tryScanStringCopyValueThenEncode(m, buf, oid, arg); err2 == nil { + argBuf = argBuf2 + } else { + return nil, err + } + } + + if argBuf != nil { + buf = argBuf + pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4)) + } + return buf, nil +} + +func tryScanStringCopyValueThenEncode(m *pgtype.Map, buf []byte, oid uint32, arg any) ([]byte, error) { + s, ok := arg.(string) + if !ok { + textBuf, err := m.Encode(oid, TextFormatCode, arg, nil) + if err != nil { + return nil, errors.New("not a string and cannot be encoded as text") + } + s = string(textBuf) + } + + var v any + err := m.Scan(oid, TextFormatCode, []byte(s), &v) + if err != nil { + return nil, err + } + + return m.Encode(oid, BinaryFormatCode, v, buf) +} diff --git a/vendor/github.com/jackc/puddle/v2/CHANGELOG.md b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md new file mode 100644 index 0000000..d0d202c --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/CHANGELOG.md @@ -0,0 +1,79 @@ +# 2.2.2 (September 10, 2024) + +* Add empty acquire time to stats (Maxim Ivanov) +* Stop importing nanotime from runtime via linkname (maypok86) + +# 2.2.1 (July 15, 2023) + +* Fix: CreateResource cannot overflow pool. This changes documented behavior of CreateResource. Previously, + CreateResource could create a resource even if the pool was full. This could cause the pool to overflow. While this + was documented, it was documenting incorrect behavior. CreateResource now returns an error if the pool is full. + +# 2.2.0 (February 11, 2023) + +* Use Go 1.19 atomics and drop go.uber.org/atomic dependency + +# 2.1.2 (November 12, 2022) + +* Restore support to Go 1.18 via go.uber.org/atomic + +# 2.1.1 (November 11, 2022) + +* Fix create resource concurrently with Stat call race + +# 2.1.0 (October 28, 2022) + +* Concurrency control is now implemented with a semaphore. This simplifies some internal logic, resolves a few error conditions (including a deadlock), and improves performance. (Jan Dubsky) +* Go 1.19 is now required for the improved atomic support. + +# 2.0.1 (October 28, 2022) + +* Fix race condition when Close is called concurrently with multiple constructors + +# 2.0.0 (September 17, 2022) + +* Use generics instead of interface{} (Столяров Владимир Алексеевич) +* Add Reset +* Do not cancel resource construction when Acquire is canceled +* NewPool takes Config + +# 1.3.0 (August 27, 2022) + +* Acquire creates resources in background to allow creation to continue after Acquire is canceled (James Hartig) + +# 1.2.1 (December 2, 2021) + +* TryAcquire now does not block when background constructing resource + +# 1.2.0 (November 20, 2021) + +* Add TryAcquire (A. Jensen) +* Fix: remove memory leak / unintentionally pinned memory when shrinking slices (Alexander Staubo) +* Fix: Do not leave pool locked after panic from nil context + +# 1.1.4 (September 11, 2021) + +* Fix: Deadlock in CreateResource if pool was closed during resource acquisition (Dmitriy Matrenichev) + +# 1.1.3 (December 3, 2020) + +* Fix: Failed resource creation could cause concurrent Acquire to hang. (Evgeny Vanslov) + +# 1.1.2 (September 26, 2020) + +* Fix: Resource.Destroy no longer removes itself from the pool before its destructor has completed. +* Fix: Prevent crash when pool is closed while resource is being created. + +# 1.1.1 (April 2, 2020) + +* Pool.Close can be safely called multiple times +* AcquireAllIDle immediately returns nil if pool is closed +* CreateResource checks if pool is closed before taking any action +* Fix potential race condition when CreateResource and Close are called concurrently. CreateResource now checks if pool is closed before adding newly created resource to pool. + +# 1.1.0 (February 5, 2020) + +* Use runtime.nanotime for faster tracking of acquire time and last usage time. +* Track resource idle time to enable client health check logic. (Patrick Ellul) +* Add CreateResource to construct a new resource without acquiring it. (Patrick Ellul) +* Fix deadlock race when acquire is cancelled. (Michael Tharp) diff --git a/vendor/github.com/jackc/puddle/v2/LICENSE b/vendor/github.com/jackc/puddle/v2/LICENSE new file mode 100644 index 0000000..bcc286c --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2018 Jack Christensen + +MIT License + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/jackc/puddle/v2/README.md b/vendor/github.com/jackc/puddle/v2/README.md new file mode 100644 index 0000000..fa82a9d --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/README.md @@ -0,0 +1,80 @@ +[![Go Reference](https://pkg.go.dev/badge/github.com/jackc/puddle/v2.svg)](https://pkg.go.dev/github.com/jackc/puddle/v2) +![Build Status](https://github.com/jackc/puddle/actions/workflows/ci.yml/badge.svg) + +# Puddle + +Puddle is a tiny generic resource pool library for Go that uses the standard +context library to signal cancellation of acquires. It is designed to contain +the minimum functionality required for a resource pool. It can be used directly +or it can be used as the base for a domain specific resource pool. For example, +a database connection pool may use puddle internally and implement health checks +and keep-alive behavior without needing to implement any concurrent code of its +own. + +## Features + +* Acquire cancellation via context standard library +* Statistics API for monitoring pool pressure +* No dependencies outside of standard library and golang.org/x/sync +* High performance +* 100% test coverage of reachable code + +## Example Usage + +```go +package main + +import ( + "context" + "log" + "net" + + "github.com/jackc/puddle/v2" +) + +func main() { + constructor := func(context.Context) (net.Conn, error) { + return net.Dial("tcp", "127.0.0.1:8080") + } + destructor := func(value net.Conn) { + value.Close() + } + maxPoolSize := int32(10) + + pool, err := puddle.NewPool(&puddle.Config[net.Conn]{Constructor: constructor, Destructor: destructor, MaxSize: maxPoolSize}) + if err != nil { + log.Fatal(err) + } + + // Acquire resource from the pool. + res, err := pool.Acquire(context.Background()) + if err != nil { + log.Fatal(err) + } + + // Use resource. + _, err = res.Value().Write([]byte{1}) + if err != nil { + log.Fatal(err) + } + + // Release when done. + res.Release() +} +``` + +## Status + +Puddle is stable and feature complete. + +* Bug reports and fixes are welcome. +* New features will usually not be accepted if they can be feasibly implemented in a wrapper. +* Performance optimizations will usually not be accepted unless the performance issue rises to the level of a bug. + +## Supported Go Versions + +puddle supports the same versions of Go that are supported by the Go project. For [Go](https://golang.org/doc/devel/release.html#policy) that is the two most recent major releases. This means puddle supports Go 1.19 and higher. + +## License + +MIT diff --git a/vendor/github.com/jackc/puddle/v2/context.go b/vendor/github.com/jackc/puddle/v2/context.go new file mode 100644 index 0000000..e19d2a6 --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/context.go @@ -0,0 +1,24 @@ +package puddle + +import ( + "context" + "time" +) + +// valueCancelCtx combines two contexts into one. One context is used for values and the other is used for cancellation. +type valueCancelCtx struct { + valueCtx context.Context + cancelCtx context.Context +} + +func (ctx *valueCancelCtx) Deadline() (time.Time, bool) { return ctx.cancelCtx.Deadline() } +func (ctx *valueCancelCtx) Done() <-chan struct{} { return ctx.cancelCtx.Done() } +func (ctx *valueCancelCtx) Err() error { return ctx.cancelCtx.Err() } +func (ctx *valueCancelCtx) Value(key any) any { return ctx.valueCtx.Value(key) } + +func newValueCancelCtx(valueCtx, cancelContext context.Context) context.Context { + return &valueCancelCtx{ + valueCtx: valueCtx, + cancelCtx: cancelContext, + } +} diff --git a/vendor/github.com/jackc/puddle/v2/doc.go b/vendor/github.com/jackc/puddle/v2/doc.go new file mode 100644 index 0000000..818e4a6 --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/doc.go @@ -0,0 +1,11 @@ +// Package puddle is a generic resource pool with type-parametrized api. +/* + +Puddle is a tiny generic resource pool library for Go that uses the standard +context library to signal cancellation of acquires. It is designed to contain +the minimum functionality a resource pool needs that cannot be implemented +without concurrency concerns. For example, a database connection pool may use +puddle internally and implement health checks and keep-alive behavior without +needing to implement any concurrent code of its own. +*/ +package puddle diff --git a/vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go b/vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go new file mode 100644 index 0000000..7e4660c --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/internal/genstack/gen_stack.go @@ -0,0 +1,85 @@ +package genstack + +// GenStack implements a generational stack. +// +// GenStack works as common stack except for the fact that all elements in the +// older generation are guaranteed to be popped before any element in the newer +// generation. New elements are always pushed to the current (newest) +// generation. +// +// We could also say that GenStack behaves as a stack in case of a single +// generation, but it behaves as a queue of individual generation stacks. +type GenStack[T any] struct { + // We can represent arbitrary number of generations using 2 stacks. The + // new stack stores all new pushes and the old stack serves all reads. + // Old stack can represent multiple generations. If old == new, then all + // elements pushed in previous (not current) generations have already + // been popped. + + old *stack[T] + new *stack[T] +} + +// NewGenStack creates a new empty GenStack. +func NewGenStack[T any]() *GenStack[T] { + s := &stack[T]{} + return &GenStack[T]{ + old: s, + new: s, + } +} + +func (s *GenStack[T]) Pop() (T, bool) { + // Pushes always append to the new stack, so if the old once becomes + // empty, it will remail empty forever. + if s.old.len() == 0 && s.old != s.new { + s.old = s.new + } + + if s.old.len() == 0 { + var zero T + return zero, false + } + + return s.old.pop(), true +} + +// Push pushes a new element at the top of the stack. +func (s *GenStack[T]) Push(v T) { s.new.push(v) } + +// NextGen starts a new stack generation. +func (s *GenStack[T]) NextGen() { + if s.old == s.new { + s.new = &stack[T]{} + return + } + + // We need to pop from the old stack to the top of the new stack. Let's + // have an example: + // + // Old: 4 3 2 1 + // New: 8 7 6 5 + // PopOrder: 1 2 3 4 5 6 7 8 + // + // + // To preserve pop order, we have to take all elements from the old + // stack and push them to the top of new stack: + // + // New: 8 7 6 5 4 3 2 1 + // + s.new.push(s.old.takeAll()...) + + // We have the old stack allocated and empty, so why not to reuse it as + // new new stack. + s.old, s.new = s.new, s.old +} + +// Len returns number of elements in the stack. +func (s *GenStack[T]) Len() int { + l := s.old.len() + if s.old != s.new { + l += s.new.len() + } + + return l +} diff --git a/vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go b/vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go new file mode 100644 index 0000000..dbced0c --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/internal/genstack/stack.go @@ -0,0 +1,39 @@ +package genstack + +// stack is a wrapper around an array implementing a stack. +// +// We cannot use slice to represent the stack because append might change the +// pointer value of the slice. That would be an issue in GenStack +// implementation. +type stack[T any] struct { + arr []T +} + +// push pushes a new element at the top of a stack. +func (s *stack[T]) push(vs ...T) { s.arr = append(s.arr, vs...) } + +// pop pops the stack top-most element. +// +// If stack length is zero, this method panics. +func (s *stack[T]) pop() T { + idx := s.len() - 1 + val := s.arr[idx] + + // Avoid memory leak + var zero T + s.arr[idx] = zero + + s.arr = s.arr[:idx] + return val +} + +// takeAll returns all elements in the stack in order as they are stored - i.e. +// the top-most stack element is the last one. +func (s *stack[T]) takeAll() []T { + arr := s.arr + s.arr = nil + return arr +} + +// len returns number of elements in the stack. +func (s *stack[T]) len() int { return len(s.arr) } diff --git a/vendor/github.com/jackc/puddle/v2/log.go b/vendor/github.com/jackc/puddle/v2/log.go new file mode 100644 index 0000000..b21b946 --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/log.go @@ -0,0 +1,32 @@ +package puddle + +import "unsafe" + +type ints interface { + int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 +} + +// log2Int returns log2 of an integer. This function panics if val < 0. For val +// == 0, returns 0. +func log2Int[T ints](val T) uint8 { + if val <= 0 { + panic("log2 of non-positive number does not exist") + } + + return log2IntRange(val, 0, uint8(8*unsafe.Sizeof(val))) +} + +func log2IntRange[T ints](val T, begin, end uint8) uint8 { + length := end - begin + if length == 1 { + return begin + } + + delim := begin + length/2 + mask := T(1) << delim + if mask > val { + return log2IntRange(val, begin, delim) + } else { + return log2IntRange(val, delim, end) + } +} diff --git a/vendor/github.com/jackc/puddle/v2/nanotime.go b/vendor/github.com/jackc/puddle/v2/nanotime.go new file mode 100644 index 0000000..8a5351a --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/nanotime.go @@ -0,0 +1,16 @@ +package puddle + +import "time" + +// nanotime returns the time in nanoseconds since process start. +// +// This approach, described at +// https://github.com/golang/go/issues/61765#issuecomment-1672090302, +// is fast, monotonic, and portable, and avoids the previous +// dependence on runtime.nanotime using the (unsafe) linkname hack. +// In particular, time.Since does less work than time.Now. +func nanotime() int64 { + return time.Since(globalStart).Nanoseconds() +} + +var globalStart = time.Now() diff --git a/vendor/github.com/jackc/puddle/v2/pool.go b/vendor/github.com/jackc/puddle/v2/pool.go new file mode 100644 index 0000000..c411d2f --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/pool.go @@ -0,0 +1,710 @@ +package puddle + +import ( + "context" + "errors" + "sync" + "sync/atomic" + "time" + + "github.com/jackc/puddle/v2/internal/genstack" + "golang.org/x/sync/semaphore" +) + +const ( + resourceStatusConstructing = 0 + resourceStatusIdle = iota + resourceStatusAcquired = iota + resourceStatusHijacked = iota +) + +// ErrClosedPool occurs on an attempt to acquire a connection from a closed pool +// or a pool that is closed while the acquire is waiting. +var ErrClosedPool = errors.New("closed pool") + +// ErrNotAvailable occurs on an attempt to acquire a resource from a pool +// that is at maximum capacity and has no available resources. +var ErrNotAvailable = errors.New("resource not available") + +// Constructor is a function called by the pool to construct a resource. +type Constructor[T any] func(ctx context.Context) (res T, err error) + +// Destructor is a function called by the pool to destroy a resource. +type Destructor[T any] func(res T) + +// Resource is the resource handle returned by acquiring from the pool. +type Resource[T any] struct { + value T + pool *Pool[T] + creationTime time.Time + lastUsedNano int64 + poolResetCount int + status byte +} + +// Value returns the resource value. +func (res *Resource[T]) Value() T { + if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { + panic("tried to access resource that is not acquired or hijacked") + } + return res.value +} + +// Release returns the resource to the pool. res must not be subsequently used. +func (res *Resource[T]) Release() { + if res.status != resourceStatusAcquired { + panic("tried to release resource that is not acquired") + } + res.pool.releaseAcquiredResource(res, nanotime()) +} + +// ReleaseUnused returns the resource to the pool without updating when it was last used used. i.e. LastUsedNanotime +// will not change. res must not be subsequently used. +func (res *Resource[T]) ReleaseUnused() { + if res.status != resourceStatusAcquired { + panic("tried to release resource that is not acquired") + } + res.pool.releaseAcquiredResource(res, res.lastUsedNano) +} + +// Destroy returns the resource to the pool for destruction. res must not be +// subsequently used. +func (res *Resource[T]) Destroy() { + if res.status != resourceStatusAcquired { + panic("tried to destroy resource that is not acquired") + } + go res.pool.destroyAcquiredResource(res) +} + +// Hijack assumes ownership of the resource from the pool. Caller is responsible +// for cleanup of resource value. +func (res *Resource[T]) Hijack() { + if res.status != resourceStatusAcquired { + panic("tried to hijack resource that is not acquired") + } + res.pool.hijackAcquiredResource(res) +} + +// CreationTime returns when the resource was created by the pool. +func (res *Resource[T]) CreationTime() time.Time { + if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { + panic("tried to access resource that is not acquired or hijacked") + } + return res.creationTime +} + +// LastUsedNanotime returns when Release was last called on the resource measured in nanoseconds from an arbitrary time +// (a monotonic time). Returns creation time if Release has never been called. This is only useful to compare with +// other calls to LastUsedNanotime. In almost all cases, IdleDuration should be used instead. +func (res *Resource[T]) LastUsedNanotime() int64 { + if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { + panic("tried to access resource that is not acquired or hijacked") + } + + return res.lastUsedNano +} + +// IdleDuration returns the duration since Release was last called on the resource. This is equivalent to subtracting +// LastUsedNanotime to the current nanotime. +func (res *Resource[T]) IdleDuration() time.Duration { + if !(res.status == resourceStatusAcquired || res.status == resourceStatusHijacked) { + panic("tried to access resource that is not acquired or hijacked") + } + + return time.Duration(nanotime() - res.lastUsedNano) +} + +// Pool is a concurrency-safe resource pool. +type Pool[T any] struct { + // mux is the pool internal lock. Any modification of shared state of + // the pool (but Acquires of acquireSem) must be performed only by + // holder of the lock. Long running operations are not allowed when mux + // is held. + mux sync.Mutex + // acquireSem provides an allowance to acquire a resource. + // + // Releases are allowed only when caller holds mux. Acquires have to + // happen before mux is locked (doesn't apply to semaphore.TryAcquire in + // AcquireAllIdle). + acquireSem *semaphore.Weighted + destructWG sync.WaitGroup + + allResources resList[T] + idleResources *genstack.GenStack[*Resource[T]] + + constructor Constructor[T] + destructor Destructor[T] + maxSize int32 + + acquireCount int64 + acquireDuration time.Duration + emptyAcquireCount int64 + emptyAcquireWaitTime time.Duration + canceledAcquireCount atomic.Int64 + + resetCount int + + baseAcquireCtx context.Context + cancelBaseAcquireCtx context.CancelFunc + closed bool +} + +type Config[T any] struct { + Constructor Constructor[T] + Destructor Destructor[T] + MaxSize int32 +} + +// NewPool creates a new pool. Returns an error iff MaxSize is less than 1. +func NewPool[T any](config *Config[T]) (*Pool[T], error) { + if config.MaxSize < 1 { + return nil, errors.New("MaxSize must be >= 1") + } + + baseAcquireCtx, cancelBaseAcquireCtx := context.WithCancel(context.Background()) + + return &Pool[T]{ + acquireSem: semaphore.NewWeighted(int64(config.MaxSize)), + idleResources: genstack.NewGenStack[*Resource[T]](), + maxSize: config.MaxSize, + constructor: config.Constructor, + destructor: config.Destructor, + baseAcquireCtx: baseAcquireCtx, + cancelBaseAcquireCtx: cancelBaseAcquireCtx, + }, nil +} + +// Close destroys all resources in the pool and rejects future Acquire calls. +// Blocks until all resources are returned to pool and destroyed. +func (p *Pool[T]) Close() { + defer p.destructWG.Wait() + + p.mux.Lock() + defer p.mux.Unlock() + + if p.closed { + return + } + p.closed = true + p.cancelBaseAcquireCtx() + + for res, ok := p.idleResources.Pop(); ok; res, ok = p.idleResources.Pop() { + p.allResources.remove(res) + go p.destructResourceValue(res.value) + } +} + +// Stat is a snapshot of Pool statistics. +type Stat struct { + constructingResources int32 + acquiredResources int32 + idleResources int32 + maxResources int32 + acquireCount int64 + acquireDuration time.Duration + emptyAcquireCount int64 + emptyAcquireWaitTime time.Duration + canceledAcquireCount int64 +} + +// TotalResources returns the total number of resources currently in the pool. +// The value is the sum of ConstructingResources, AcquiredResources, and +// IdleResources. +func (s *Stat) TotalResources() int32 { + return s.constructingResources + s.acquiredResources + s.idleResources +} + +// ConstructingResources returns the number of resources with construction in progress in +// the pool. +func (s *Stat) ConstructingResources() int32 { + return s.constructingResources +} + +// AcquiredResources returns the number of currently acquired resources in the pool. +func (s *Stat) AcquiredResources() int32 { + return s.acquiredResources +} + +// IdleResources returns the number of currently idle resources in the pool. +func (s *Stat) IdleResources() int32 { + return s.idleResources +} + +// MaxResources returns the maximum size of the pool. +func (s *Stat) MaxResources() int32 { + return s.maxResources +} + +// AcquireCount returns the cumulative count of successful acquires from the pool. +func (s *Stat) AcquireCount() int64 { + return s.acquireCount +} + +// AcquireDuration returns the total duration of all successful acquires from +// the pool. +func (s *Stat) AcquireDuration() time.Duration { + return s.acquireDuration +} + +// EmptyAcquireCount returns the cumulative count of successful acquires from the pool +// that waited for a resource to be released or constructed because the pool was +// empty. +func (s *Stat) EmptyAcquireCount() int64 { + return s.emptyAcquireCount +} + +// EmptyAcquireWaitTime returns the cumulative time waited for successful acquires +// from the pool for a resource to be released or constructed because the pool was +// empty. +func (s *Stat) EmptyAcquireWaitTime() time.Duration { + return s.emptyAcquireWaitTime +} + +// CanceledAcquireCount returns the cumulative count of acquires from the pool +// that were canceled by a context. +func (s *Stat) CanceledAcquireCount() int64 { + return s.canceledAcquireCount +} + +// Stat returns the current pool statistics. +func (p *Pool[T]) Stat() *Stat { + p.mux.Lock() + defer p.mux.Unlock() + + s := &Stat{ + maxResources: p.maxSize, + acquireCount: p.acquireCount, + emptyAcquireCount: p.emptyAcquireCount, + emptyAcquireWaitTime: p.emptyAcquireWaitTime, + canceledAcquireCount: p.canceledAcquireCount.Load(), + acquireDuration: p.acquireDuration, + } + + for _, res := range p.allResources { + switch res.status { + case resourceStatusConstructing: + s.constructingResources += 1 + case resourceStatusIdle: + s.idleResources += 1 + case resourceStatusAcquired: + s.acquiredResources += 1 + } + } + + return s +} + +// tryAcquireIdleResource checks if there is any idle resource. If there is +// some, this method removes it from idle list and returns it. If the idle pool +// is empty, this method returns nil and doesn't modify the idleResources slice. +// +// WARNING: Caller of this method must hold the pool mutex! +func (p *Pool[T]) tryAcquireIdleResource() *Resource[T] { + res, ok := p.idleResources.Pop() + if !ok { + return nil + } + + res.status = resourceStatusAcquired + return res +} + +// createNewResource creates a new resource and inserts it into list of pool +// resources. +// +// WARNING: Caller of this method must hold the pool mutex! +func (p *Pool[T]) createNewResource() *Resource[T] { + res := &Resource[T]{ + pool: p, + creationTime: time.Now(), + lastUsedNano: nanotime(), + poolResetCount: p.resetCount, + status: resourceStatusConstructing, + } + + p.allResources.append(res) + p.destructWG.Add(1) + + return res +} + +// Acquire gets a resource from the pool. If no resources are available and the pool is not at maximum capacity it will +// create a new resource. If the pool is at maximum capacity it will block until a resource is available. ctx can be +// used to cancel the Acquire. +// +// If Acquire creates a new resource the resource constructor function will receive a context that delegates Value() to +// ctx. Canceling ctx will cause Acquire to return immediately but it will not cancel the resource creation. This avoids +// the problem of it being impossible to create resources when the time to create a resource is greater than any one +// caller of Acquire is willing to wait. +func (p *Pool[T]) Acquire(ctx context.Context) (_ *Resource[T], err error) { + select { + case <-ctx.Done(): + p.canceledAcquireCount.Add(1) + return nil, ctx.Err() + default: + } + + return p.acquire(ctx) +} + +// acquire is a continuation of Acquire function that doesn't check context +// validity. +// +// This function exists solely only for benchmarking purposes. +func (p *Pool[T]) acquire(ctx context.Context) (*Resource[T], error) { + startNano := nanotime() + + var waitedForLock bool + if !p.acquireSem.TryAcquire(1) { + waitedForLock = true + err := p.acquireSem.Acquire(ctx, 1) + if err != nil { + p.canceledAcquireCount.Add(1) + return nil, err + } + } + + p.mux.Lock() + if p.closed { + p.acquireSem.Release(1) + p.mux.Unlock() + return nil, ErrClosedPool + } + + // If a resource is available in the pool. + if res := p.tryAcquireIdleResource(); res != nil { + waitTime := time.Duration(nanotime() - startNano) + if waitedForLock { + p.emptyAcquireCount += 1 + p.emptyAcquireWaitTime += waitTime + } + p.acquireCount += 1 + p.acquireDuration += waitTime + p.mux.Unlock() + return res, nil + } + + if len(p.allResources) >= int(p.maxSize) { + // Unreachable code. + panic("bug: semaphore allowed more acquires than pool allows") + } + + // The resource is not idle, but there is enough space to create one. + res := p.createNewResource() + p.mux.Unlock() + + res, err := p.initResourceValue(ctx, res) + if err != nil { + return nil, err + } + + p.mux.Lock() + defer p.mux.Unlock() + + p.emptyAcquireCount += 1 + p.acquireCount += 1 + waitTime := time.Duration(nanotime() - startNano) + p.acquireDuration += waitTime + p.emptyAcquireWaitTime += waitTime + + return res, nil +} + +func (p *Pool[T]) initResourceValue(ctx context.Context, res *Resource[T]) (*Resource[T], error) { + // Create the resource in a goroutine to immediately return from Acquire + // if ctx is canceled without also canceling the constructor. + // + // See: + // - https://github.com/jackc/pgx/issues/1287 + // - https://github.com/jackc/pgx/issues/1259 + constructErrChan := make(chan error) + go func() { + constructorCtx := newValueCancelCtx(ctx, p.baseAcquireCtx) + value, err := p.constructor(constructorCtx) + if err != nil { + p.mux.Lock() + p.allResources.remove(res) + p.destructWG.Done() + + // The resource won't be acquired because its + // construction failed. We have to allow someone else to + // take that resouce. + p.acquireSem.Release(1) + p.mux.Unlock() + + select { + case constructErrChan <- err: + case <-ctx.Done(): + // The caller is cancelled, so no-one awaits the + // error. This branch avoid goroutine leak. + } + return + } + + // The resource is already in p.allResources where it might be read. So we need to acquire the lock to update its + // status. + p.mux.Lock() + res.value = value + res.status = resourceStatusAcquired + p.mux.Unlock() + + // This select works because the channel is unbuffered. + select { + case constructErrChan <- nil: + case <-ctx.Done(): + p.releaseAcquiredResource(res, res.lastUsedNano) + } + }() + + select { + case <-ctx.Done(): + p.canceledAcquireCount.Add(1) + return nil, ctx.Err() + case err := <-constructErrChan: + if err != nil { + return nil, err + } + return res, nil + } +} + +// TryAcquire gets a resource from the pool if one is immediately available. If not, it returns ErrNotAvailable. If no +// resources are available but the pool has room to grow, a resource will be created in the background. ctx is only +// used to cancel the background creation. +func (p *Pool[T]) TryAcquire(ctx context.Context) (*Resource[T], error) { + if !p.acquireSem.TryAcquire(1) { + return nil, ErrNotAvailable + } + + p.mux.Lock() + defer p.mux.Unlock() + + if p.closed { + p.acquireSem.Release(1) + return nil, ErrClosedPool + } + + // If a resource is available now + if res := p.tryAcquireIdleResource(); res != nil { + p.acquireCount += 1 + return res, nil + } + + if len(p.allResources) >= int(p.maxSize) { + // Unreachable code. + panic("bug: semaphore allowed more acquires than pool allows") + } + + res := p.createNewResource() + go func() { + value, err := p.constructor(ctx) + + p.mux.Lock() + defer p.mux.Unlock() + // We have to create the resource and only then release the + // semaphore - For the time being there is no resource that + // someone could acquire. + defer p.acquireSem.Release(1) + + if err != nil { + p.allResources.remove(res) + p.destructWG.Done() + return + } + + res.value = value + res.status = resourceStatusIdle + p.idleResources.Push(res) + }() + + return nil, ErrNotAvailable +} + +// acquireSemAll tries to acquire num free tokens from sem. This function is +// guaranteed to acquire at least the lowest number of tokens that has been +// available in the semaphore during runtime of this function. +// +// For the time being, semaphore doesn't allow to acquire all tokens atomically +// (see https://github.com/golang/sync/pull/19). We simulate this by trying all +// powers of 2 that are less or equal to num. +// +// For example, let's immagine we have 19 free tokens in the semaphore which in +// total has 24 tokens (i.e. the maxSize of the pool is 24 resources). Then if +// num is 24, the log2Uint(24) is 4 and we try to acquire 16, 8, 4, 2 and 1 +// tokens. Out of those, the acquire of 16, 2 and 1 tokens will succeed. +// +// Naturally, Acquires and Releases of the semaphore might take place +// concurrently. For this reason, it's not guaranteed that absolutely all free +// tokens in the semaphore will be acquired. But it's guaranteed that at least +// the minimal number of tokens that has been present over the whole process +// will be acquired. This is sufficient for the use-case we have in this +// package. +// +// TODO: Replace this with acquireSem.TryAcquireAll() if it gets to +// upstream. https://github.com/golang/sync/pull/19 +func acquireSemAll(sem *semaphore.Weighted, num int) int { + if sem.TryAcquire(int64(num)) { + return num + } + + var acquired int + for i := int(log2Int(num)); i >= 0; i-- { + val := 1 << i + if sem.TryAcquire(int64(val)) { + acquired += val + } + } + + return acquired +} + +// AcquireAllIdle acquires all currently idle resources. Its intended use is for +// health check and keep-alive functionality. It does not update pool +// statistics. +func (p *Pool[T]) AcquireAllIdle() []*Resource[T] { + p.mux.Lock() + defer p.mux.Unlock() + + if p.closed { + return nil + } + + numIdle := p.idleResources.Len() + if numIdle == 0 { + return nil + } + + // In acquireSemAll we use only TryAcquire and not Acquire. Because + // TryAcquire cannot block, the fact that we hold mutex locked and try + // to acquire semaphore cannot result in dead-lock. + // + // Because the mutex is locked, no parallel Release can run. This + // implies that the number of tokens can only decrease because some + // Acquire/TryAcquire call can consume the semaphore token. Consequently + // acquired is always less or equal to numIdle. Moreover if acquired < + // numIdle, then there are some parallel Acquire/TryAcquire calls that + // will take the remaining idle connections. + acquired := acquireSemAll(p.acquireSem, numIdle) + + idle := make([]*Resource[T], acquired) + for i := range idle { + res, _ := p.idleResources.Pop() + res.status = resourceStatusAcquired + idle[i] = res + } + + // We have to bump the generation to ensure that Acquire/TryAcquire + // calls running in parallel (those which caused acquired < numIdle) + // will consume old connections and not freshly released connections + // instead. + p.idleResources.NextGen() + + return idle +} + +// CreateResource constructs a new resource without acquiring it. It goes straight in the IdlePool. If the pool is full +// it returns an error. It can be useful to maintain warm resources under little load. +func (p *Pool[T]) CreateResource(ctx context.Context) error { + if !p.acquireSem.TryAcquire(1) { + return ErrNotAvailable + } + + p.mux.Lock() + if p.closed { + p.acquireSem.Release(1) + p.mux.Unlock() + return ErrClosedPool + } + + if len(p.allResources) >= int(p.maxSize) { + p.acquireSem.Release(1) + p.mux.Unlock() + return ErrNotAvailable + } + + res := p.createNewResource() + p.mux.Unlock() + + value, err := p.constructor(ctx) + p.mux.Lock() + defer p.mux.Unlock() + defer p.acquireSem.Release(1) + if err != nil { + p.allResources.remove(res) + p.destructWG.Done() + return err + } + + res.value = value + res.status = resourceStatusIdle + + // If closed while constructing resource then destroy it and return an error + if p.closed { + go p.destructResourceValue(res.value) + return ErrClosedPool + } + + p.idleResources.Push(res) + + return nil +} + +// Reset destroys all resources, but leaves the pool open. It is intended for use when an error is detected that would +// disrupt all resources (such as a network interruption or a server state change). +// +// It is safe to reset a pool while resources are checked out. Those resources will be destroyed when they are returned +// to the pool. +func (p *Pool[T]) Reset() { + p.mux.Lock() + defer p.mux.Unlock() + + p.resetCount++ + + for res, ok := p.idleResources.Pop(); ok; res, ok = p.idleResources.Pop() { + p.allResources.remove(res) + go p.destructResourceValue(res.value) + } +} + +// releaseAcquiredResource returns res to the the pool. +func (p *Pool[T]) releaseAcquiredResource(res *Resource[T], lastUsedNano int64) { + p.mux.Lock() + defer p.mux.Unlock() + defer p.acquireSem.Release(1) + + if p.closed || res.poolResetCount != p.resetCount { + p.allResources.remove(res) + go p.destructResourceValue(res.value) + } else { + res.lastUsedNano = lastUsedNano + res.status = resourceStatusIdle + p.idleResources.Push(res) + } +} + +// Remove removes res from the pool and closes it. If res is not part of the +// pool Remove will panic. +func (p *Pool[T]) destroyAcquiredResource(res *Resource[T]) { + p.destructResourceValue(res.value) + + p.mux.Lock() + defer p.mux.Unlock() + defer p.acquireSem.Release(1) + + p.allResources.remove(res) +} + +func (p *Pool[T]) hijackAcquiredResource(res *Resource[T]) { + p.mux.Lock() + defer p.mux.Unlock() + defer p.acquireSem.Release(1) + + p.allResources.remove(res) + res.status = resourceStatusHijacked + p.destructWG.Done() // not responsible for destructing hijacked resources +} + +func (p *Pool[T]) destructResourceValue(value T) { + p.destructor(value) + p.destructWG.Done() +} diff --git a/vendor/github.com/jackc/puddle/v2/resource_list.go b/vendor/github.com/jackc/puddle/v2/resource_list.go new file mode 100644 index 0000000..b243095 --- /dev/null +++ b/vendor/github.com/jackc/puddle/v2/resource_list.go @@ -0,0 +1,28 @@ +package puddle + +type resList[T any] []*Resource[T] + +func (l *resList[T]) append(val *Resource[T]) { *l = append(*l, val) } + +func (l *resList[T]) popBack() *Resource[T] { + idx := len(*l) - 1 + val := (*l)[idx] + (*l)[idx] = nil // Avoid memory leak + *l = (*l)[:idx] + + return val +} + +func (l *resList[T]) remove(val *Resource[T]) { + for i, elem := range *l { + if elem == val { + lastIdx := len(*l) - 1 + (*l)[i] = (*l)[lastIdx] + (*l)[lastIdx] = nil // Avoid memory leak + (*l) = (*l)[:lastIdx] + return + } + } + + panic("BUG: removeResource could not find res in slice") +} diff --git a/vendor/github.com/jmoiron/sqlx/.gitignore b/vendor/github.com/jmoiron/sqlx/.gitignore new file mode 100644 index 0000000..b2be23c --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/.gitignore @@ -0,0 +1,25 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test +.idea + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +tags +environ diff --git a/vendor/github.com/jmoiron/sqlx/LICENSE b/vendor/github.com/jmoiron/sqlx/LICENSE new file mode 100644 index 0000000..0d31edf --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/LICENSE @@ -0,0 +1,23 @@ + Copyright (c) 2013, Jason Moiron + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/jmoiron/sqlx/Makefile b/vendor/github.com/jmoiron/sqlx/Makefile new file mode 100644 index 0000000..448b9dd --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/Makefile @@ -0,0 +1,30 @@ +.ONESHELL: +SHELL = /bin/sh +.SHELLFLAGS = -ec + +BASE_PACKAGE := github.com/jmoiron/sqlx + +tooling: + go install honnef.co/go/tools/cmd/staticcheck@v0.4.7 + go install golang.org/x/vuln/cmd/govulncheck@v1.0.4 + go install golang.org/x/tools/cmd/goimports@v0.20.0 + +has-changes: + git diff --exit-code --quiet HEAD -- + +lint: + go vet ./... + staticcheck -checks=all ./... + +fmt: + go list -f '{{.Dir}}' ./... | xargs -I {} goimports -local $(BASE_PACKAGE) -w {} + +vuln-check: + govulncheck ./... + +test-race: + go test -v -race -count=1 ./... + +update-dependencies: + go get -u -t -v ./... + go mod tidy diff --git a/vendor/github.com/jmoiron/sqlx/README.md b/vendor/github.com/jmoiron/sqlx/README.md new file mode 100644 index 0000000..5bfd231 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/README.md @@ -0,0 +1,213 @@ +# sqlx + +[![CircleCI](https://dl.circleci.com/status-badge/img/gh/jmoiron/sqlx/tree/master.svg?style=shield)](https://dl.circleci.com/status-badge/redirect/gh/jmoiron/sqlx/tree/master) [![Coverage Status](https://coveralls.io/repos/github/jmoiron/sqlx/badge.svg?branch=master)](https://coveralls.io/github/jmoiron/sqlx?branch=master) [![Godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/jmoiron/sqlx) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/jmoiron/sqlx/master/LICENSE) + +sqlx is a library which provides a set of extensions on go's standard +`database/sql` library. The sqlx versions of `sql.DB`, `sql.TX`, `sql.Stmt`, +et al. all leave the underlying interfaces untouched, so that their interfaces +are a superset on the standard ones. This makes it relatively painless to +integrate existing codebases using database/sql with sqlx. + +Major additional concepts are: + +* Marshal rows into structs (with embedded struct support), maps, and slices +* Named parameter support including prepared statements +* `Get` and `Select` to go quickly from query to struct/slice + +In addition to the [godoc API documentation](http://godoc.org/github.com/jmoiron/sqlx), +there is also some [user documentation](http://jmoiron.github.io/sqlx/) that +explains how to use `database/sql` along with sqlx. + +## Recent Changes + +1.3.0: + +* `sqlx.DB.Connx(context.Context) *sqlx.Conn` +* `sqlx.BindDriver(driverName, bindType)` +* support for `[]map[string]interface{}` to do "batch" insertions +* allocation & perf improvements for `sqlx.In` + +DB.Connx returns an `sqlx.Conn`, which is an `sql.Conn`-alike consistent with +sqlx's wrapping of other types. + +`BindDriver` allows users to control the bindvars that sqlx will use for drivers, +and add new drivers at runtime. This results in a very slight performance hit +when resolving the driver into a bind type (~40ns per call), but it allows users +to specify what bindtype their driver uses even when sqlx has not been updated +to know about it by default. + +### Backwards Compatibility + +Compatibility with the most recent two versions of Go is a requirement for any +new changes. Compatibility beyond that is not guaranteed. + +Versioning is done with Go modules. Breaking changes (eg. removing deprecated API) +will get major version number bumps. + +## install + + go get github.com/jmoiron/sqlx + +## issues + +Row headers can be ambiguous (`SELECT 1 AS a, 2 AS a`), and the result of +`Columns()` does not fully qualify column names in queries like: + +```sql +SELECT a.id, a.name, b.id, b.name FROM foos AS a JOIN foos AS b ON a.parent = b.id; +``` + +making a struct or map destination ambiguous. Use `AS` in your queries +to give columns distinct names, `rows.Scan` to scan them manually, or +`SliceScan` to get a slice of results. + +## usage + +Below is an example which shows some common use cases for sqlx. Check +[sqlx_test.go](https://github.com/jmoiron/sqlx/blob/master/sqlx_test.go) for more +usage. + + +```go +package main + +import ( + "database/sql" + "fmt" + "log" + + _ "github.com/lib/pq" + "github.com/jmoiron/sqlx" +) + +var schema = ` +CREATE TABLE person ( + first_name text, + last_name text, + email text +); + +CREATE TABLE place ( + country text, + city text NULL, + telcode integer +)` + +type Person struct { + FirstName string `db:"first_name"` + LastName string `db:"last_name"` + Email string +} + +type Place struct { + Country string + City sql.NullString + TelCode int +} + +func main() { + // this Pings the database trying to connect + // use sqlx.Open() for sql.Open() semantics + db, err := sqlx.Connect("postgres", "user=foo dbname=bar sslmode=disable") + if err != nil { + log.Fatalln(err) + } + + // exec the schema or fail; multi-statement Exec behavior varies between + // database drivers; pq will exec them all, sqlite3 won't, ymmv + db.MustExec(schema) + + tx := db.MustBegin() + tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "Jason", "Moiron", "jmoiron@jmoiron.net") + tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "John", "Doe", "johndoeDNE@gmail.net") + tx.MustExec("INSERT INTO place (country, city, telcode) VALUES ($1, $2, $3)", "United States", "New York", "1") + tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Hong Kong", "852") + tx.MustExec("INSERT INTO place (country, telcode) VALUES ($1, $2)", "Singapore", "65") + // Named queries can use structs, so if you have an existing struct (i.e. person := &Person{}) that you have populated, you can pass it in as &person + tx.NamedExec("INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", &Person{"Jane", "Citizen", "jane.citzen@example.com"}) + tx.Commit() + + // Query the database, storing results in a []Person (wrapped in []interface{}) + people := []Person{} + db.Select(&people, "SELECT * FROM person ORDER BY first_name ASC") + jason, john := people[0], people[1] + + fmt.Printf("%#v\n%#v", jason, john) + // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"} + // Person{FirstName:"John", LastName:"Doe", Email:"johndoeDNE@gmail.net"} + + // You can also get a single result, a la QueryRow + jason = Person{} + err = db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason") + fmt.Printf("%#v\n", jason) + // Person{FirstName:"Jason", LastName:"Moiron", Email:"jmoiron@jmoiron.net"} + + // if you have null fields and use SELECT *, you must use sql.Null* in your struct + places := []Place{} + err = db.Select(&places, "SELECT * FROM place ORDER BY telcode ASC") + if err != nil { + fmt.Println(err) + return + } + usa, singsing, honkers := places[0], places[1], places[2] + + fmt.Printf("%#v\n%#v\n%#v\n", usa, singsing, honkers) + // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1} + // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65} + // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852} + + // Loop through rows using only one struct + place := Place{} + rows, err := db.Queryx("SELECT * FROM place") + for rows.Next() { + err := rows.StructScan(&place) + if err != nil { + log.Fatalln(err) + } + fmt.Printf("%#v\n", place) + } + // Place{Country:"United States", City:sql.NullString{String:"New York", Valid:true}, TelCode:1} + // Place{Country:"Hong Kong", City:sql.NullString{String:"", Valid:false}, TelCode:852} + // Place{Country:"Singapore", City:sql.NullString{String:"", Valid:false}, TelCode:65} + + // Named queries, using `:name` as the bindvar. Automatic bindvar support + // which takes into account the dbtype based on the driverName on sqlx.Open/Connect + _, err = db.NamedExec(`INSERT INTO person (first_name,last_name,email) VALUES (:first,:last,:email)`, + map[string]interface{}{ + "first": "Bin", + "last": "Smuth", + "email": "bensmith@allblacks.nz", + }) + + // Selects Mr. Smith from the database + rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:fn`, map[string]interface{}{"fn": "Bin"}) + + // Named queries can also use structs. Their bind names follow the same rules + // as the name -> db mapping, so struct fields are lowercased and the `db` tag + // is taken into consideration. + rows, err = db.NamedQuery(`SELECT * FROM person WHERE first_name=:first_name`, jason) + + + // batch insert + + // batch insert with structs + personStructs := []Person{ + {FirstName: "Ardie", LastName: "Savea", Email: "asavea@ab.co.nz"}, + {FirstName: "Sonny Bill", LastName: "Williams", Email: "sbw@ab.co.nz"}, + {FirstName: "Ngani", LastName: "Laumape", Email: "nlaumape@ab.co.nz"}, + } + + _, err = db.NamedExec(`INSERT INTO person (first_name, last_name, email) + VALUES (:first_name, :last_name, :email)`, personStructs) + + // batch insert with maps + personMaps := []map[string]interface{}{ + {"first_name": "Ardie", "last_name": "Savea", "email": "asavea@ab.co.nz"}, + {"first_name": "Sonny Bill", "last_name": "Williams", "email": "sbw@ab.co.nz"}, + {"first_name": "Ngani", "last_name": "Laumape", "email": "nlaumape@ab.co.nz"}, + } + + _, err = db.NamedExec(`INSERT INTO person (first_name, last_name, email) + VALUES (:first_name, :last_name, :email)`, personMaps) +} +``` diff --git a/vendor/github.com/jmoiron/sqlx/bind.go b/vendor/github.com/jmoiron/sqlx/bind.go new file mode 100644 index 0000000..ec0da4e --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/bind.go @@ -0,0 +1,265 @@ +package sqlx + +import ( + "bytes" + "database/sql/driver" + "errors" + "reflect" + "strconv" + "strings" + "sync" + + "github.com/jmoiron/sqlx/reflectx" +) + +// Bindvar types supported by Rebind, BindMap and BindStruct. +const ( + UNKNOWN = iota + QUESTION + DOLLAR + NAMED + AT +) + +var defaultBinds = map[int][]string{ + DOLLAR: []string{"postgres", "pgx", "pq-timeouts", "cloudsqlpostgres", "ql", "nrpostgres", "cockroach"}, + QUESTION: []string{"mysql", "sqlite3", "nrmysql", "nrsqlite3"}, + NAMED: []string{"oci8", "ora", "goracle", "godror"}, + AT: []string{"sqlserver"}, +} + +var binds sync.Map + +func init() { + for bind, drivers := range defaultBinds { + for _, driver := range drivers { + BindDriver(driver, bind) + } + } + +} + +// BindType returns the bindtype for a given database given a drivername. +func BindType(driverName string) int { + itype, ok := binds.Load(driverName) + if !ok { + return UNKNOWN + } + return itype.(int) +} + +// BindDriver sets the BindType for driverName to bindType. +func BindDriver(driverName string, bindType int) { + binds.Store(driverName, bindType) +} + +// FIXME: this should be able to be tolerant of escaped ?'s in queries without +// losing much speed, and should be to avoid confusion. + +// Rebind a query from the default bindtype (QUESTION) to the target bindtype. +func Rebind(bindType int, query string) string { + switch bindType { + case QUESTION, UNKNOWN: + return query + } + + // Add space enough for 10 params before we have to allocate + rqb := make([]byte, 0, len(query)+10) + + var i, j int + + for i = strings.Index(query, "?"); i != -1; i = strings.Index(query, "?") { + rqb = append(rqb, query[:i]...) + + switch bindType { + case DOLLAR: + rqb = append(rqb, '$') + case NAMED: + rqb = append(rqb, ':', 'a', 'r', 'g') + case AT: + rqb = append(rqb, '@', 'p') + } + + j++ + rqb = strconv.AppendInt(rqb, int64(j), 10) + + query = query[i+1:] + } + + return string(append(rqb, query...)) +} + +// Experimental implementation of Rebind which uses a bytes.Buffer. The code is +// much simpler and should be more resistant to odd unicode, but it is twice as +// slow. Kept here for benchmarking purposes and to possibly replace Rebind if +// problems arise with its somewhat naive handling of unicode. +func rebindBuff(bindType int, query string) string { + if bindType != DOLLAR { + return query + } + + b := make([]byte, 0, len(query)) + rqb := bytes.NewBuffer(b) + j := 1 + for _, r := range query { + if r == '?' { + rqb.WriteRune('$') + rqb.WriteString(strconv.Itoa(j)) + j++ + } else { + rqb.WriteRune(r) + } + } + + return rqb.String() +} + +func asSliceForIn(i interface{}) (v reflect.Value, ok bool) { + if i == nil { + return reflect.Value{}, false + } + + v = reflect.ValueOf(i) + t := reflectx.Deref(v.Type()) + + // Only expand slices + if t.Kind() != reflect.Slice { + return reflect.Value{}, false + } + + // []byte is a driver.Value type so it should not be expanded + if t == reflect.TypeOf([]byte{}) { + return reflect.Value{}, false + + } + + return v, true +} + +// In expands slice values in args, returning the modified query string +// and a new arg list that can be executed by a database. The `query` should +// use the `?` bindVar. The return value uses the `?` bindVar. +func In(query string, args ...interface{}) (string, []interface{}, error) { + // argMeta stores reflect.Value and length for slices and + // the value itself for non-slice arguments + type argMeta struct { + v reflect.Value + i interface{} + length int + } + + var flatArgsCount int + var anySlices bool + + var stackMeta [32]argMeta + + var meta []argMeta + if len(args) <= len(stackMeta) { + meta = stackMeta[:len(args)] + } else { + meta = make([]argMeta, len(args)) + } + + for i, arg := range args { + if a, ok := arg.(driver.Valuer); ok { + var err error + arg, err = a.Value() + if err != nil { + return "", nil, err + } + } + + if v, ok := asSliceForIn(arg); ok { + meta[i].length = v.Len() + meta[i].v = v + + anySlices = true + flatArgsCount += meta[i].length + + if meta[i].length == 0 { + return "", nil, errors.New("empty slice passed to 'in' query") + } + } else { + meta[i].i = arg + flatArgsCount++ + } + } + + // don't do any parsing if there aren't any slices; note that this means + // some errors that we might have caught below will not be returned. + if !anySlices { + return query, args, nil + } + + newArgs := make([]interface{}, 0, flatArgsCount) + + var buf strings.Builder + buf.Grow(len(query) + len(", ?")*flatArgsCount) + + var arg, offset int + + for i := strings.IndexByte(query[offset:], '?'); i != -1; i = strings.IndexByte(query[offset:], '?') { + if arg >= len(meta) { + // if an argument wasn't passed, lets return an error; this is + // not actually how database/sql Exec/Query works, but since we are + // creating an argument list programmatically, we want to be able + // to catch these programmer errors earlier. + return "", nil, errors.New("number of bindVars exceeds arguments") + } + + argMeta := meta[arg] + arg++ + + // not a slice, continue. + // our questionmark will either be written before the next expansion + // of a slice or after the loop when writing the rest of the query + if argMeta.length == 0 { + offset = offset + i + 1 + newArgs = append(newArgs, argMeta.i) + continue + } + + // write everything up to and including our ? character + buf.WriteString(query[:offset+i+1]) + + for si := 1; si < argMeta.length; si++ { + buf.WriteString(", ?") + } + + newArgs = appendReflectSlice(newArgs, argMeta.v, argMeta.length) + + // slice the query and reset the offset. this avoids some bookkeeping for + // the write after the loop + query = query[offset+i+1:] + offset = 0 + } + + buf.WriteString(query) + + if arg < len(meta) { + return "", nil, errors.New("number of bindVars less than number arguments") + } + + return buf.String(), newArgs, nil +} + +func appendReflectSlice(args []interface{}, v reflect.Value, vlen int) []interface{} { + switch val := v.Interface().(type) { + case []interface{}: + args = append(args, val...) + case []int: + for i := range val { + args = append(args, val[i]) + } + case []string: + for i := range val { + args = append(args, val[i]) + } + default: + for si := 0; si < vlen; si++ { + args = append(args, v.Index(si).Interface()) + } + } + + return args +} diff --git a/vendor/github.com/jmoiron/sqlx/doc.go b/vendor/github.com/jmoiron/sqlx/doc.go new file mode 100644 index 0000000..b801041 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/doc.go @@ -0,0 +1,11 @@ +// Package sqlx provides general purpose extensions to database/sql. +// +// It is intended to seamlessly wrap database/sql and provide convenience +// methods which are useful in the development of database driven applications. +// None of the underlying database/sql methods are changed. Instead all extended +// behavior is implemented through new methods defined on wrapper types. +// +// Additions include scanning into structs, named query support, rebinding +// queries for different drivers, convenient shorthands for common error handling +// and more. +package sqlx diff --git a/vendor/github.com/jmoiron/sqlx/named.go b/vendor/github.com/jmoiron/sqlx/named.go new file mode 100644 index 0000000..6ac4477 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/named.go @@ -0,0 +1,458 @@ +package sqlx + +// Named Query Support +// +// * BindMap - bind query bindvars to map/struct args +// * NamedExec, NamedQuery - named query w/ struct or map +// * NamedStmt - a pre-compiled named query which is a prepared statement +// +// Internal Interfaces: +// +// * compileNamedQuery - rebind a named query, returning a query and list of names +// * bindArgs, bindMapArgs, bindAnyArgs - given a list of names, return an arglist +// +import ( + "bytes" + "database/sql" + "errors" + "fmt" + "reflect" + "regexp" + "strconv" + "unicode" + + "github.com/jmoiron/sqlx/reflectx" +) + +// NamedStmt is a prepared statement that executes named queries. Prepare it +// how you would execute a NamedQuery, but pass in a struct or map when executing. +type NamedStmt struct { + Params []string + QueryString string + Stmt *Stmt +} + +// Close closes the named statement. +func (n *NamedStmt) Close() error { + return n.Stmt.Close() +} + +// Exec executes a named statement using the struct passed. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) Exec(arg interface{}) (sql.Result, error) { + args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) + if err != nil { + return *new(sql.Result), err + } + return n.Stmt.Exec(args...) +} + +// Query executes a named statement using the struct argument, returning rows. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) Query(arg interface{}) (*sql.Rows, error) { + args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) + if err != nil { + return nil, err + } + return n.Stmt.Query(args...) +} + +// QueryRow executes a named statement against the database. Because sqlx cannot +// create a *sql.Row with an error condition pre-set for binding errors, sqlx +// returns a *sqlx.Row instead. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) QueryRow(arg interface{}) *Row { + args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) + if err != nil { + return &Row{err: err} + } + return n.Stmt.QueryRowx(args...) +} + +// MustExec execs a NamedStmt, panicing on error +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) MustExec(arg interface{}) sql.Result { + res, err := n.Exec(arg) + if err != nil { + panic(err) + } + return res +} + +// Queryx using this NamedStmt +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) Queryx(arg interface{}) (*Rows, error) { + r, err := n.Query(arg) + if err != nil { + return nil, err + } + return &Rows{Rows: r, Mapper: n.Stmt.Mapper, unsafe: isUnsafe(n)}, err +} + +// QueryRowx this NamedStmt. Because of limitations with QueryRow, this is +// an alias for QueryRow. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) QueryRowx(arg interface{}) *Row { + return n.QueryRow(arg) +} + +// Select using this NamedStmt +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) Select(dest interface{}, arg interface{}) error { + rows, err := n.Queryx(arg) + if err != nil { + return err + } + // if something happens here, we want to make sure the rows are Closed + defer rows.Close() + return scanAll(rows, dest, false) +} + +// Get using this NamedStmt +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) Get(dest interface{}, arg interface{}) error { + r := n.QueryRowx(arg) + return r.scanAny(dest, false) +} + +// Unsafe creates an unsafe version of the NamedStmt +func (n *NamedStmt) Unsafe() *NamedStmt { + r := &NamedStmt{Params: n.Params, Stmt: n.Stmt, QueryString: n.QueryString} + r.Stmt.unsafe = true + return r +} + +// A union interface of preparer and binder, required to be able to prepare +// named statements (as the bindtype must be determined). +type namedPreparer interface { + Preparer + binder +} + +func prepareNamed(p namedPreparer, query string) (*NamedStmt, error) { + bindType := BindType(p.DriverName()) + q, args, err := compileNamedQuery([]byte(query), bindType) + if err != nil { + return nil, err + } + stmt, err := Preparex(p, q) + if err != nil { + return nil, err + } + return &NamedStmt{ + QueryString: q, + Params: args, + Stmt: stmt, + }, nil +} + +// convertMapStringInterface attempts to convert v to map[string]interface{}. +// Unlike v.(map[string]interface{}), this function works on named types that +// are convertible to map[string]interface{} as well. +func convertMapStringInterface(v interface{}) (map[string]interface{}, bool) { + var m map[string]interface{} + mtype := reflect.TypeOf(m) + t := reflect.TypeOf(v) + if !t.ConvertibleTo(mtype) { + return nil, false + } + return reflect.ValueOf(v).Convert(mtype).Interface().(map[string]interface{}), true + +} + +func bindAnyArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) { + if maparg, ok := convertMapStringInterface(arg); ok { + return bindMapArgs(names, maparg) + } + return bindArgs(names, arg, m) +} + +// private interface to generate a list of interfaces from a given struct +// type, given a list of names to pull out of the struct. Used by public +// BindStruct interface. +func bindArgs(names []string, arg interface{}, m *reflectx.Mapper) ([]interface{}, error) { + arglist := make([]interface{}, 0, len(names)) + + // grab the indirected value of arg + var v reflect.Value + for v = reflect.ValueOf(arg); v.Kind() == reflect.Ptr; { + v = v.Elem() + } + + err := m.TraversalsByNameFunc(v.Type(), names, func(i int, t []int) error { + if len(t) == 0 { + return fmt.Errorf("could not find name %s in %#v", names[i], arg) + } + + val := reflectx.FieldByIndexesReadOnly(v, t) + arglist = append(arglist, val.Interface()) + + return nil + }) + + return arglist, err +} + +// like bindArgs, but for maps. +func bindMapArgs(names []string, arg map[string]interface{}) ([]interface{}, error) { + arglist := make([]interface{}, 0, len(names)) + + for _, name := range names { + val, ok := arg[name] + if !ok { + return arglist, fmt.Errorf("could not find name %s in %#v", name, arg) + } + arglist = append(arglist, val) + } + return arglist, nil +} + +// bindStruct binds a named parameter query with fields from a struct argument. +// The rules for binding field names to parameter names follow the same +// conventions as for StructScan, including obeying the `db` struct tags. +func bindStruct(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) { + bound, names, err := compileNamedQuery([]byte(query), bindType) + if err != nil { + return "", []interface{}{}, err + } + + arglist, err := bindAnyArgs(names, arg, m) + if err != nil { + return "", []interface{}{}, err + } + + return bound, arglist, nil +} + +var valuesReg = regexp.MustCompile(`\)\s*(?i)VALUES\s*\(`) + +func findMatchingClosingBracketIndex(s string) int { + count := 0 + for i, ch := range s { + if ch == '(' { + count++ + } + if ch == ')' { + count-- + if count == 0 { + return i + } + } + } + return 0 +} + +func fixBound(bound string, loop int) string { + loc := valuesReg.FindStringIndex(bound) + // defensive guard when "VALUES (...)" not found + if len(loc) < 2 { + return bound + } + + openingBracketIndex := loc[1] - 1 + index := findMatchingClosingBracketIndex(bound[openingBracketIndex:]) + // defensive guard. must have closing bracket + if index == 0 { + return bound + } + closingBracketIndex := openingBracketIndex + index + 1 + + var buffer bytes.Buffer + + buffer.WriteString(bound[0:closingBracketIndex]) + for i := 0; i < loop-1; i++ { + buffer.WriteString(",") + buffer.WriteString(bound[openingBracketIndex:closingBracketIndex]) + } + buffer.WriteString(bound[closingBracketIndex:]) + return buffer.String() +} + +// bindArray binds a named parameter query with fields from an array or slice of +// structs argument. +func bindArray(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) { + // do the initial binding with QUESTION; if bindType is not question, + // we can rebind it at the end. + bound, names, err := compileNamedQuery([]byte(query), QUESTION) + if err != nil { + return "", []interface{}{}, err + } + arrayValue := reflect.ValueOf(arg) + arrayLen := arrayValue.Len() + if arrayLen == 0 { + return "", []interface{}{}, fmt.Errorf("length of array is 0: %#v", arg) + } + var arglist = make([]interface{}, 0, len(names)*arrayLen) + for i := 0; i < arrayLen; i++ { + elemArglist, err := bindAnyArgs(names, arrayValue.Index(i).Interface(), m) + if err != nil { + return "", []interface{}{}, err + } + arglist = append(arglist, elemArglist...) + } + if arrayLen > 1 { + bound = fixBound(bound, arrayLen) + } + // adjust binding type if we weren't on question + if bindType != QUESTION { + bound = Rebind(bindType, bound) + } + return bound, arglist, nil +} + +// bindMap binds a named parameter query with a map of arguments. +func bindMap(bindType int, query string, args map[string]interface{}) (string, []interface{}, error) { + bound, names, err := compileNamedQuery([]byte(query), bindType) + if err != nil { + return "", []interface{}{}, err + } + + arglist, err := bindMapArgs(names, args) + return bound, arglist, err +} + +// -- Compilation of Named Queries + +// Allow digits and letters in bind params; additionally runes are +// checked against underscores, meaning that bind params can have be +// alphanumeric with underscores. Mind the difference between unicode +// digits and numbers, where '5' is a digit but '五' is not. +var allowedBindRunes = []*unicode.RangeTable{unicode.Letter, unicode.Digit} + +// FIXME: this function isn't safe for unicode named params, as a failing test +// can testify. This is not a regression but a failure of the original code +// as well. It should be modified to range over runes in a string rather than +// bytes, even though this is less convenient and slower. Hopefully the +// addition of the prepared NamedStmt (which will only do this once) will make +// up for the slightly slower ad-hoc NamedExec/NamedQuery. + +// compile a NamedQuery into an unbound query (using the '?' bindvar) and +// a list of names. +func compileNamedQuery(qs []byte, bindType int) (query string, names []string, err error) { + names = make([]string, 0, 10) + rebound := make([]byte, 0, len(qs)) + + inName := false + last := len(qs) - 1 + currentVar := 1 + name := make([]byte, 0, 10) + + for i, b := range qs { + // a ':' while we're in a name is an error + if b == ':' { + // if this is the second ':' in a '::' escape sequence, append a ':' + if inName && i > 0 && qs[i-1] == ':' { + rebound = append(rebound, ':') + inName = false + continue + } else if inName { + err = errors.New("unexpected `:` while reading named param at " + strconv.Itoa(i)) + return query, names, err + } + inName = true + name = []byte{} + } else if inName && i > 0 && b == '=' && len(name) == 0 { + rebound = append(rebound, ':', '=') + inName = false + continue + // if we're in a name, and this is an allowed character, continue + } else if inName && (unicode.IsOneOf(allowedBindRunes, rune(b)) || b == '_' || b == '.') && i != last { + // append the byte to the name if we are in a name and not on the last byte + name = append(name, b) + // if we're in a name and it's not an allowed character, the name is done + } else if inName { + inName = false + // if this is the final byte of the string and it is part of the name, then + // make sure to add it to the name + if i == last && unicode.IsOneOf(allowedBindRunes, rune(b)) { + name = append(name, b) + } + // add the string representation to the names list + names = append(names, string(name)) + // add a proper bindvar for the bindType + switch bindType { + // oracle only supports named type bind vars even for positional + case NAMED: + rebound = append(rebound, ':') + rebound = append(rebound, name...) + case QUESTION, UNKNOWN: + rebound = append(rebound, '?') + case DOLLAR: + rebound = append(rebound, '$') + for _, b := range strconv.Itoa(currentVar) { + rebound = append(rebound, byte(b)) + } + currentVar++ + case AT: + rebound = append(rebound, '@', 'p') + for _, b := range strconv.Itoa(currentVar) { + rebound = append(rebound, byte(b)) + } + currentVar++ + } + // add this byte to string unless it was not part of the name + if i != last { + rebound = append(rebound, b) + } else if !unicode.IsOneOf(allowedBindRunes, rune(b)) { + rebound = append(rebound, b) + } + } else { + // this is a normal byte and should just go onto the rebound query + rebound = append(rebound, b) + } + } + + return string(rebound), names, err +} + +// BindNamed binds a struct or a map to a query with named parameters. +// DEPRECATED: use sqlx.Named` instead of this, it may be removed in future. +func BindNamed(bindType int, query string, arg interface{}) (string, []interface{}, error) { + return bindNamedMapper(bindType, query, arg, mapper()) +} + +// Named takes a query using named parameters and an argument and +// returns a new query with a list of args that can be executed by +// a database. The return value uses the `?` bindvar. +func Named(query string, arg interface{}) (string, []interface{}, error) { + return bindNamedMapper(QUESTION, query, arg, mapper()) +} + +func bindNamedMapper(bindType int, query string, arg interface{}, m *reflectx.Mapper) (string, []interface{}, error) { + t := reflect.TypeOf(arg) + k := t.Kind() + switch { + case k == reflect.Map && t.Key().Kind() == reflect.String: + m, ok := convertMapStringInterface(arg) + if !ok { + return "", nil, fmt.Errorf("sqlx.bindNamedMapper: unsupported map type: %T", arg) + } + return bindMap(bindType, query, m) + case k == reflect.Array || k == reflect.Slice: + return bindArray(bindType, query, arg, m) + default: + return bindStruct(bindType, query, arg, m) + } +} + +// NamedQuery binds a named query and then runs Query on the result using the +// provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with +// map[string]interface{} types. +func NamedQuery(e Ext, query string, arg interface{}) (*Rows, error) { + q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) + if err != nil { + return nil, err + } + return e.Queryx(q, args...) +} + +// NamedExec uses BindStruct to get a query executable by the driver and +// then runs Exec on the result. Returns an error from the binding +// or the query execution itself. +func NamedExec(e Ext, query string, arg interface{}) (sql.Result, error) { + q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) + if err != nil { + return nil, err + } + return e.Exec(q, args...) +} diff --git a/vendor/github.com/jmoiron/sqlx/named_context.go b/vendor/github.com/jmoiron/sqlx/named_context.go new file mode 100644 index 0000000..9ad23f4 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/named_context.go @@ -0,0 +1,133 @@ +//go:build go1.8 +// +build go1.8 + +package sqlx + +import ( + "context" + "database/sql" +) + +// A union interface of contextPreparer and binder, required to be able to +// prepare named statements with context (as the bindtype must be determined). +type namedPreparerContext interface { + PreparerContext + binder +} + +func prepareNamedContext(ctx context.Context, p namedPreparerContext, query string) (*NamedStmt, error) { + bindType := BindType(p.DriverName()) + q, args, err := compileNamedQuery([]byte(query), bindType) + if err != nil { + return nil, err + } + stmt, err := PreparexContext(ctx, p, q) + if err != nil { + return nil, err + } + return &NamedStmt{ + QueryString: q, + Params: args, + Stmt: stmt, + }, nil +} + +// ExecContext executes a named statement using the struct passed. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) ExecContext(ctx context.Context, arg interface{}) (sql.Result, error) { + args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) + if err != nil { + return *new(sql.Result), err + } + return n.Stmt.ExecContext(ctx, args...) +} + +// QueryContext executes a named statement using the struct argument, returning rows. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) QueryContext(ctx context.Context, arg interface{}) (*sql.Rows, error) { + args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) + if err != nil { + return nil, err + } + return n.Stmt.QueryContext(ctx, args...) +} + +// QueryRowContext executes a named statement against the database. Because sqlx cannot +// create a *sql.Row with an error condition pre-set for binding errors, sqlx +// returns a *sqlx.Row instead. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) QueryRowContext(ctx context.Context, arg interface{}) *Row { + args, err := bindAnyArgs(n.Params, arg, n.Stmt.Mapper) + if err != nil { + return &Row{err: err} + } + return n.Stmt.QueryRowxContext(ctx, args...) +} + +// MustExecContext execs a NamedStmt, panicing on error +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) MustExecContext(ctx context.Context, arg interface{}) sql.Result { + res, err := n.ExecContext(ctx, arg) + if err != nil { + panic(err) + } + return res +} + +// QueryxContext using this NamedStmt +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) QueryxContext(ctx context.Context, arg interface{}) (*Rows, error) { + r, err := n.QueryContext(ctx, arg) + if err != nil { + return nil, err + } + return &Rows{Rows: r, Mapper: n.Stmt.Mapper, unsafe: isUnsafe(n)}, err +} + +// QueryRowxContext this NamedStmt. Because of limitations with QueryRow, this is +// an alias for QueryRow. +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) QueryRowxContext(ctx context.Context, arg interface{}) *Row { + return n.QueryRowContext(ctx, arg) +} + +// SelectContext using this NamedStmt +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) SelectContext(ctx context.Context, dest interface{}, arg interface{}) error { + rows, err := n.QueryxContext(ctx, arg) + if err != nil { + return err + } + // if something happens here, we want to make sure the rows are Closed + defer rows.Close() + return scanAll(rows, dest, false) +} + +// GetContext using this NamedStmt +// Any named placeholder parameters are replaced with fields from arg. +func (n *NamedStmt) GetContext(ctx context.Context, dest interface{}, arg interface{}) error { + r := n.QueryRowxContext(ctx, arg) + return r.scanAny(dest, false) +} + +// NamedQueryContext binds a named query and then runs Query on the result using the +// provided Ext (sqlx.Tx, sqlx.Db). It works with both structs and with +// map[string]interface{} types. +func NamedQueryContext(ctx context.Context, e ExtContext, query string, arg interface{}) (*Rows, error) { + q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) + if err != nil { + return nil, err + } + return e.QueryxContext(ctx, q, args...) +} + +// NamedExecContext uses BindStruct to get a query executable by the driver and +// then runs Exec on the result. Returns an error from the binding +// or the query execution itself. +func NamedExecContext(ctx context.Context, e ExtContext, query string, arg interface{}) (sql.Result, error) { + q, args, err := bindNamedMapper(BindType(e.DriverName()), query, arg, mapperFor(e)) + if err != nil { + return nil, err + } + return e.ExecContext(ctx, q, args...) +} diff --git a/vendor/github.com/jmoiron/sqlx/reflectx/README.md b/vendor/github.com/jmoiron/sqlx/reflectx/README.md new file mode 100644 index 0000000..f01d3d1 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/reflectx/README.md @@ -0,0 +1,17 @@ +# reflectx + +The sqlx package has special reflect needs. In particular, it needs to: + +* be able to map a name to a field +* understand embedded structs +* understand mapping names to fields by a particular tag +* user specified name -> field mapping functions + +These behaviors mimic the behaviors by the standard library marshallers and also the +behavior of standard Go accessors. + +The first two are amply taken care of by `Reflect.Value.FieldByName`, and the third is +addressed by `Reflect.Value.FieldByNameFunc`, but these don't quite understand struct +tags in the ways that are vital to most marshallers, and they are slow. + +This reflectx package extends reflect to achieve these goals. diff --git a/vendor/github.com/jmoiron/sqlx/reflectx/reflect.go b/vendor/github.com/jmoiron/sqlx/reflectx/reflect.go new file mode 100644 index 0000000..8ec6a13 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/reflectx/reflect.go @@ -0,0 +1,443 @@ +// Package reflectx implements extensions to the standard reflect lib suitable +// for implementing marshalling and unmarshalling packages. The main Mapper type +// allows for Go-compatible named attribute access, including accessing embedded +// struct attributes and the ability to use functions and struct tags to +// customize field names. +package reflectx + +import ( + "reflect" + "runtime" + "strings" + "sync" +) + +// A FieldInfo is metadata for a struct field. +type FieldInfo struct { + Index []int + Path string + Field reflect.StructField + Zero reflect.Value + Name string + Options map[string]string + Embedded bool + Children []*FieldInfo + Parent *FieldInfo +} + +// A StructMap is an index of field metadata for a struct. +type StructMap struct { + Tree *FieldInfo + Index []*FieldInfo + Paths map[string]*FieldInfo + Names map[string]*FieldInfo +} + +// GetByPath returns a *FieldInfo for a given string path. +func (f StructMap) GetByPath(path string) *FieldInfo { + return f.Paths[path] +} + +// GetByTraversal returns a *FieldInfo for a given integer path. It is +// analogous to reflect.FieldByIndex, but using the cached traversal +// rather than re-executing the reflect machinery each time. +func (f StructMap) GetByTraversal(index []int) *FieldInfo { + if len(index) == 0 { + return nil + } + + tree := f.Tree + for _, i := range index { + if i >= len(tree.Children) || tree.Children[i] == nil { + return nil + } + tree = tree.Children[i] + } + return tree +} + +// Mapper is a general purpose mapper of names to struct fields. A Mapper +// behaves like most marshallers in the standard library, obeying a field tag +// for name mapping but also providing a basic transform function. +type Mapper struct { + cache map[reflect.Type]*StructMap + tagName string + tagMapFunc func(string) string + mapFunc func(string) string + mutex sync.Mutex +} + +// NewMapper returns a new mapper using the tagName as its struct field tag. +// If tagName is the empty string, it is ignored. +func NewMapper(tagName string) *Mapper { + return &Mapper{ + cache: make(map[reflect.Type]*StructMap), + tagName: tagName, + } +} + +// NewMapperTagFunc returns a new mapper which contains a mapper for field names +// AND a mapper for tag values. This is useful for tags like json which can +// have values like "name,omitempty". +func NewMapperTagFunc(tagName string, mapFunc, tagMapFunc func(string) string) *Mapper { + return &Mapper{ + cache: make(map[reflect.Type]*StructMap), + tagName: tagName, + mapFunc: mapFunc, + tagMapFunc: tagMapFunc, + } +} + +// NewMapperFunc returns a new mapper which optionally obeys a field tag and +// a struct field name mapper func given by f. Tags will take precedence, but +// for any other field, the mapped name will be f(field.Name) +func NewMapperFunc(tagName string, f func(string) string) *Mapper { + return &Mapper{ + cache: make(map[reflect.Type]*StructMap), + tagName: tagName, + mapFunc: f, + } +} + +// TypeMap returns a mapping of field strings to int slices representing +// the traversal down the struct to reach the field. +func (m *Mapper) TypeMap(t reflect.Type) *StructMap { + m.mutex.Lock() + mapping, ok := m.cache[t] + if !ok { + mapping = getMapping(t, m.tagName, m.mapFunc, m.tagMapFunc) + m.cache[t] = mapping + } + m.mutex.Unlock() + return mapping +} + +// FieldMap returns the mapper's mapping of field names to reflect values. Panics +// if v's Kind is not Struct, or v is not Indirectable to a struct kind. +func (m *Mapper) FieldMap(v reflect.Value) map[string]reflect.Value { + v = reflect.Indirect(v) + mustBe(v, reflect.Struct) + + r := map[string]reflect.Value{} + tm := m.TypeMap(v.Type()) + for tagName, fi := range tm.Names { + r[tagName] = FieldByIndexes(v, fi.Index) + } + return r +} + +// FieldByName returns a field by its mapped name as a reflect.Value. +// Panics if v's Kind is not Struct or v is not Indirectable to a struct Kind. +// Returns zero Value if the name is not found. +func (m *Mapper) FieldByName(v reflect.Value, name string) reflect.Value { + v = reflect.Indirect(v) + mustBe(v, reflect.Struct) + + tm := m.TypeMap(v.Type()) + fi, ok := tm.Names[name] + if !ok { + return v + } + return FieldByIndexes(v, fi.Index) +} + +// FieldsByName returns a slice of values corresponding to the slice of names +// for the value. Panics if v's Kind is not Struct or v is not Indirectable +// to a struct Kind. Returns zero Value for each name not found. +func (m *Mapper) FieldsByName(v reflect.Value, names []string) []reflect.Value { + v = reflect.Indirect(v) + mustBe(v, reflect.Struct) + + tm := m.TypeMap(v.Type()) + vals := make([]reflect.Value, 0, len(names)) + for _, name := range names { + fi, ok := tm.Names[name] + if !ok { + vals = append(vals, *new(reflect.Value)) + } else { + vals = append(vals, FieldByIndexes(v, fi.Index)) + } + } + return vals +} + +// TraversalsByName returns a slice of int slices which represent the struct +// traversals for each mapped name. Panics if t is not a struct or Indirectable +// to a struct. Returns empty int slice for each name not found. +func (m *Mapper) TraversalsByName(t reflect.Type, names []string) [][]int { + r := make([][]int, 0, len(names)) + m.TraversalsByNameFunc(t, names, func(_ int, i []int) error { + if i == nil { + r = append(r, []int{}) + } else { + r = append(r, i) + } + + return nil + }) + return r +} + +// TraversalsByNameFunc traverses the mapped names and calls fn with the index of +// each name and the struct traversal represented by that name. Panics if t is not +// a struct or Indirectable to a struct. Returns the first error returned by fn or nil. +func (m *Mapper) TraversalsByNameFunc(t reflect.Type, names []string, fn func(int, []int) error) error { + t = Deref(t) + mustBe(t, reflect.Struct) + tm := m.TypeMap(t) + for i, name := range names { + fi, ok := tm.Names[name] + if !ok { + if err := fn(i, nil); err != nil { + return err + } + } else { + if err := fn(i, fi.Index); err != nil { + return err + } + } + } + return nil +} + +// FieldByIndexes returns a value for the field given by the struct traversal +// for the given value. +func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value { + for _, i := range indexes { + v = reflect.Indirect(v).Field(i) + // if this is a pointer and it's nil, allocate a new value and set it + if v.Kind() == reflect.Ptr && v.IsNil() { + alloc := reflect.New(Deref(v.Type())) + v.Set(alloc) + } + if v.Kind() == reflect.Map && v.IsNil() { + v.Set(reflect.MakeMap(v.Type())) + } + } + return v +} + +// FieldByIndexesReadOnly returns a value for a particular struct traversal, +// but is not concerned with allocating nil pointers because the value is +// going to be used for reading and not setting. +func FieldByIndexesReadOnly(v reflect.Value, indexes []int) reflect.Value { + for _, i := range indexes { + v = reflect.Indirect(v).Field(i) + } + return v +} + +// Deref is Indirect for reflect.Types +func Deref(t reflect.Type) reflect.Type { + if t.Kind() == reflect.Ptr { + t = t.Elem() + } + return t +} + +// -- helpers & utilities -- + +type kinder interface { + Kind() reflect.Kind +} + +// mustBe checks a value against a kind, panicing with a reflect.ValueError +// if the kind isn't that which is required. +func mustBe(v kinder, expected reflect.Kind) { + if k := v.Kind(); k != expected { + panic(&reflect.ValueError{Method: methodName(), Kind: k}) + } +} + +// methodName returns the caller of the function calling methodName +func methodName() string { + pc, _, _, _ := runtime.Caller(2) + f := runtime.FuncForPC(pc) + if f == nil { + return "unknown method" + } + return f.Name() +} + +type typeQueue struct { + t reflect.Type + fi *FieldInfo + pp string // Parent path +} + +// A copying append that creates a new slice each time. +func apnd(is []int, i int) []int { + x := make([]int, len(is)+1) + copy(x, is) + x[len(x)-1] = i + return x +} + +type mapf func(string) string + +// parseName parses the tag and the target name for the given field using +// the tagName (eg 'json' for `json:"foo"` tags), mapFunc for mapping the +// field's name to a target name, and tagMapFunc for mapping the tag to +// a target name. +func parseName(field reflect.StructField, tagName string, mapFunc, tagMapFunc mapf) (tag, fieldName string) { + // first, set the fieldName to the field's name + fieldName = field.Name + // if a mapFunc is set, use that to override the fieldName + if mapFunc != nil { + fieldName = mapFunc(fieldName) + } + + // if there's no tag to look for, return the field name + if tagName == "" { + return "", fieldName + } + + // if this tag is not set using the normal convention in the tag, + // then return the fieldname.. this check is done because according + // to the reflect documentation: + // If the tag does not have the conventional format, + // the value returned by Get is unspecified. + // which doesn't sound great. + if !strings.Contains(string(field.Tag), tagName+":") { + return "", fieldName + } + + // at this point we're fairly sure that we have a tag, so lets pull it out + tag = field.Tag.Get(tagName) + + // if we have a mapper function, call it on the whole tag + // XXX: this is a change from the old version, which pulled out the name + // before the tagMapFunc could be run, but I think this is the right way + if tagMapFunc != nil { + tag = tagMapFunc(tag) + } + + // finally, split the options from the name + parts := strings.Split(tag, ",") + fieldName = parts[0] + + return tag, fieldName +} + +// parseOptions parses options out of a tag string, skipping the name +func parseOptions(tag string) map[string]string { + parts := strings.Split(tag, ",") + options := make(map[string]string, len(parts)) + if len(parts) > 1 { + for _, opt := range parts[1:] { + // short circuit potentially expensive split op + if strings.Contains(opt, "=") { + kv := strings.Split(opt, "=") + options[kv[0]] = kv[1] + continue + } + options[opt] = "" + } + } + return options +} + +// getMapping returns a mapping for the t type, using the tagName, mapFunc and +// tagMapFunc to determine the canonical names of fields. +func getMapping(t reflect.Type, tagName string, mapFunc, tagMapFunc mapf) *StructMap { + m := []*FieldInfo{} + + root := &FieldInfo{} + queue := []typeQueue{} + queue = append(queue, typeQueue{Deref(t), root, ""}) + +QueueLoop: + for len(queue) != 0 { + // pop the first item off of the queue + tq := queue[0] + queue = queue[1:] + + // ignore recursive field + for p := tq.fi.Parent; p != nil; p = p.Parent { + if tq.fi.Field.Type == p.Field.Type { + continue QueueLoop + } + } + + nChildren := 0 + if tq.t.Kind() == reflect.Struct { + nChildren = tq.t.NumField() + } + tq.fi.Children = make([]*FieldInfo, nChildren) + + // iterate through all of its fields + for fieldPos := 0; fieldPos < nChildren; fieldPos++ { + + f := tq.t.Field(fieldPos) + + // parse the tag and the target name using the mapping options for this field + tag, name := parseName(f, tagName, mapFunc, tagMapFunc) + + // if the name is "-", disabled via a tag, skip it + if name == "-" { + continue + } + + fi := FieldInfo{ + Field: f, + Name: name, + Zero: reflect.New(f.Type).Elem(), + Options: parseOptions(tag), + } + + // if the path is empty this path is just the name + if tq.pp == "" { + fi.Path = fi.Name + } else { + fi.Path = tq.pp + "." + fi.Name + } + + // skip unexported fields + if len(f.PkgPath) != 0 && !f.Anonymous { + continue + } + + // bfs search of anonymous embedded structs + if f.Anonymous { + pp := tq.pp + if tag != "" { + pp = fi.Path + } + + fi.Embedded = true + fi.Index = apnd(tq.fi.Index, fieldPos) + nChildren := 0 + ft := Deref(f.Type) + if ft.Kind() == reflect.Struct { + nChildren = ft.NumField() + } + fi.Children = make([]*FieldInfo, nChildren) + queue = append(queue, typeQueue{Deref(f.Type), &fi, pp}) + } else if fi.Zero.Kind() == reflect.Struct || (fi.Zero.Kind() == reflect.Ptr && fi.Zero.Type().Elem().Kind() == reflect.Struct) { + fi.Index = apnd(tq.fi.Index, fieldPos) + fi.Children = make([]*FieldInfo, Deref(f.Type).NumField()) + queue = append(queue, typeQueue{Deref(f.Type), &fi, fi.Path}) + } + + fi.Index = apnd(tq.fi.Index, fieldPos) + fi.Parent = tq.fi + tq.fi.Children[fieldPos] = &fi + m = append(m, &fi) + } + } + + flds := &StructMap{Index: m, Tree: root, Paths: map[string]*FieldInfo{}, Names: map[string]*FieldInfo{}} + for _, fi := range flds.Index { + // check if nothing has already been pushed with the same path + // sometimes you can choose to override a type using embedded struct + fld, ok := flds.Paths[fi.Path] + if !ok || fld.Embedded { + flds.Paths[fi.Path] = fi + if fi.Name != "" && !fi.Embedded { + flds.Names[fi.Path] = fi + } + } + } + + return flds +} diff --git a/vendor/github.com/jmoiron/sqlx/sqlx.go b/vendor/github.com/jmoiron/sqlx/sqlx.go new file mode 100644 index 0000000..8259a4f --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/sqlx.go @@ -0,0 +1,1054 @@ +package sqlx + +import ( + "database/sql" + "database/sql/driver" + "errors" + "fmt" + "io/ioutil" + "path/filepath" + "reflect" + "strings" + "sync" + + "github.com/jmoiron/sqlx/reflectx" +) + +// Although the NameMapper is convenient, in practice it should not +// be relied on except for application code. If you are writing a library +// that uses sqlx, you should be aware that the name mappings you expect +// can be overridden by your user's application. + +// NameMapper is used to map column names to struct field names. By default, +// it uses strings.ToLower to lowercase struct field names. It can be set +// to whatever you want, but it is encouraged to be set before sqlx is used +// as name-to-field mappings are cached after first use on a type. +var NameMapper = strings.ToLower +var origMapper = reflect.ValueOf(NameMapper) + +// Rather than creating on init, this is created when necessary so that +// importers have time to customize the NameMapper. +var mpr *reflectx.Mapper + +// mprMu protects mpr. +var mprMu sync.Mutex + +// mapper returns a valid mapper using the configured NameMapper func. +func mapper() *reflectx.Mapper { + mprMu.Lock() + defer mprMu.Unlock() + + if mpr == nil { + mpr = reflectx.NewMapperFunc("db", NameMapper) + } else if origMapper != reflect.ValueOf(NameMapper) { + // if NameMapper has changed, create a new mapper + mpr = reflectx.NewMapperFunc("db", NameMapper) + origMapper = reflect.ValueOf(NameMapper) + } + return mpr +} + +// isScannable takes the reflect.Type and the actual dest value and returns +// whether or not it's Scannable. Something is scannable if: +// - it is not a struct +// - it implements sql.Scanner +// - it has no exported fields +func isScannable(t reflect.Type) bool { + if reflect.PtrTo(t).Implements(_scannerInterface) { + return true + } + if t.Kind() != reflect.Struct { + return true + } + + // it's not important that we use the right mapper for this particular object, + // we're only concerned on how many exported fields this struct has + return len(mapper().TypeMap(t).Index) == 0 +} + +// ColScanner is an interface used by MapScan and SliceScan +type ColScanner interface { + Columns() ([]string, error) + Scan(dest ...interface{}) error + Err() error +} + +// Queryer is an interface used by Get and Select +type Queryer interface { + Query(query string, args ...interface{}) (*sql.Rows, error) + Queryx(query string, args ...interface{}) (*Rows, error) + QueryRowx(query string, args ...interface{}) *Row +} + +// Execer is an interface used by MustExec and LoadFile +type Execer interface { + Exec(query string, args ...interface{}) (sql.Result, error) +} + +// Binder is an interface for something which can bind queries (Tx, DB) +type binder interface { + DriverName() string + Rebind(string) string + BindNamed(string, interface{}) (string, []interface{}, error) +} + +// Ext is a union interface which can bind, query, and exec, used by +// NamedQuery and NamedExec. +type Ext interface { + binder + Queryer + Execer +} + +// Preparer is an interface used by Preparex. +type Preparer interface { + Prepare(query string) (*sql.Stmt, error) +} + +// determine if any of our extensions are unsafe +func isUnsafe(i interface{}) bool { + switch v := i.(type) { + case Row: + return v.unsafe + case *Row: + return v.unsafe + case Rows: + return v.unsafe + case *Rows: + return v.unsafe + case NamedStmt: + return v.Stmt.unsafe + case *NamedStmt: + return v.Stmt.unsafe + case Stmt: + return v.unsafe + case *Stmt: + return v.unsafe + case qStmt: + return v.unsafe + case *qStmt: + return v.unsafe + case DB: + return v.unsafe + case *DB: + return v.unsafe + case Tx: + return v.unsafe + case *Tx: + return v.unsafe + case sql.Rows, *sql.Rows: + return false + default: + return false + } +} + +func mapperFor(i interface{}) *reflectx.Mapper { + switch i := i.(type) { + case DB: + return i.Mapper + case *DB: + return i.Mapper + case Tx: + return i.Mapper + case *Tx: + return i.Mapper + default: + return mapper() + } +} + +var _scannerInterface = reflect.TypeOf((*sql.Scanner)(nil)).Elem() + +//lint:ignore U1000 ignoring this for now +var _valuerInterface = reflect.TypeOf((*driver.Valuer)(nil)).Elem() + +// Row is a reimplementation of sql.Row in order to gain access to the underlying +// sql.Rows.Columns() data, necessary for StructScan. +type Row struct { + err error + unsafe bool + rows *sql.Rows + Mapper *reflectx.Mapper +} + +// Scan is a fixed implementation of sql.Row.Scan, which does not discard the +// underlying error from the internal rows object if it exists. +func (r *Row) Scan(dest ...interface{}) error { + if r.err != nil { + return r.err + } + + // TODO(bradfitz): for now we need to defensively clone all + // []byte that the driver returned (not permitting + // *RawBytes in Rows.Scan), since we're about to close + // the Rows in our defer, when we return from this function. + // the contract with the driver.Next(...) interface is that it + // can return slices into read-only temporary memory that's + // only valid until the next Scan/Close. But the TODO is that + // for a lot of drivers, this copy will be unnecessary. We + // should provide an optional interface for drivers to + // implement to say, "don't worry, the []bytes that I return + // from Next will not be modified again." (for instance, if + // they were obtained from the network anyway) But for now we + // don't care. + defer r.rows.Close() + for _, dp := range dest { + if _, ok := dp.(*sql.RawBytes); ok { + return errors.New("sql: RawBytes isn't allowed on Row.Scan") + } + } + + if !r.rows.Next() { + if err := r.rows.Err(); err != nil { + return err + } + return sql.ErrNoRows + } + err := r.rows.Scan(dest...) + if err != nil { + return err + } + // Make sure the query can be processed to completion with no errors. + if err := r.rows.Close(); err != nil { + return err + } + return nil +} + +// Columns returns the underlying sql.Rows.Columns(), or the deferred error usually +// returned by Row.Scan() +func (r *Row) Columns() ([]string, error) { + if r.err != nil { + return []string{}, r.err + } + return r.rows.Columns() +} + +// ColumnTypes returns the underlying sql.Rows.ColumnTypes(), or the deferred error +func (r *Row) ColumnTypes() ([]*sql.ColumnType, error) { + if r.err != nil { + return []*sql.ColumnType{}, r.err + } + return r.rows.ColumnTypes() +} + +// Err returns the error encountered while scanning. +func (r *Row) Err() error { + return r.err +} + +// DB is a wrapper around sql.DB which keeps track of the driverName upon Open, +// used mostly to automatically bind named queries using the right bindvars. +type DB struct { + *sql.DB + driverName string + unsafe bool + Mapper *reflectx.Mapper +} + +// NewDb returns a new sqlx DB wrapper for a pre-existing *sql.DB. The +// driverName of the original database is required for named query support. +// +//lint:ignore ST1003 changing this would break the package interface. +func NewDb(db *sql.DB, driverName string) *DB { + return &DB{DB: db, driverName: driverName, Mapper: mapper()} +} + +// DriverName returns the driverName passed to the Open function for this DB. +func (db *DB) DriverName() string { + return db.driverName +} + +// Open is the same as sql.Open, but returns an *sqlx.DB instead. +func Open(driverName, dataSourceName string) (*DB, error) { + db, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return &DB{DB: db, driverName: driverName, Mapper: mapper()}, err +} + +// MustOpen is the same as sql.Open, but returns an *sqlx.DB instead and panics on error. +func MustOpen(driverName, dataSourceName string) *DB { + db, err := Open(driverName, dataSourceName) + if err != nil { + panic(err) + } + return db +} + +// MapperFunc sets a new mapper for this db using the default sqlx struct tag +// and the provided mapper function. +func (db *DB) MapperFunc(mf func(string) string) { + db.Mapper = reflectx.NewMapperFunc("db", mf) +} + +// Rebind transforms a query from QUESTION to the DB driver's bindvar type. +func (db *DB) Rebind(query string) string { + return Rebind(BindType(db.driverName), query) +} + +// Unsafe returns a version of DB which will silently succeed to scan when +// columns in the SQL result have no fields in the destination struct. +// sqlx.Stmt and sqlx.Tx which are created from this DB will inherit its +// safety behavior. +func (db *DB) Unsafe() *DB { + return &DB{DB: db.DB, driverName: db.driverName, unsafe: true, Mapper: db.Mapper} +} + +// BindNamed binds a query using the DB driver's bindvar type. +func (db *DB) BindNamed(query string, arg interface{}) (string, []interface{}, error) { + return bindNamedMapper(BindType(db.driverName), query, arg, db.Mapper) +} + +// NamedQuery using this DB. +// Any named placeholder parameters are replaced with fields from arg. +func (db *DB) NamedQuery(query string, arg interface{}) (*Rows, error) { + return NamedQuery(db, query, arg) +} + +// NamedExec using this DB. +// Any named placeholder parameters are replaced with fields from arg. +func (db *DB) NamedExec(query string, arg interface{}) (sql.Result, error) { + return NamedExec(db, query, arg) +} + +// Select using this DB. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) Select(dest interface{}, query string, args ...interface{}) error { + return Select(db, dest, query, args...) +} + +// Get using this DB. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (db *DB) Get(dest interface{}, query string, args ...interface{}) error { + return Get(db, dest, query, args...) +} + +// MustBegin starts a transaction, and panics on error. Returns an *sqlx.Tx instead +// of an *sql.Tx. +func (db *DB) MustBegin() *Tx { + tx, err := db.Beginx() + if err != nil { + panic(err) + } + return tx +} + +// Beginx begins a transaction and returns an *sqlx.Tx instead of an *sql.Tx. +func (db *DB) Beginx() (*Tx, error) { + tx, err := db.DB.Begin() + if err != nil { + return nil, err + } + return &Tx{Tx: tx, driverName: db.driverName, unsafe: db.unsafe, Mapper: db.Mapper}, err +} + +// Queryx queries the database and returns an *sqlx.Rows. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) Queryx(query string, args ...interface{}) (*Rows, error) { + r, err := db.DB.Query(query, args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: db.unsafe, Mapper: db.Mapper}, err +} + +// QueryRowx queries the database and returns an *sqlx.Row. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) QueryRowx(query string, args ...interface{}) *Row { + rows, err := db.DB.Query(query, args...) + return &Row{rows: rows, err: err, unsafe: db.unsafe, Mapper: db.Mapper} +} + +// MustExec (panic) runs MustExec using this database. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) MustExec(query string, args ...interface{}) sql.Result { + return MustExec(db, query, args...) +} + +// Preparex returns an sqlx.Stmt instead of a sql.Stmt +func (db *DB) Preparex(query string) (*Stmt, error) { + return Preparex(db, query) +} + +// PrepareNamed returns an sqlx.NamedStmt +func (db *DB) PrepareNamed(query string) (*NamedStmt, error) { + return prepareNamed(db, query) +} + +// Conn is a wrapper around sql.Conn with extra functionality +type Conn struct { + *sql.Conn + driverName string + unsafe bool + Mapper *reflectx.Mapper +} + +// Tx is an sqlx wrapper around sql.Tx with extra functionality +type Tx struct { + *sql.Tx + driverName string + unsafe bool + Mapper *reflectx.Mapper +} + +// DriverName returns the driverName used by the DB which began this transaction. +func (tx *Tx) DriverName() string { + return tx.driverName +} + +// Rebind a query within a transaction's bindvar type. +func (tx *Tx) Rebind(query string) string { + return Rebind(BindType(tx.driverName), query) +} + +// Unsafe returns a version of Tx which will silently succeed to scan when +// columns in the SQL result have no fields in the destination struct. +func (tx *Tx) Unsafe() *Tx { + return &Tx{Tx: tx.Tx, driverName: tx.driverName, unsafe: true, Mapper: tx.Mapper} +} + +// BindNamed binds a query within a transaction's bindvar type. +func (tx *Tx) BindNamed(query string, arg interface{}) (string, []interface{}, error) { + return bindNamedMapper(BindType(tx.driverName), query, arg, tx.Mapper) +} + +// NamedQuery within a transaction. +// Any named placeholder parameters are replaced with fields from arg. +func (tx *Tx) NamedQuery(query string, arg interface{}) (*Rows, error) { + return NamedQuery(tx, query, arg) +} + +// NamedExec a named query within a transaction. +// Any named placeholder parameters are replaced with fields from arg. +func (tx *Tx) NamedExec(query string, arg interface{}) (sql.Result, error) { + return NamedExec(tx, query, arg) +} + +// Select within a transaction. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) Select(dest interface{}, query string, args ...interface{}) error { + return Select(tx, dest, query, args...) +} + +// Queryx within a transaction. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) Queryx(query string, args ...interface{}) (*Rows, error) { + r, err := tx.Tx.Query(query, args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: tx.unsafe, Mapper: tx.Mapper}, err +} + +// QueryRowx within a transaction. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) QueryRowx(query string, args ...interface{}) *Row { + rows, err := tx.Tx.Query(query, args...) + return &Row{rows: rows, err: err, unsafe: tx.unsafe, Mapper: tx.Mapper} +} + +// Get within a transaction. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (tx *Tx) Get(dest interface{}, query string, args ...interface{}) error { + return Get(tx, dest, query, args...) +} + +// MustExec runs MustExec within a transaction. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) MustExec(query string, args ...interface{}) sql.Result { + return MustExec(tx, query, args...) +} + +// Preparex a statement within a transaction. +func (tx *Tx) Preparex(query string) (*Stmt, error) { + return Preparex(tx, query) +} + +// Stmtx returns a version of the prepared statement which runs within a transaction. Provided +// stmt can be either *sql.Stmt or *sqlx.Stmt. +func (tx *Tx) Stmtx(stmt interface{}) *Stmt { + var s *sql.Stmt + switch v := stmt.(type) { + case Stmt: + s = v.Stmt + case *Stmt: + s = v.Stmt + case *sql.Stmt: + s = v + default: + panic(fmt.Sprintf("non-statement type %v passed to Stmtx", reflect.ValueOf(stmt).Type())) + } + return &Stmt{Stmt: tx.Stmt(s), Mapper: tx.Mapper} +} + +// NamedStmt returns a version of the prepared statement which runs within a transaction. +func (tx *Tx) NamedStmt(stmt *NamedStmt) *NamedStmt { + return &NamedStmt{ + QueryString: stmt.QueryString, + Params: stmt.Params, + Stmt: tx.Stmtx(stmt.Stmt), + } +} + +// PrepareNamed returns an sqlx.NamedStmt +func (tx *Tx) PrepareNamed(query string) (*NamedStmt, error) { + return prepareNamed(tx, query) +} + +// Stmt is an sqlx wrapper around sql.Stmt with extra functionality +type Stmt struct { + *sql.Stmt + unsafe bool + Mapper *reflectx.Mapper +} + +// Unsafe returns a version of Stmt which will silently succeed to scan when +// columns in the SQL result have no fields in the destination struct. +func (s *Stmt) Unsafe() *Stmt { + return &Stmt{Stmt: s.Stmt, unsafe: true, Mapper: s.Mapper} +} + +// Select using the prepared statement. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) Select(dest interface{}, args ...interface{}) error { + return Select(&qStmt{s}, dest, "", args...) +} + +// Get using the prepared statement. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (s *Stmt) Get(dest interface{}, args ...interface{}) error { + return Get(&qStmt{s}, dest, "", args...) +} + +// MustExec (panic) using this statement. Note that the query portion of the error +// output will be blank, as Stmt does not expose its query. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) MustExec(args ...interface{}) sql.Result { + return MustExec(&qStmt{s}, "", args...) +} + +// QueryRowx using this statement. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) QueryRowx(args ...interface{}) *Row { + qs := &qStmt{s} + return qs.QueryRowx("", args...) +} + +// Queryx using this statement. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) Queryx(args ...interface{}) (*Rows, error) { + qs := &qStmt{s} + return qs.Queryx("", args...) +} + +// qStmt is an unexposed wrapper which lets you use a Stmt as a Queryer & Execer by +// implementing those interfaces and ignoring the `query` argument. +type qStmt struct{ *Stmt } + +func (q *qStmt) Query(query string, args ...interface{}) (*sql.Rows, error) { + return q.Stmt.Query(args...) +} + +func (q *qStmt) Queryx(query string, args ...interface{}) (*Rows, error) { + r, err := q.Stmt.Query(args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper}, err +} + +func (q *qStmt) QueryRowx(query string, args ...interface{}) *Row { + rows, err := q.Stmt.Query(args...) + return &Row{rows: rows, err: err, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper} +} + +func (q *qStmt) Exec(query string, args ...interface{}) (sql.Result, error) { + return q.Stmt.Exec(args...) +} + +// Rows is a wrapper around sql.Rows which caches costly reflect operations +// during a looped StructScan +type Rows struct { + *sql.Rows + unsafe bool + Mapper *reflectx.Mapper + // these fields cache memory use for a rows during iteration w/ structScan + started bool + fields [][]int + values []interface{} +} + +// SliceScan using this Rows. +func (r *Rows) SliceScan() ([]interface{}, error) { + return SliceScan(r) +} + +// MapScan using this Rows. +func (r *Rows) MapScan(dest map[string]interface{}) error { + return MapScan(r, dest) +} + +// StructScan is like sql.Rows.Scan, but scans a single Row into a single Struct. +// Use this and iterate over Rows manually when the memory load of Select() might be +// prohibitive. *Rows.StructScan caches the reflect work of matching up column +// positions to fields to avoid that overhead per scan, which means it is not safe +// to run StructScan on the same Rows instance with different struct types. +func (r *Rows) StructScan(dest interface{}) error { + v := reflect.ValueOf(dest) + + if v.Kind() != reflect.Ptr { + return errors.New("must pass a pointer, not a value, to StructScan destination") + } + + v = v.Elem() + + if !r.started { + columns, err := r.Columns() + if err != nil { + return err + } + m := r.Mapper + + r.fields = m.TraversalsByName(v.Type(), columns) + // if we are not unsafe and are missing fields, return an error + if f, err := missingFields(r.fields); err != nil && !r.unsafe { + return fmt.Errorf("missing destination name %s in %T", columns[f], dest) + } + r.values = make([]interface{}, len(columns)) + r.started = true + } + + err := fieldsByTraversal(v, r.fields, r.values, true) + if err != nil { + return err + } + // scan into the struct field pointers and append to our results + err = r.Scan(r.values...) + if err != nil { + return err + } + return r.Err() +} + +// Connect to a database and verify with a ping. +func Connect(driverName, dataSourceName string) (*DB, error) { + db, err := Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + err = db.Ping() + if err != nil { + db.Close() + return nil, err + } + return db, nil +} + +// MustConnect connects to a database and panics on error. +func MustConnect(driverName, dataSourceName string) *DB { + db, err := Connect(driverName, dataSourceName) + if err != nil { + panic(err) + } + return db +} + +// Preparex prepares a statement. +func Preparex(p Preparer, query string) (*Stmt, error) { + s, err := p.Prepare(query) + if err != nil { + return nil, err + } + return &Stmt{Stmt: s, unsafe: isUnsafe(p), Mapper: mapperFor(p)}, err +} + +// Select executes a query using the provided Queryer, and StructScans each row +// into dest, which must be a slice. If the slice elements are scannable, then +// the result set must have only one column. Otherwise, StructScan is used. +// The *sql.Rows are closed automatically. +// Any placeholder parameters are replaced with supplied args. +func Select(q Queryer, dest interface{}, query string, args ...interface{}) error { + rows, err := q.Queryx(query, args...) + if err != nil { + return err + } + // if something happens here, we want to make sure the rows are Closed + defer rows.Close() + return scanAll(rows, dest, false) +} + +// Get does a QueryRow using the provided Queryer, and scans the resulting row +// to dest. If dest is scannable, the result must only have one column. Otherwise, +// StructScan is used. Get will return sql.ErrNoRows like row.Scan would. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func Get(q Queryer, dest interface{}, query string, args ...interface{}) error { + r := q.QueryRowx(query, args...) + return r.scanAny(dest, false) +} + +// LoadFile exec's every statement in a file (as a single call to Exec). +// LoadFile may return a nil *sql.Result if errors are encountered locating or +// reading the file at path. LoadFile reads the entire file into memory, so it +// is not suitable for loading large data dumps, but can be useful for initializing +// schemas or loading indexes. +// +// FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 +// or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting +// this by requiring something with DriverName() and then attempting to split the +// queries will be difficult to get right, and its current driver-specific behavior +// is deemed at least not complex in its incorrectness. +func LoadFile(e Execer, path string) (*sql.Result, error) { + realpath, err := filepath.Abs(path) + if err != nil { + return nil, err + } + contents, err := ioutil.ReadFile(realpath) + if err != nil { + return nil, err + } + res, err := e.Exec(string(contents)) + return &res, err +} + +// MustExec execs the query using e and panics if there was an error. +// Any placeholder parameters are replaced with supplied args. +func MustExec(e Execer, query string, args ...interface{}) sql.Result { + res, err := e.Exec(query, args...) + if err != nil { + panic(err) + } + return res +} + +// SliceScan using this Rows. +func (r *Row) SliceScan() ([]interface{}, error) { + return SliceScan(r) +} + +// MapScan using this Rows. +func (r *Row) MapScan(dest map[string]interface{}) error { + return MapScan(r, dest) +} + +func (r *Row) scanAny(dest interface{}, structOnly bool) error { + if r.err != nil { + return r.err + } + if r.rows == nil { + r.err = sql.ErrNoRows + return r.err + } + defer r.rows.Close() + + v := reflect.ValueOf(dest) + if v.Kind() != reflect.Ptr { + return errors.New("must pass a pointer, not a value, to StructScan destination") + } + if v.IsNil() { + return errors.New("nil pointer passed to StructScan destination") + } + + base := reflectx.Deref(v.Type()) + scannable := isScannable(base) + + if structOnly && scannable { + return structOnlyError(base) + } + + columns, err := r.Columns() + if err != nil { + return err + } + + if scannable && len(columns) > 1 { + return fmt.Errorf("scannable dest type %s with >1 columns (%d) in result", base.Kind(), len(columns)) + } + + if scannable { + return r.Scan(dest) + } + + m := r.Mapper + + fields := m.TraversalsByName(v.Type(), columns) + // if we are not unsafe and are missing fields, return an error + if f, err := missingFields(fields); err != nil && !r.unsafe { + return fmt.Errorf("missing destination name %s in %T", columns[f], dest) + } + values := make([]interface{}, len(columns)) + + err = fieldsByTraversal(v, fields, values, true) + if err != nil { + return err + } + // scan into the struct field pointers and append to our results + return r.Scan(values...) +} + +// StructScan a single Row into dest. +func (r *Row) StructScan(dest interface{}) error { + return r.scanAny(dest, true) +} + +// SliceScan a row, returning a []interface{} with values similar to MapScan. +// This function is primarily intended for use where the number of columns +// is not known. Because you can pass an []interface{} directly to Scan, +// it's recommended that you do that as it will not have to allocate new +// slices per row. +func SliceScan(r ColScanner) ([]interface{}, error) { + // ignore r.started, since we needn't use reflect for anything. + columns, err := r.Columns() + if err != nil { + return []interface{}{}, err + } + + values := make([]interface{}, len(columns)) + for i := range values { + values[i] = new(interface{}) + } + + err = r.Scan(values...) + + if err != nil { + return values, err + } + + for i := range columns { + values[i] = *(values[i].(*interface{})) + } + + return values, r.Err() +} + +// MapScan scans a single Row into the dest map[string]interface{}. +// Use this to get results for SQL that might not be under your control +// (for instance, if you're building an interface for an SQL server that +// executes SQL from input). Please do not use this as a primary interface! +// This will modify the map sent to it in place, so reuse the same map with +// care. Columns which occur more than once in the result will overwrite +// each other! +func MapScan(r ColScanner, dest map[string]interface{}) error { + // ignore r.started, since we needn't use reflect for anything. + columns, err := r.Columns() + if err != nil { + return err + } + + values := make([]interface{}, len(columns)) + for i := range values { + values[i] = new(interface{}) + } + + err = r.Scan(values...) + if err != nil { + return err + } + + for i, column := range columns { + dest[column] = *(values[i].(*interface{})) + } + + return r.Err() +} + +type rowsi interface { + Close() error + Columns() ([]string, error) + Err() error + Next() bool + Scan(...interface{}) error +} + +// structOnlyError returns an error appropriate for type when a non-scannable +// struct is expected but something else is given +func structOnlyError(t reflect.Type) error { + isStruct := t.Kind() == reflect.Struct + isScanner := reflect.PtrTo(t).Implements(_scannerInterface) + if !isStruct { + return fmt.Errorf("expected %s but got %s", reflect.Struct, t.Kind()) + } + if isScanner { + return fmt.Errorf("structscan expects a struct dest but the provided struct type %s implements scanner", t.Name()) + } + return fmt.Errorf("expected a struct, but struct %s has no exported fields", t.Name()) +} + +// scanAll scans all rows into a destination, which must be a slice of any +// type. It resets the slice length to zero before appending each element to +// the slice. If the destination slice type is a Struct, then StructScan will +// be used on each row. If the destination is some other kind of base type, +// then each row must only have one column which can scan into that type. This +// allows you to do something like: +// +// rows, _ := db.Query("select id from people;") +// var ids []int +// scanAll(rows, &ids, false) +// +// and ids will be a list of the id results. I realize that this is a desirable +// interface to expose to users, but for now it will only be exposed via changes +// to `Get` and `Select`. The reason that this has been implemented like this is +// this is the only way to not duplicate reflect work in the new API while +// maintaining backwards compatibility. +func scanAll(rows rowsi, dest interface{}, structOnly bool) error { + var v, vp reflect.Value + + value := reflect.ValueOf(dest) + + // json.Unmarshal returns errors for these + if value.Kind() != reflect.Ptr { + return errors.New("must pass a pointer, not a value, to StructScan destination") + } + if value.IsNil() { + return errors.New("nil pointer passed to StructScan destination") + } + direct := reflect.Indirect(value) + + slice, err := baseType(value.Type(), reflect.Slice) + if err != nil { + return err + } + direct.SetLen(0) + + isPtr := slice.Elem().Kind() == reflect.Ptr + base := reflectx.Deref(slice.Elem()) + scannable := isScannable(base) + + if structOnly && scannable { + return structOnlyError(base) + } + + columns, err := rows.Columns() + if err != nil { + return err + } + + // if it's a base type make sure it only has 1 column; if not return an error + if scannable && len(columns) > 1 { + return fmt.Errorf("non-struct dest type %s with >1 columns (%d)", base.Kind(), len(columns)) + } + + if !scannable { + var values []interface{} + var m *reflectx.Mapper + + switch rows := rows.(type) { + case *Rows: + m = rows.Mapper + default: + m = mapper() + } + + fields := m.TraversalsByName(base, columns) + // if we are not unsafe and are missing fields, return an error + if f, err := missingFields(fields); err != nil && !isUnsafe(rows) { + return fmt.Errorf("missing destination name %s in %T", columns[f], dest) + } + values = make([]interface{}, len(columns)) + + for rows.Next() { + // create a new struct type (which returns PtrTo) and indirect it + vp = reflect.New(base) + v = reflect.Indirect(vp) + + err = fieldsByTraversal(v, fields, values, true) + if err != nil { + return err + } + + // scan into the struct field pointers and append to our results + err = rows.Scan(values...) + if err != nil { + return err + } + + if isPtr { + direct.Set(reflect.Append(direct, vp)) + } else { + direct.Set(reflect.Append(direct, v)) + } + } + } else { + for rows.Next() { + vp = reflect.New(base) + err = rows.Scan(vp.Interface()) + if err != nil { + return err + } + // append + if isPtr { + direct.Set(reflect.Append(direct, vp)) + } else { + direct.Set(reflect.Append(direct, reflect.Indirect(vp))) + } + } + } + + return rows.Err() +} + +// FIXME: StructScan was the very first bit of API in sqlx, and now unfortunately +// it doesn't really feel like it's named properly. There is an incongruency +// between this and the way that StructScan (which might better be ScanStruct +// anyway) works on a rows object. + +// StructScan all rows from an sql.Rows or an sqlx.Rows into the dest slice. +// StructScan will scan in the entire rows result, so if you do not want to +// allocate structs for the entire result, use Queryx and see sqlx.Rows.StructScan. +// If rows is sqlx.Rows, it will use its mapper, otherwise it will use the default. +func StructScan(rows rowsi, dest interface{}) error { + return scanAll(rows, dest, true) + +} + +// reflect helpers + +func baseType(t reflect.Type, expected reflect.Kind) (reflect.Type, error) { + t = reflectx.Deref(t) + if t.Kind() != expected { + return nil, fmt.Errorf("expected %s but got %s", expected, t.Kind()) + } + return t, nil +} + +// fieldsByName fills a values interface with fields from the passed value based +// on the traversals in int. If ptrs is true, return addresses instead of values. +// We write this instead of using FieldsByName to save allocations and map lookups +// when iterating over many rows. Empty traversals will get an interface pointer. +// Because of the necessity of requesting ptrs or values, it's considered a bit too +// specialized for inclusion in reflectx itself. +func fieldsByTraversal(v reflect.Value, traversals [][]int, values []interface{}, ptrs bool) error { + v = reflect.Indirect(v) + if v.Kind() != reflect.Struct { + return errors.New("argument not a struct") + } + + for i, traversal := range traversals { + if len(traversal) == 0 { + values[i] = new(interface{}) + continue + } + f := reflectx.FieldByIndexes(v, traversal) + if ptrs { + values[i] = f.Addr().Interface() + } else { + values[i] = f.Interface() + } + } + return nil +} + +func missingFields(transversals [][]int) (field int, err error) { + for i, t := range transversals { + if len(t) == 0 { + return i, errors.New("missing field") + } + } + return 0, nil +} diff --git a/vendor/github.com/jmoiron/sqlx/sqlx_context.go b/vendor/github.com/jmoiron/sqlx/sqlx_context.go new file mode 100644 index 0000000..32621d5 --- /dev/null +++ b/vendor/github.com/jmoiron/sqlx/sqlx_context.go @@ -0,0 +1,415 @@ +//go:build go1.8 +// +build go1.8 + +package sqlx + +import ( + "context" + "database/sql" + "fmt" + "io/ioutil" + "path/filepath" + "reflect" +) + +// ConnectContext to a database and verify with a ping. +func ConnectContext(ctx context.Context, driverName, dataSourceName string) (*DB, error) { + db, err := Open(driverName, dataSourceName) + if err != nil { + return db, err + } + err = db.PingContext(ctx) + return db, err +} + +// QueryerContext is an interface used by GetContext and SelectContext +type QueryerContext interface { + QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) + QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) + QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row +} + +// PreparerContext is an interface used by PreparexContext. +type PreparerContext interface { + PrepareContext(ctx context.Context, query string) (*sql.Stmt, error) +} + +// ExecerContext is an interface used by MustExecContext and LoadFileContext +type ExecerContext interface { + ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) +} + +// ExtContext is a union interface which can bind, query, and exec, with Context +// used by NamedQueryContext and NamedExecContext. +type ExtContext interface { + binder + QueryerContext + ExecerContext +} + +// SelectContext executes a query using the provided Queryer, and StructScans +// each row into dest, which must be a slice. If the slice elements are +// scannable, then the result set must have only one column. Otherwise, +// StructScan is used. The *sql.Rows are closed automatically. +// Any placeholder parameters are replaced with supplied args. +func SelectContext(ctx context.Context, q QueryerContext, dest interface{}, query string, args ...interface{}) error { + rows, err := q.QueryxContext(ctx, query, args...) + if err != nil { + return err + } + // if something happens here, we want to make sure the rows are Closed + defer rows.Close() + return scanAll(rows, dest, false) +} + +// PreparexContext prepares a statement. +// +// The provided context is used for the preparation of the statement, not for +// the execution of the statement. +func PreparexContext(ctx context.Context, p PreparerContext, query string) (*Stmt, error) { + s, err := p.PrepareContext(ctx, query) + if err != nil { + return nil, err + } + return &Stmt{Stmt: s, unsafe: isUnsafe(p), Mapper: mapperFor(p)}, err +} + +// GetContext does a QueryRow using the provided Queryer, and scans the +// resulting row to dest. If dest is scannable, the result must only have one +// column. Otherwise, StructScan is used. Get will return sql.ErrNoRows like +// row.Scan would. Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func GetContext(ctx context.Context, q QueryerContext, dest interface{}, query string, args ...interface{}) error { + r := q.QueryRowxContext(ctx, query, args...) + return r.scanAny(dest, false) +} + +// LoadFileContext exec's every statement in a file (as a single call to Exec). +// LoadFileContext may return a nil *sql.Result if errors are encountered +// locating or reading the file at path. LoadFile reads the entire file into +// memory, so it is not suitable for loading large data dumps, but can be useful +// for initializing schemas or loading indexes. +// +// FIXME: this does not really work with multi-statement files for mattn/go-sqlite3 +// or the go-mysql-driver/mysql drivers; pq seems to be an exception here. Detecting +// this by requiring something with DriverName() and then attempting to split the +// queries will be difficult to get right, and its current driver-specific behavior +// is deemed at least not complex in its incorrectness. +func LoadFileContext(ctx context.Context, e ExecerContext, path string) (*sql.Result, error) { + realpath, err := filepath.Abs(path) + if err != nil { + return nil, err + } + contents, err := ioutil.ReadFile(realpath) + if err != nil { + return nil, err + } + res, err := e.ExecContext(ctx, string(contents)) + return &res, err +} + +// MustExecContext execs the query using e and panics if there was an error. +// Any placeholder parameters are replaced with supplied args. +func MustExecContext(ctx context.Context, e ExecerContext, query string, args ...interface{}) sql.Result { + res, err := e.ExecContext(ctx, query, args...) + if err != nil { + panic(err) + } + return res +} + +// PrepareNamedContext returns an sqlx.NamedStmt +func (db *DB) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error) { + return prepareNamedContext(ctx, db, query) +} + +// NamedQueryContext using this DB. +// Any named placeholder parameters are replaced with fields from arg. +func (db *DB) NamedQueryContext(ctx context.Context, query string, arg interface{}) (*Rows, error) { + return NamedQueryContext(ctx, db, query, arg) +} + +// NamedExecContext using this DB. +// Any named placeholder parameters are replaced with fields from arg. +func (db *DB) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) { + return NamedExecContext(ctx, db, query, arg) +} + +// SelectContext using this DB. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return SelectContext(ctx, db, dest, query, args...) +} + +// GetContext using this DB. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (db *DB) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return GetContext(ctx, db, dest, query, args...) +} + +// PreparexContext returns an sqlx.Stmt instead of a sql.Stmt. +// +// The provided context is used for the preparation of the statement, not for +// the execution of the statement. +func (db *DB) PreparexContext(ctx context.Context, query string) (*Stmt, error) { + return PreparexContext(ctx, db, query) +} + +// QueryxContext queries the database and returns an *sqlx.Rows. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { + r, err := db.DB.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: db.unsafe, Mapper: db.Mapper}, err +} + +// QueryRowxContext queries the database and returns an *sqlx.Row. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { + rows, err := db.DB.QueryContext(ctx, query, args...) + return &Row{rows: rows, err: err, unsafe: db.unsafe, Mapper: db.Mapper} +} + +// MustBeginTx starts a transaction, and panics on error. Returns an *sqlx.Tx instead +// of an *sql.Tx. +// +// The provided context is used until the transaction is committed or rolled +// back. If the context is canceled, the sql package will roll back the +// transaction. Tx.Commit will return an error if the context provided to +// MustBeginContext is canceled. +func (db *DB) MustBeginTx(ctx context.Context, opts *sql.TxOptions) *Tx { + tx, err := db.BeginTxx(ctx, opts) + if err != nil { + panic(err) + } + return tx +} + +// MustExecContext (panic) runs MustExec using this database. +// Any placeholder parameters are replaced with supplied args. +func (db *DB) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result { + return MustExecContext(ctx, db, query, args...) +} + +// BeginTxx begins a transaction and returns an *sqlx.Tx instead of an +// *sql.Tx. +// +// The provided context is used until the transaction is committed or rolled +// back. If the context is canceled, the sql package will roll back the +// transaction. Tx.Commit will return an error if the context provided to +// BeginxContext is canceled. +func (db *DB) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + tx, err := db.DB.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + return &Tx{Tx: tx, driverName: db.driverName, unsafe: db.unsafe, Mapper: db.Mapper}, err +} + +// Connx returns an *sqlx.Conn instead of an *sql.Conn. +func (db *DB) Connx(ctx context.Context) (*Conn, error) { + conn, err := db.DB.Conn(ctx) + if err != nil { + return nil, err + } + + return &Conn{Conn: conn, driverName: db.driverName, unsafe: db.unsafe, Mapper: db.Mapper}, nil +} + +// BeginTxx begins a transaction and returns an *sqlx.Tx instead of an +// *sql.Tx. +// +// The provided context is used until the transaction is committed or rolled +// back. If the context is canceled, the sql package will roll back the +// transaction. Tx.Commit will return an error if the context provided to +// BeginxContext is canceled. +func (c *Conn) BeginTxx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + tx, err := c.Conn.BeginTx(ctx, opts) + if err != nil { + return nil, err + } + return &Tx{Tx: tx, driverName: c.driverName, unsafe: c.unsafe, Mapper: c.Mapper}, err +} + +// SelectContext using this Conn. +// Any placeholder parameters are replaced with supplied args. +func (c *Conn) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return SelectContext(ctx, c, dest, query, args...) +} + +// GetContext using this Conn. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (c *Conn) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return GetContext(ctx, c, dest, query, args...) +} + +// PreparexContext returns an sqlx.Stmt instead of a sql.Stmt. +// +// The provided context is used for the preparation of the statement, not for +// the execution of the statement. +func (c *Conn) PreparexContext(ctx context.Context, query string) (*Stmt, error) { + return PreparexContext(ctx, c, query) +} + +// QueryxContext queries the database and returns an *sqlx.Rows. +// Any placeholder parameters are replaced with supplied args. +func (c *Conn) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { + r, err := c.Conn.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: c.unsafe, Mapper: c.Mapper}, err +} + +// QueryRowxContext queries the database and returns an *sqlx.Row. +// Any placeholder parameters are replaced with supplied args. +func (c *Conn) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { + rows, err := c.Conn.QueryContext(ctx, query, args...) + return &Row{rows: rows, err: err, unsafe: c.unsafe, Mapper: c.Mapper} +} + +// Rebind a query within a Conn's bindvar type. +func (c *Conn) Rebind(query string) string { + return Rebind(BindType(c.driverName), query) +} + +// StmtxContext returns a version of the prepared statement which runs within a +// transaction. Provided stmt can be either *sql.Stmt or *sqlx.Stmt. +func (tx *Tx) StmtxContext(ctx context.Context, stmt interface{}) *Stmt { + var s *sql.Stmt + switch v := stmt.(type) { + case Stmt: + s = v.Stmt + case *Stmt: + s = v.Stmt + case *sql.Stmt: + s = v + default: + panic(fmt.Sprintf("non-statement type %v passed to Stmtx", reflect.ValueOf(stmt).Type())) + } + return &Stmt{Stmt: tx.StmtContext(ctx, s), Mapper: tx.Mapper} +} + +// NamedStmtContext returns a version of the prepared statement which runs +// within a transaction. +func (tx *Tx) NamedStmtContext(ctx context.Context, stmt *NamedStmt) *NamedStmt { + return &NamedStmt{ + QueryString: stmt.QueryString, + Params: stmt.Params, + Stmt: tx.StmtxContext(ctx, stmt.Stmt), + } +} + +// PreparexContext returns an sqlx.Stmt instead of a sql.Stmt. +// +// The provided context is used for the preparation of the statement, not for +// the execution of the statement. +func (tx *Tx) PreparexContext(ctx context.Context, query string) (*Stmt, error) { + return PreparexContext(ctx, tx, query) +} + +// PrepareNamedContext returns an sqlx.NamedStmt +func (tx *Tx) PrepareNamedContext(ctx context.Context, query string) (*NamedStmt, error) { + return prepareNamedContext(ctx, tx, query) +} + +// MustExecContext runs MustExecContext within a transaction. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) MustExecContext(ctx context.Context, query string, args ...interface{}) sql.Result { + return MustExecContext(ctx, tx, query, args...) +} + +// QueryxContext within a transaction and context. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { + r, err := tx.Tx.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: tx.unsafe, Mapper: tx.Mapper}, err +} + +// SelectContext within a transaction and context. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return SelectContext(ctx, tx, dest, query, args...) +} + +// GetContext within a transaction and context. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (tx *Tx) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { + return GetContext(ctx, tx, dest, query, args...) +} + +// QueryRowxContext within a transaction and context. +// Any placeholder parameters are replaced with supplied args. +func (tx *Tx) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { + rows, err := tx.Tx.QueryContext(ctx, query, args...) + return &Row{rows: rows, err: err, unsafe: tx.unsafe, Mapper: tx.Mapper} +} + +// NamedExecContext using this Tx. +// Any named placeholder parameters are replaced with fields from arg. +func (tx *Tx) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) { + return NamedExecContext(ctx, tx, query, arg) +} + +// SelectContext using the prepared statement. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) SelectContext(ctx context.Context, dest interface{}, args ...interface{}) error { + return SelectContext(ctx, &qStmt{s}, dest, "", args...) +} + +// GetContext using the prepared statement. +// Any placeholder parameters are replaced with supplied args. +// An error is returned if the result set is empty. +func (s *Stmt) GetContext(ctx context.Context, dest interface{}, args ...interface{}) error { + return GetContext(ctx, &qStmt{s}, dest, "", args...) +} + +// MustExecContext (panic) using this statement. Note that the query portion of +// the error output will be blank, as Stmt does not expose its query. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) MustExecContext(ctx context.Context, args ...interface{}) sql.Result { + return MustExecContext(ctx, &qStmt{s}, "", args...) +} + +// QueryRowxContext using this statement. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) QueryRowxContext(ctx context.Context, args ...interface{}) *Row { + qs := &qStmt{s} + return qs.QueryRowxContext(ctx, "", args...) +} + +// QueryxContext using this statement. +// Any placeholder parameters are replaced with supplied args. +func (s *Stmt) QueryxContext(ctx context.Context, args ...interface{}) (*Rows, error) { + qs := &qStmt{s} + return qs.QueryxContext(ctx, "", args...) +} + +func (q *qStmt) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + return q.Stmt.QueryContext(ctx, args...) +} + +func (q *qStmt) QueryxContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { + r, err := q.Stmt.QueryContext(ctx, args...) + if err != nil { + return nil, err + } + return &Rows{Rows: r, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper}, err +} + +func (q *qStmt) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *Row { + rows, err := q.Stmt.QueryContext(ctx, args...) + return &Row{rows: rows, err: err, unsafe: q.Stmt.unsafe, Mapper: q.Stmt.Mapper} +} + +func (q *qStmt) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + return q.Stmt.ExecContext(ctx, args...) +} diff --git a/vendor/github.com/json-iterator/go/.codecov.yml b/vendor/github.com/json-iterator/go/.codecov.yml new file mode 100644 index 0000000..955dc0b --- /dev/null +++ b/vendor/github.com/json-iterator/go/.codecov.yml @@ -0,0 +1,3 @@ +ignore: + - "output_tests/.*" + diff --git a/vendor/github.com/json-iterator/go/.gitignore b/vendor/github.com/json-iterator/go/.gitignore new file mode 100644 index 0000000..1555653 --- /dev/null +++ b/vendor/github.com/json-iterator/go/.gitignore @@ -0,0 +1,4 @@ +/vendor +/bug_test.go +/coverage.txt +/.idea diff --git a/vendor/github.com/json-iterator/go/.travis.yml b/vendor/github.com/json-iterator/go/.travis.yml new file mode 100644 index 0000000..449e67c --- /dev/null +++ b/vendor/github.com/json-iterator/go/.travis.yml @@ -0,0 +1,14 @@ +language: go + +go: + - 1.8.x + - 1.x + +before_install: + - go get -t -v ./... + +script: + - ./test.sh + +after_success: + - bash <(curl -s https://codecov.io/bash) diff --git a/vendor/github.com/json-iterator/go/Gopkg.lock b/vendor/github.com/json-iterator/go/Gopkg.lock new file mode 100644 index 0000000..c8a9fbb --- /dev/null +++ b/vendor/github.com/json-iterator/go/Gopkg.lock @@ -0,0 +1,21 @@ +# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. + + +[[projects]] + name = "github.com/modern-go/concurrent" + packages = ["."] + revision = "e0a39a4cb4216ea8db28e22a69f4ec25610d513a" + version = "1.0.0" + +[[projects]] + name = "github.com/modern-go/reflect2" + packages = ["."] + revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" + version = "1.0.1" + +[solve-meta] + analyzer-name = "dep" + analyzer-version = 1 + inputs-digest = "ea54a775e5a354cb015502d2e7aa4b74230fc77e894f34a838b268c25ec8eeb8" + solver-name = "gps-cdcl" + solver-version = 1 diff --git a/vendor/github.com/json-iterator/go/Gopkg.toml b/vendor/github.com/json-iterator/go/Gopkg.toml new file mode 100644 index 0000000..313a0f8 --- /dev/null +++ b/vendor/github.com/json-iterator/go/Gopkg.toml @@ -0,0 +1,26 @@ +# Gopkg.toml example +# +# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md +# for detailed Gopkg.toml documentation. +# +# required = ["github.com/user/thing/cmd/thing"] +# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] +# +# [[constraint]] +# name = "github.com/user/project" +# version = "1.0.0" +# +# [[constraint]] +# name = "github.com/user/project2" +# branch = "dev" +# source = "github.com/myfork/project2" +# +# [[override]] +# name = "github.com/x/y" +# version = "2.4.0" + +ignored = ["github.com/davecgh/go-spew*","github.com/google/gofuzz*","github.com/stretchr/testify*"] + +[[constraint]] + name = "github.com/modern-go/reflect2" + version = "1.0.1" diff --git a/vendor/github.com/json-iterator/go/LICENSE b/vendor/github.com/json-iterator/go/LICENSE new file mode 100644 index 0000000..2cf4f5a --- /dev/null +++ b/vendor/github.com/json-iterator/go/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 json-iterator + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/json-iterator/go/README.md b/vendor/github.com/json-iterator/go/README.md new file mode 100644 index 0000000..c589add --- /dev/null +++ b/vendor/github.com/json-iterator/go/README.md @@ -0,0 +1,85 @@ +[![Sourcegraph](https://sourcegraph.com/github.com/json-iterator/go/-/badge.svg)](https://sourcegraph.com/github.com/json-iterator/go?badge) +[![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](https://pkg.go.dev/github.com/json-iterator/go) +[![Build Status](https://travis-ci.org/json-iterator/go.svg?branch=master)](https://travis-ci.org/json-iterator/go) +[![codecov](https://codecov.io/gh/json-iterator/go/branch/master/graph/badge.svg)](https://codecov.io/gh/json-iterator/go) +[![rcard](https://goreportcard.com/badge/github.com/json-iterator/go)](https://goreportcard.com/report/github.com/json-iterator/go) +[![License](http://img.shields.io/badge/license-mit-blue.svg?style=flat-square)](https://raw.githubusercontent.com/json-iterator/go/master/LICENSE) +[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby) + +A high-performance 100% compatible drop-in replacement of "encoding/json" + +# Benchmark + +![benchmark](http://jsoniter.com/benchmarks/go-benchmark.png) + +Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go + +Raw Result (easyjson requires static code generation) + +| | ns/op | allocation bytes | allocation times | +| --------------- | ----------- | ---------------- | ---------------- | +| std decode | 35510 ns/op | 1960 B/op | 99 allocs/op | +| easyjson decode | 8499 ns/op | 160 B/op | 4 allocs/op | +| jsoniter decode | 5623 ns/op | 160 B/op | 3 allocs/op | +| std encode | 2213 ns/op | 712 B/op | 5 allocs/op | +| easyjson encode | 883 ns/op | 576 B/op | 3 allocs/op | +| jsoniter encode | 837 ns/op | 384 B/op | 4 allocs/op | + +Always benchmark with your own workload. +The result depends heavily on the data input. + +# Usage + +100% compatibility with standard lib + +Replace + +```go +import "encoding/json" +json.Marshal(&data) +``` + +with + +```go +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary +json.Marshal(&data) +``` + +Replace + +```go +import "encoding/json" +json.Unmarshal(input, &data) +``` + +with + +```go +import jsoniter "github.com/json-iterator/go" + +var json = jsoniter.ConfigCompatibleWithStandardLibrary +json.Unmarshal(input, &data) +``` + +[More documentation](http://jsoniter.com/migrate-from-go-std.html) + +# How to get + +``` +go get github.com/json-iterator/go +``` + +# Contribution Welcomed ! + +Contributors + +- [thockin](https://github.com/thockin) +- [mattn](https://github.com/mattn) +- [cch123](https://github.com/cch123) +- [Oleg Shaldybin](https://github.com/olegshaldybin) +- [Jason Toffaletti](https://github.com/toffaletti) + +Report issue or pull request, or email taowen@gmail.com, or [![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/json-iterator/Lobby) diff --git a/vendor/github.com/json-iterator/go/adapter.go b/vendor/github.com/json-iterator/go/adapter.go new file mode 100644 index 0000000..92d2cc4 --- /dev/null +++ b/vendor/github.com/json-iterator/go/adapter.go @@ -0,0 +1,150 @@ +package jsoniter + +import ( + "bytes" + "io" +) + +// RawMessage to make replace json with jsoniter +type RawMessage []byte + +// Unmarshal adapts to json/encoding Unmarshal API +// +// Unmarshal parses the JSON-encoded data and stores the result in the value pointed to by v. +// Refer to https://godoc.org/encoding/json#Unmarshal for more information +func Unmarshal(data []byte, v interface{}) error { + return ConfigDefault.Unmarshal(data, v) +} + +// UnmarshalFromString is a convenient method to read from string instead of []byte +func UnmarshalFromString(str string, v interface{}) error { + return ConfigDefault.UnmarshalFromString(str, v) +} + +// Get quick method to get value from deeply nested JSON structure +func Get(data []byte, path ...interface{}) Any { + return ConfigDefault.Get(data, path...) +} + +// Marshal adapts to json/encoding Marshal API +// +// Marshal returns the JSON encoding of v, adapts to json/encoding Marshal API +// Refer to https://godoc.org/encoding/json#Marshal for more information +func Marshal(v interface{}) ([]byte, error) { + return ConfigDefault.Marshal(v) +} + +// MarshalIndent same as json.MarshalIndent. Prefix is not supported. +func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + return ConfigDefault.MarshalIndent(v, prefix, indent) +} + +// MarshalToString convenient method to write as string instead of []byte +func MarshalToString(v interface{}) (string, error) { + return ConfigDefault.MarshalToString(v) +} + +// NewDecoder adapts to json/stream NewDecoder API. +// +// NewDecoder returns a new decoder that reads from r. +// +// Instead of a json/encoding Decoder, an Decoder is returned +// Refer to https://godoc.org/encoding/json#NewDecoder for more information +func NewDecoder(reader io.Reader) *Decoder { + return ConfigDefault.NewDecoder(reader) +} + +// Decoder reads and decodes JSON values from an input stream. +// Decoder provides identical APIs with json/stream Decoder (Token() and UseNumber() are in progress) +type Decoder struct { + iter *Iterator +} + +// Decode decode JSON into interface{} +func (adapter *Decoder) Decode(obj interface{}) error { + if adapter.iter.head == adapter.iter.tail && adapter.iter.reader != nil { + if !adapter.iter.loadMore() { + return io.EOF + } + } + adapter.iter.ReadVal(obj) + err := adapter.iter.Error + if err == io.EOF { + return nil + } + return adapter.iter.Error +} + +// More is there more? +func (adapter *Decoder) More() bool { + iter := adapter.iter + if iter.Error != nil { + return false + } + c := iter.nextToken() + if c == 0 { + return false + } + iter.unreadByte() + return c != ']' && c != '}' +} + +// Buffered remaining buffer +func (adapter *Decoder) Buffered() io.Reader { + remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail] + return bytes.NewReader(remaining) +} + +// UseNumber causes the Decoder to unmarshal a number into an interface{} as a +// Number instead of as a float64. +func (adapter *Decoder) UseNumber() { + cfg := adapter.iter.cfg.configBeforeFrozen + cfg.UseNumber = true + adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) +} + +// DisallowUnknownFields causes the Decoder to return an error when the destination +// is a struct and the input contains object keys which do not match any +// non-ignored, exported fields in the destination. +func (adapter *Decoder) DisallowUnknownFields() { + cfg := adapter.iter.cfg.configBeforeFrozen + cfg.DisallowUnknownFields = true + adapter.iter.cfg = cfg.frozeWithCacheReuse(adapter.iter.cfg.extraExtensions) +} + +// NewEncoder same as json.NewEncoder +func NewEncoder(writer io.Writer) *Encoder { + return ConfigDefault.NewEncoder(writer) +} + +// Encoder same as json.Encoder +type Encoder struct { + stream *Stream +} + +// Encode encode interface{} as JSON to io.Writer +func (adapter *Encoder) Encode(val interface{}) error { + adapter.stream.WriteVal(val) + adapter.stream.WriteRaw("\n") + adapter.stream.Flush() + return adapter.stream.Error +} + +// SetIndent set the indention. Prefix is not supported +func (adapter *Encoder) SetIndent(prefix, indent string) { + config := adapter.stream.cfg.configBeforeFrozen + config.IndentionStep = len(indent) + adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) +} + +// SetEscapeHTML escape html by default, set to false to disable +func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { + config := adapter.stream.cfg.configBeforeFrozen + config.EscapeHTML = escapeHTML + adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) +} + +// Valid reports whether data is a valid JSON encoding. +func Valid(data []byte) bool { + return ConfigDefault.Valid(data) +} diff --git a/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/json-iterator/go/any.go new file mode 100644 index 0000000..f6b8aea --- /dev/null +++ b/vendor/github.com/json-iterator/go/any.go @@ -0,0 +1,325 @@ +package jsoniter + +import ( + "errors" + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "strconv" + "unsafe" +) + +// Any generic object representation. +// The lazy json implementation holds []byte and parse lazily. +type Any interface { + LastError() error + ValueType() ValueType + MustBeValid() Any + ToBool() bool + ToInt() int + ToInt32() int32 + ToInt64() int64 + ToUint() uint + ToUint32() uint32 + ToUint64() uint64 + ToFloat32() float32 + ToFloat64() float64 + ToString() string + ToVal(val interface{}) + Get(path ...interface{}) Any + Size() int + Keys() []string + GetInterface() interface{} + WriteTo(stream *Stream) +} + +type baseAny struct{} + +func (any *baseAny) Get(path ...interface{}) Any { + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} +} + +func (any *baseAny) Size() int { + return 0 +} + +func (any *baseAny) Keys() []string { + return []string{} +} + +func (any *baseAny) ToVal(obj interface{}) { + panic("not implemented") +} + +// WrapInt32 turn int32 into Any interface +func WrapInt32(val int32) Any { + return &int32Any{baseAny{}, val} +} + +// WrapInt64 turn int64 into Any interface +func WrapInt64(val int64) Any { + return &int64Any{baseAny{}, val} +} + +// WrapUint32 turn uint32 into Any interface +func WrapUint32(val uint32) Any { + return &uint32Any{baseAny{}, val} +} + +// WrapUint64 turn uint64 into Any interface +func WrapUint64(val uint64) Any { + return &uint64Any{baseAny{}, val} +} + +// WrapFloat64 turn float64 into Any interface +func WrapFloat64(val float64) Any { + return &floatAny{baseAny{}, val} +} + +// WrapString turn string into Any interface +func WrapString(val string) Any { + return &stringAny{baseAny{}, val} +} + +// Wrap turn a go object into Any interface +func Wrap(val interface{}) Any { + if val == nil { + return &nilAny{} + } + asAny, isAny := val.(Any) + if isAny { + return asAny + } + typ := reflect2.TypeOf(val) + switch typ.Kind() { + case reflect.Slice: + return wrapArray(val) + case reflect.Struct: + return wrapStruct(val) + case reflect.Map: + return wrapMap(val) + case reflect.String: + return WrapString(val.(string)) + case reflect.Int: + if strconv.IntSize == 32 { + return WrapInt32(int32(val.(int))) + } + return WrapInt64(int64(val.(int))) + case reflect.Int8: + return WrapInt32(int32(val.(int8))) + case reflect.Int16: + return WrapInt32(int32(val.(int16))) + case reflect.Int32: + return WrapInt32(val.(int32)) + case reflect.Int64: + return WrapInt64(val.(int64)) + case reflect.Uint: + if strconv.IntSize == 32 { + return WrapUint32(uint32(val.(uint))) + } + return WrapUint64(uint64(val.(uint))) + case reflect.Uintptr: + if ptrSize == 32 { + return WrapUint32(uint32(val.(uintptr))) + } + return WrapUint64(uint64(val.(uintptr))) + case reflect.Uint8: + return WrapUint32(uint32(val.(uint8))) + case reflect.Uint16: + return WrapUint32(uint32(val.(uint16))) + case reflect.Uint32: + return WrapUint32(uint32(val.(uint32))) + case reflect.Uint64: + return WrapUint64(val.(uint64)) + case reflect.Float32: + return WrapFloat64(float64(val.(float32))) + case reflect.Float64: + return WrapFloat64(val.(float64)) + case reflect.Bool: + if val.(bool) == true { + return &trueAny{} + } + return &falseAny{} + } + return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} +} + +// ReadAny read next JSON element as an Any object. It is a better json.RawMessage. +func (iter *Iterator) ReadAny() Any { + return iter.readAny() +} + +func (iter *Iterator) readAny() Any { + c := iter.nextToken() + switch c { + case '"': + iter.unreadByte() + return &stringAny{baseAny{}, iter.ReadString()} + case 'n': + iter.skipThreeBytes('u', 'l', 'l') // null + return &nilAny{} + case 't': + iter.skipThreeBytes('r', 'u', 'e') // true + return &trueAny{} + case 'f': + iter.skipFourBytes('a', 'l', 's', 'e') // false + return &falseAny{} + case '{': + return iter.readObjectAny() + case '[': + return iter.readArrayAny() + case '-': + return iter.readNumberAny(false) + case 0: + return &invalidAny{baseAny{}, errors.New("input is empty")} + default: + return iter.readNumberAny(true) + } +} + +func (iter *Iterator) readNumberAny(positive bool) Any { + iter.startCapture(iter.head - 1) + iter.skipNumber() + lazyBuf := iter.stopCapture() + return &numberLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} +} + +func (iter *Iterator) readObjectAny() Any { + iter.startCapture(iter.head - 1) + iter.skipObject() + lazyBuf := iter.stopCapture() + return &objectLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} +} + +func (iter *Iterator) readArrayAny() Any { + iter.startCapture(iter.head - 1) + iter.skipArray() + lazyBuf := iter.stopCapture() + return &arrayLazyAny{baseAny{}, iter.cfg, lazyBuf, nil} +} + +func locateObjectField(iter *Iterator, target string) []byte { + var found []byte + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + if field == target { + found = iter.SkipAndReturnBytes() + return false + } + iter.Skip() + return true + }) + return found +} + +func locateArrayElement(iter *Iterator, target int) []byte { + var found []byte + n := 0 + iter.ReadArrayCB(func(iter *Iterator) bool { + if n == target { + found = iter.SkipAndReturnBytes() + return false + } + iter.Skip() + n++ + return true + }) + return found +} + +func locatePath(iter *Iterator, path []interface{}) Any { + for i, pathKeyObj := range path { + switch pathKey := pathKeyObj.(type) { + case string: + valueBytes := locateObjectField(iter, pathKey) + if valueBytes == nil { + return newInvalidAny(path[i:]) + } + iter.ResetBytes(valueBytes) + case int: + valueBytes := locateArrayElement(iter, pathKey) + if valueBytes == nil { + return newInvalidAny(path[i:]) + } + iter.ResetBytes(valueBytes) + case int32: + if '*' == pathKey { + return iter.readAny().Get(path[i:]...) + } + return newInvalidAny(path[i:]) + default: + return newInvalidAny(path[i:]) + } + } + if iter.Error != nil && iter.Error != io.EOF { + return &invalidAny{baseAny{}, iter.Error} + } + return iter.readAny() +} + +var anyType = reflect2.TypeOfPtr((*Any)(nil)).Elem() + +func createDecoderOfAny(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == anyType { + return &directAnyCodec{} + } + if typ.Implements(anyType) { + return &anyCodec{ + valType: typ, + } + } + return nil +} + +func createEncoderOfAny(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == anyType { + return &directAnyCodec{} + } + if typ.Implements(anyType) { + return &anyCodec{ + valType: typ, + } + } + return nil +} + +type anyCodec struct { + valType reflect2.Type +} + +func (codec *anyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + panic("not implemented") +} + +func (codec *anyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := codec.valType.UnsafeIndirect(ptr) + any := obj.(Any) + any.WriteTo(stream) +} + +func (codec *anyCodec) IsEmpty(ptr unsafe.Pointer) bool { + obj := codec.valType.UnsafeIndirect(ptr) + any := obj.(Any) + return any.Size() == 0 +} + +type directAnyCodec struct { +} + +func (codec *directAnyCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *(*Any)(ptr) = iter.readAny() +} + +func (codec *directAnyCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + any := *(*Any)(ptr) + if any == nil { + stream.WriteNil() + return + } + any.WriteTo(stream) +} + +func (codec *directAnyCodec) IsEmpty(ptr unsafe.Pointer) bool { + any := *(*Any)(ptr) + return any.Size() == 0 +} diff --git a/vendor/github.com/json-iterator/go/any_array.go b/vendor/github.com/json-iterator/go/any_array.go new file mode 100644 index 0000000..0449e9a --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_array.go @@ -0,0 +1,278 @@ +package jsoniter + +import ( + "reflect" + "unsafe" +) + +type arrayLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *arrayLazyAny) ValueType() ValueType { + return ArrayValue +} + +func (any *arrayLazyAny) MustBeValid() Any { + return any +} + +func (any *arrayLazyAny) LastError() error { + return any.err +} + +func (any *arrayLazyAny) ToBool() bool { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.ReadArray() +} + +func (any *arrayLazyAny) ToInt() int { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToInt32() int32 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToInt64() int64 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToUint() uint { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToUint32() uint32 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToUint64() uint64 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToFloat32() float32 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToFloat64() float64 { + if any.ToBool() { + return 1 + } + return 0 +} + +func (any *arrayLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *arrayLazyAny) ToVal(val interface{}) { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadVal(val) +} + +func (any *arrayLazyAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int: + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + valueBytes := locateArrayElement(iter, firstPath) + if valueBytes == nil { + return newInvalidAny(path) + } + iter.ResetBytes(valueBytes) + return locatePath(iter, path[1:]) + case int32: + if '*' == firstPath { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + arr := make([]Any, 0) + iter.ReadArrayCB(func(iter *Iterator) bool { + found := iter.readAny().Get(path[1:]...) + if found.ValueType() != InvalidValue { + arr = append(arr, found) + } + return true + }) + return wrapArray(arr) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *arrayLazyAny) Size() int { + size := 0 + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadArrayCB(func(iter *Iterator) bool { + size++ + iter.Skip() + return true + }) + return size +} + +func (any *arrayLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *arrayLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} + +type arrayAny struct { + baseAny + val reflect.Value +} + +func wrapArray(val interface{}) *arrayAny { + return &arrayAny{baseAny{}, reflect.ValueOf(val)} +} + +func (any *arrayAny) ValueType() ValueType { + return ArrayValue +} + +func (any *arrayAny) MustBeValid() Any { + return any +} + +func (any *arrayAny) LastError() error { + return nil +} + +func (any *arrayAny) ToBool() bool { + return any.val.Len() != 0 +} + +func (any *arrayAny) ToInt() int { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToInt32() int32 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToInt64() int64 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToUint() uint { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToUint32() uint32 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToUint64() uint64 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToFloat32() float32 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToFloat64() float64 { + if any.val.Len() == 0 { + return 0 + } + return 1 +} + +func (any *arrayAny) ToString() string { + str, _ := MarshalToString(any.val.Interface()) + return str +} + +func (any *arrayAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int: + if firstPath < 0 || firstPath >= any.val.Len() { + return newInvalidAny(path) + } + return Wrap(any.val.Index(firstPath).Interface()) + case int32: + if '*' == firstPath { + mappedAll := make([]Any, 0) + for i := 0; i < any.val.Len(); i++ { + mapped := Wrap(any.val.Index(i).Interface()).Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll = append(mappedAll, mapped) + } + } + return wrapArray(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *arrayAny) Size() int { + return any.val.Len() +} + +func (any *arrayAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *arrayAny) GetInterface() interface{} { + return any.val.Interface() +} diff --git a/vendor/github.com/json-iterator/go/any_bool.go b/vendor/github.com/json-iterator/go/any_bool.go new file mode 100644 index 0000000..9452324 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_bool.go @@ -0,0 +1,137 @@ +package jsoniter + +type trueAny struct { + baseAny +} + +func (any *trueAny) LastError() error { + return nil +} + +func (any *trueAny) ToBool() bool { + return true +} + +func (any *trueAny) ToInt() int { + return 1 +} + +func (any *trueAny) ToInt32() int32 { + return 1 +} + +func (any *trueAny) ToInt64() int64 { + return 1 +} + +func (any *trueAny) ToUint() uint { + return 1 +} + +func (any *trueAny) ToUint32() uint32 { + return 1 +} + +func (any *trueAny) ToUint64() uint64 { + return 1 +} + +func (any *trueAny) ToFloat32() float32 { + return 1 +} + +func (any *trueAny) ToFloat64() float64 { + return 1 +} + +func (any *trueAny) ToString() string { + return "true" +} + +func (any *trueAny) WriteTo(stream *Stream) { + stream.WriteTrue() +} + +func (any *trueAny) Parse() *Iterator { + return nil +} + +func (any *trueAny) GetInterface() interface{} { + return true +} + +func (any *trueAny) ValueType() ValueType { + return BoolValue +} + +func (any *trueAny) MustBeValid() Any { + return any +} + +type falseAny struct { + baseAny +} + +func (any *falseAny) LastError() error { + return nil +} + +func (any *falseAny) ToBool() bool { + return false +} + +func (any *falseAny) ToInt() int { + return 0 +} + +func (any *falseAny) ToInt32() int32 { + return 0 +} + +func (any *falseAny) ToInt64() int64 { + return 0 +} + +func (any *falseAny) ToUint() uint { + return 0 +} + +func (any *falseAny) ToUint32() uint32 { + return 0 +} + +func (any *falseAny) ToUint64() uint64 { + return 0 +} + +func (any *falseAny) ToFloat32() float32 { + return 0 +} + +func (any *falseAny) ToFloat64() float64 { + return 0 +} + +func (any *falseAny) ToString() string { + return "false" +} + +func (any *falseAny) WriteTo(stream *Stream) { + stream.WriteFalse() +} + +func (any *falseAny) Parse() *Iterator { + return nil +} + +func (any *falseAny) GetInterface() interface{} { + return false +} + +func (any *falseAny) ValueType() ValueType { + return BoolValue +} + +func (any *falseAny) MustBeValid() Any { + return any +} diff --git a/vendor/github.com/json-iterator/go/any_float.go b/vendor/github.com/json-iterator/go/any_float.go new file mode 100644 index 0000000..35fdb09 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_float.go @@ -0,0 +1,83 @@ +package jsoniter + +import ( + "strconv" +) + +type floatAny struct { + baseAny + val float64 +} + +func (any *floatAny) Parse() *Iterator { + return nil +} + +func (any *floatAny) ValueType() ValueType { + return NumberValue +} + +func (any *floatAny) MustBeValid() Any { + return any +} + +func (any *floatAny) LastError() error { + return nil +} + +func (any *floatAny) ToBool() bool { + return any.ToFloat64() != 0 +} + +func (any *floatAny) ToInt() int { + return int(any.val) +} + +func (any *floatAny) ToInt32() int32 { + return int32(any.val) +} + +func (any *floatAny) ToInt64() int64 { + return int64(any.val) +} + +func (any *floatAny) ToUint() uint { + if any.val > 0 { + return uint(any.val) + } + return 0 +} + +func (any *floatAny) ToUint32() uint32 { + if any.val > 0 { + return uint32(any.val) + } + return 0 +} + +func (any *floatAny) ToUint64() uint64 { + if any.val > 0 { + return uint64(any.val) + } + return 0 +} + +func (any *floatAny) ToFloat32() float32 { + return float32(any.val) +} + +func (any *floatAny) ToFloat64() float64 { + return any.val +} + +func (any *floatAny) ToString() string { + return strconv.FormatFloat(any.val, 'E', -1, 64) +} + +func (any *floatAny) WriteTo(stream *Stream) { + stream.WriteFloat64(any.val) +} + +func (any *floatAny) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_int32.go b/vendor/github.com/json-iterator/go/any_int32.go new file mode 100644 index 0000000..1b56f39 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_int32.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type int32Any struct { + baseAny + val int32 +} + +func (any *int32Any) LastError() error { + return nil +} + +func (any *int32Any) ValueType() ValueType { + return NumberValue +} + +func (any *int32Any) MustBeValid() Any { + return any +} + +func (any *int32Any) ToBool() bool { + return any.val != 0 +} + +func (any *int32Any) ToInt() int { + return int(any.val) +} + +func (any *int32Any) ToInt32() int32 { + return any.val +} + +func (any *int32Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *int32Any) ToUint() uint { + return uint(any.val) +} + +func (any *int32Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *int32Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *int32Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *int32Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *int32Any) ToString() string { + return strconv.FormatInt(int64(any.val), 10) +} + +func (any *int32Any) WriteTo(stream *Stream) { + stream.WriteInt32(any.val) +} + +func (any *int32Any) Parse() *Iterator { + return nil +} + +func (any *int32Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_int64.go b/vendor/github.com/json-iterator/go/any_int64.go new file mode 100644 index 0000000..c440d72 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_int64.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type int64Any struct { + baseAny + val int64 +} + +func (any *int64Any) LastError() error { + return nil +} + +func (any *int64Any) ValueType() ValueType { + return NumberValue +} + +func (any *int64Any) MustBeValid() Any { + return any +} + +func (any *int64Any) ToBool() bool { + return any.val != 0 +} + +func (any *int64Any) ToInt() int { + return int(any.val) +} + +func (any *int64Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *int64Any) ToInt64() int64 { + return any.val +} + +func (any *int64Any) ToUint() uint { + return uint(any.val) +} + +func (any *int64Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *int64Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *int64Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *int64Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *int64Any) ToString() string { + return strconv.FormatInt(any.val, 10) +} + +func (any *int64Any) WriteTo(stream *Stream) { + stream.WriteInt64(any.val) +} + +func (any *int64Any) Parse() *Iterator { + return nil +} + +func (any *int64Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_invalid.go b/vendor/github.com/json-iterator/go/any_invalid.go new file mode 100644 index 0000000..1d859ea --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_invalid.go @@ -0,0 +1,82 @@ +package jsoniter + +import "fmt" + +type invalidAny struct { + baseAny + err error +} + +func newInvalidAny(path []interface{}) *invalidAny { + return &invalidAny{baseAny{}, fmt.Errorf("%v not found", path)} +} + +func (any *invalidAny) LastError() error { + return any.err +} + +func (any *invalidAny) ValueType() ValueType { + return InvalidValue +} + +func (any *invalidAny) MustBeValid() Any { + panic(any.err) +} + +func (any *invalidAny) ToBool() bool { + return false +} + +func (any *invalidAny) ToInt() int { + return 0 +} + +func (any *invalidAny) ToInt32() int32 { + return 0 +} + +func (any *invalidAny) ToInt64() int64 { + return 0 +} + +func (any *invalidAny) ToUint() uint { + return 0 +} + +func (any *invalidAny) ToUint32() uint32 { + return 0 +} + +func (any *invalidAny) ToUint64() uint64 { + return 0 +} + +func (any *invalidAny) ToFloat32() float32 { + return 0 +} + +func (any *invalidAny) ToFloat64() float64 { + return 0 +} + +func (any *invalidAny) ToString() string { + return "" +} + +func (any *invalidAny) WriteTo(stream *Stream) { +} + +func (any *invalidAny) Get(path ...interface{}) Any { + if any.err == nil { + return &invalidAny{baseAny{}, fmt.Errorf("get %v from invalid", path)} + } + return &invalidAny{baseAny{}, fmt.Errorf("%v, get %v from invalid", any.err, path)} +} + +func (any *invalidAny) Parse() *Iterator { + return nil +} + +func (any *invalidAny) GetInterface() interface{} { + return nil +} diff --git a/vendor/github.com/json-iterator/go/any_nil.go b/vendor/github.com/json-iterator/go/any_nil.go new file mode 100644 index 0000000..d04cb54 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_nil.go @@ -0,0 +1,69 @@ +package jsoniter + +type nilAny struct { + baseAny +} + +func (any *nilAny) LastError() error { + return nil +} + +func (any *nilAny) ValueType() ValueType { + return NilValue +} + +func (any *nilAny) MustBeValid() Any { + return any +} + +func (any *nilAny) ToBool() bool { + return false +} + +func (any *nilAny) ToInt() int { + return 0 +} + +func (any *nilAny) ToInt32() int32 { + return 0 +} + +func (any *nilAny) ToInt64() int64 { + return 0 +} + +func (any *nilAny) ToUint() uint { + return 0 +} + +func (any *nilAny) ToUint32() uint32 { + return 0 +} + +func (any *nilAny) ToUint64() uint64 { + return 0 +} + +func (any *nilAny) ToFloat32() float32 { + return 0 +} + +func (any *nilAny) ToFloat64() float64 { + return 0 +} + +func (any *nilAny) ToString() string { + return "" +} + +func (any *nilAny) WriteTo(stream *Stream) { + stream.WriteNil() +} + +func (any *nilAny) Parse() *Iterator { + return nil +} + +func (any *nilAny) GetInterface() interface{} { + return nil +} diff --git a/vendor/github.com/json-iterator/go/any_number.go b/vendor/github.com/json-iterator/go/any_number.go new file mode 100644 index 0000000..9d1e901 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_number.go @@ -0,0 +1,123 @@ +package jsoniter + +import ( + "io" + "unsafe" +) + +type numberLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *numberLazyAny) ValueType() ValueType { + return NumberValue +} + +func (any *numberLazyAny) MustBeValid() Any { + return any +} + +func (any *numberLazyAny) LastError() error { + return any.err +} + +func (any *numberLazyAny) ToBool() bool { + return any.ToFloat64() != 0 +} + +func (any *numberLazyAny) ToInt() int { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToInt32() int32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToInt64() int64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadInt64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint() uint { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint32() uint32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToUint64() uint64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadUint64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToFloat32() float32 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadFloat32() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToFloat64() float64 { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + val := iter.ReadFloat64() + if iter.Error != nil && iter.Error != io.EOF { + any.err = iter.Error + } + return val +} + +func (any *numberLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *numberLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *numberLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} diff --git a/vendor/github.com/json-iterator/go/any_object.go b/vendor/github.com/json-iterator/go/any_object.go new file mode 100644 index 0000000..c44ef5c --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_object.go @@ -0,0 +1,374 @@ +package jsoniter + +import ( + "reflect" + "unsafe" +) + +type objectLazyAny struct { + baseAny + cfg *frozenConfig + buf []byte + err error +} + +func (any *objectLazyAny) ValueType() ValueType { + return ObjectValue +} + +func (any *objectLazyAny) MustBeValid() Any { + return any +} + +func (any *objectLazyAny) LastError() error { + return any.err +} + +func (any *objectLazyAny) ToBool() bool { + return true +} + +func (any *objectLazyAny) ToInt() int { + return 0 +} + +func (any *objectLazyAny) ToInt32() int32 { + return 0 +} + +func (any *objectLazyAny) ToInt64() int64 { + return 0 +} + +func (any *objectLazyAny) ToUint() uint { + return 0 +} + +func (any *objectLazyAny) ToUint32() uint32 { + return 0 +} + +func (any *objectLazyAny) ToUint64() uint64 { + return 0 +} + +func (any *objectLazyAny) ToFloat32() float32 { + return 0 +} + +func (any *objectLazyAny) ToFloat64() float64 { + return 0 +} + +func (any *objectLazyAny) ToString() string { + return *(*string)(unsafe.Pointer(&any.buf)) +} + +func (any *objectLazyAny) ToVal(obj interface{}) { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadVal(obj) +} + +func (any *objectLazyAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case string: + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + valueBytes := locateObjectField(iter, firstPath) + if valueBytes == nil { + return newInvalidAny(path) + } + iter.ResetBytes(valueBytes) + return locatePath(iter, path[1:]) + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadMapCB(func(iter *Iterator, field string) bool { + mapped := locatePath(iter, path[1:]) + if mapped.ValueType() != InvalidValue { + mappedAll[field] = mapped + } + return true + }) + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *objectLazyAny) Keys() []string { + keys := []string{} + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadMapCB(func(iter *Iterator, field string) bool { + iter.Skip() + keys = append(keys, field) + return true + }) + return keys +} + +func (any *objectLazyAny) Size() int { + size := 0 + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + iter.Skip() + size++ + return true + }) + return size +} + +func (any *objectLazyAny) WriteTo(stream *Stream) { + stream.Write(any.buf) +} + +func (any *objectLazyAny) GetInterface() interface{} { + iter := any.cfg.BorrowIterator(any.buf) + defer any.cfg.ReturnIterator(iter) + return iter.Read() +} + +type objectAny struct { + baseAny + err error + val reflect.Value +} + +func wrapStruct(val interface{}) *objectAny { + return &objectAny{baseAny{}, nil, reflect.ValueOf(val)} +} + +func (any *objectAny) ValueType() ValueType { + return ObjectValue +} + +func (any *objectAny) MustBeValid() Any { + return any +} + +func (any *objectAny) Parse() *Iterator { + return nil +} + +func (any *objectAny) LastError() error { + return any.err +} + +func (any *objectAny) ToBool() bool { + return any.val.NumField() != 0 +} + +func (any *objectAny) ToInt() int { + return 0 +} + +func (any *objectAny) ToInt32() int32 { + return 0 +} + +func (any *objectAny) ToInt64() int64 { + return 0 +} + +func (any *objectAny) ToUint() uint { + return 0 +} + +func (any *objectAny) ToUint32() uint32 { + return 0 +} + +func (any *objectAny) ToUint64() uint64 { + return 0 +} + +func (any *objectAny) ToFloat32() float32 { + return 0 +} + +func (any *objectAny) ToFloat64() float64 { + return 0 +} + +func (any *objectAny) ToString() string { + str, err := MarshalToString(any.val.Interface()) + any.err = err + return str +} + +func (any *objectAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case string: + field := any.val.FieldByName(firstPath) + if !field.IsValid() { + return newInvalidAny(path) + } + return Wrap(field.Interface()) + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + for i := 0; i < any.val.NumField(); i++ { + field := any.val.Field(i) + if field.CanInterface() { + mapped := Wrap(field.Interface()).Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll[any.val.Type().Field(i).Name] = mapped + } + } + } + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + return newInvalidAny(path) + } +} + +func (any *objectAny) Keys() []string { + keys := make([]string, 0, any.val.NumField()) + for i := 0; i < any.val.NumField(); i++ { + keys = append(keys, any.val.Type().Field(i).Name) + } + return keys +} + +func (any *objectAny) Size() int { + return any.val.NumField() +} + +func (any *objectAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *objectAny) GetInterface() interface{} { + return any.val.Interface() +} + +type mapAny struct { + baseAny + err error + val reflect.Value +} + +func wrapMap(val interface{}) *mapAny { + return &mapAny{baseAny{}, nil, reflect.ValueOf(val)} +} + +func (any *mapAny) ValueType() ValueType { + return ObjectValue +} + +func (any *mapAny) MustBeValid() Any { + return any +} + +func (any *mapAny) Parse() *Iterator { + return nil +} + +func (any *mapAny) LastError() error { + return any.err +} + +func (any *mapAny) ToBool() bool { + return true +} + +func (any *mapAny) ToInt() int { + return 0 +} + +func (any *mapAny) ToInt32() int32 { + return 0 +} + +func (any *mapAny) ToInt64() int64 { + return 0 +} + +func (any *mapAny) ToUint() uint { + return 0 +} + +func (any *mapAny) ToUint32() uint32 { + return 0 +} + +func (any *mapAny) ToUint64() uint64 { + return 0 +} + +func (any *mapAny) ToFloat32() float32 { + return 0 +} + +func (any *mapAny) ToFloat64() float64 { + return 0 +} + +func (any *mapAny) ToString() string { + str, err := MarshalToString(any.val.Interface()) + any.err = err + return str +} + +func (any *mapAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + switch firstPath := path[0].(type) { + case int32: + if '*' == firstPath { + mappedAll := map[string]Any{} + for _, key := range any.val.MapKeys() { + keyAsStr := key.String() + element := Wrap(any.val.MapIndex(key).Interface()) + mapped := element.Get(path[1:]...) + if mapped.ValueType() != InvalidValue { + mappedAll[keyAsStr] = mapped + } + } + return wrapMap(mappedAll) + } + return newInvalidAny(path) + default: + value := any.val.MapIndex(reflect.ValueOf(firstPath)) + if !value.IsValid() { + return newInvalidAny(path) + } + return Wrap(value.Interface()) + } +} + +func (any *mapAny) Keys() []string { + keys := make([]string, 0, any.val.Len()) + for _, key := range any.val.MapKeys() { + keys = append(keys, key.String()) + } + return keys +} + +func (any *mapAny) Size() int { + return any.val.Len() +} + +func (any *mapAny) WriteTo(stream *Stream) { + stream.WriteVal(any.val) +} + +func (any *mapAny) GetInterface() interface{} { + return any.val.Interface() +} diff --git a/vendor/github.com/json-iterator/go/any_str.go b/vendor/github.com/json-iterator/go/any_str.go new file mode 100644 index 0000000..1f12f66 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_str.go @@ -0,0 +1,166 @@ +package jsoniter + +import ( + "fmt" + "strconv" +) + +type stringAny struct { + baseAny + val string +} + +func (any *stringAny) Get(path ...interface{}) Any { + if len(path) == 0 { + return any + } + return &invalidAny{baseAny{}, fmt.Errorf("GetIndex %v from simple value", path)} +} + +func (any *stringAny) Parse() *Iterator { + return nil +} + +func (any *stringAny) ValueType() ValueType { + return StringValue +} + +func (any *stringAny) MustBeValid() Any { + return any +} + +func (any *stringAny) LastError() error { + return nil +} + +func (any *stringAny) ToBool() bool { + str := any.ToString() + if str == "0" { + return false + } + for _, c := range str { + switch c { + case ' ', '\n', '\r', '\t': + default: + return true + } + } + return false +} + +func (any *stringAny) ToInt() int { + return int(any.ToInt64()) + +} + +func (any *stringAny) ToInt32() int32 { + return int32(any.ToInt64()) +} + +func (any *stringAny) ToInt64() int64 { + if any.val == "" { + return 0 + } + + flag := 1 + startPos := 0 + if any.val[0] == '+' || any.val[0] == '-' { + startPos = 1 + } + + if any.val[0] == '-' { + flag = -1 + } + + endPos := startPos + for i := startPos; i < len(any.val); i++ { + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + break + } + } + parsed, _ := strconv.ParseInt(any.val[startPos:endPos], 10, 64) + return int64(flag) * parsed +} + +func (any *stringAny) ToUint() uint { + return uint(any.ToUint64()) +} + +func (any *stringAny) ToUint32() uint32 { + return uint32(any.ToUint64()) +} + +func (any *stringAny) ToUint64() uint64 { + if any.val == "" { + return 0 + } + + startPos := 0 + + if any.val[0] == '-' { + return 0 + } + if any.val[0] == '+' { + startPos = 1 + } + + endPos := startPos + for i := startPos; i < len(any.val); i++ { + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + break + } + } + parsed, _ := strconv.ParseUint(any.val[startPos:endPos], 10, 64) + return parsed +} + +func (any *stringAny) ToFloat32() float32 { + return float32(any.ToFloat64()) +} + +func (any *stringAny) ToFloat64() float64 { + if len(any.val) == 0 { + return 0 + } + + // first char invalid + if any.val[0] != '+' && any.val[0] != '-' && (any.val[0] > '9' || any.val[0] < '0') { + return 0 + } + + // extract valid num expression from string + // eg 123true => 123, -12.12xxa => -12.12 + endPos := 1 + for i := 1; i < len(any.val); i++ { + if any.val[i] == '.' || any.val[i] == 'e' || any.val[i] == 'E' || any.val[i] == '+' || any.val[i] == '-' { + endPos = i + 1 + continue + } + + // end position is the first char which is not digit + if any.val[i] >= '0' && any.val[i] <= '9' { + endPos = i + 1 + } else { + endPos = i + break + } + } + parsed, _ := strconv.ParseFloat(any.val[:endPos], 64) + return parsed +} + +func (any *stringAny) ToString() string { + return any.val +} + +func (any *stringAny) WriteTo(stream *Stream) { + stream.WriteString(any.val) +} + +func (any *stringAny) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_uint32.go b/vendor/github.com/json-iterator/go/any_uint32.go new file mode 100644 index 0000000..656bbd3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_uint32.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type uint32Any struct { + baseAny + val uint32 +} + +func (any *uint32Any) LastError() error { + return nil +} + +func (any *uint32Any) ValueType() ValueType { + return NumberValue +} + +func (any *uint32Any) MustBeValid() Any { + return any +} + +func (any *uint32Any) ToBool() bool { + return any.val != 0 +} + +func (any *uint32Any) ToInt() int { + return int(any.val) +} + +func (any *uint32Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *uint32Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *uint32Any) ToUint() uint { + return uint(any.val) +} + +func (any *uint32Any) ToUint32() uint32 { + return any.val +} + +func (any *uint32Any) ToUint64() uint64 { + return uint64(any.val) +} + +func (any *uint32Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *uint32Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *uint32Any) ToString() string { + return strconv.FormatInt(int64(any.val), 10) +} + +func (any *uint32Any) WriteTo(stream *Stream) { + stream.WriteUint32(any.val) +} + +func (any *uint32Any) Parse() *Iterator { + return nil +} + +func (any *uint32Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/any_uint64.go b/vendor/github.com/json-iterator/go/any_uint64.go new file mode 100644 index 0000000..7df2fce --- /dev/null +++ b/vendor/github.com/json-iterator/go/any_uint64.go @@ -0,0 +1,74 @@ +package jsoniter + +import ( + "strconv" +) + +type uint64Any struct { + baseAny + val uint64 +} + +func (any *uint64Any) LastError() error { + return nil +} + +func (any *uint64Any) ValueType() ValueType { + return NumberValue +} + +func (any *uint64Any) MustBeValid() Any { + return any +} + +func (any *uint64Any) ToBool() bool { + return any.val != 0 +} + +func (any *uint64Any) ToInt() int { + return int(any.val) +} + +func (any *uint64Any) ToInt32() int32 { + return int32(any.val) +} + +func (any *uint64Any) ToInt64() int64 { + return int64(any.val) +} + +func (any *uint64Any) ToUint() uint { + return uint(any.val) +} + +func (any *uint64Any) ToUint32() uint32 { + return uint32(any.val) +} + +func (any *uint64Any) ToUint64() uint64 { + return any.val +} + +func (any *uint64Any) ToFloat32() float32 { + return float32(any.val) +} + +func (any *uint64Any) ToFloat64() float64 { + return float64(any.val) +} + +func (any *uint64Any) ToString() string { + return strconv.FormatUint(any.val, 10) +} + +func (any *uint64Any) WriteTo(stream *Stream) { + stream.WriteUint64(any.val) +} + +func (any *uint64Any) Parse() *Iterator { + return nil +} + +func (any *uint64Any) GetInterface() interface{} { + return any.val +} diff --git a/vendor/github.com/json-iterator/go/build.sh b/vendor/github.com/json-iterator/go/build.sh new file mode 100644 index 0000000..b45ef68 --- /dev/null +++ b/vendor/github.com/json-iterator/go/build.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +set -x + +if [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then + mkdir -p /tmp/build-golang/src/github.com/json-iterator + ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go +fi +export GOPATH=/tmp/build-golang +go get -u github.com/golang/dep/cmd/dep +cd /tmp/build-golang/src/github.com/json-iterator/go +exec $GOPATH/bin/dep ensure -update diff --git a/vendor/github.com/json-iterator/go/config.go b/vendor/github.com/json-iterator/go/config.go new file mode 100644 index 0000000..2adcdc3 --- /dev/null +++ b/vendor/github.com/json-iterator/go/config.go @@ -0,0 +1,375 @@ +package jsoniter + +import ( + "encoding/json" + "io" + "reflect" + "sync" + "unsafe" + + "github.com/modern-go/concurrent" + "github.com/modern-go/reflect2" +) + +// Config customize how the API should behave. +// The API is created from Config by Froze. +type Config struct { + IndentionStep int + MarshalFloatWith6Digits bool + EscapeHTML bool + SortMapKeys bool + UseNumber bool + DisallowUnknownFields bool + TagKey string + OnlyTaggedField bool + ValidateJsonRawMessage bool + ObjectFieldMustBeSimpleString bool + CaseSensitive bool +} + +// API the public interface of this package. +// Primary Marshal and Unmarshal. +type API interface { + IteratorPool + StreamPool + MarshalToString(v interface{}) (string, error) + Marshal(v interface{}) ([]byte, error) + MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) + UnmarshalFromString(str string, v interface{}) error + Unmarshal(data []byte, v interface{}) error + Get(data []byte, path ...interface{}) Any + NewEncoder(writer io.Writer) *Encoder + NewDecoder(reader io.Reader) *Decoder + Valid(data []byte) bool + RegisterExtension(extension Extension) + DecoderOf(typ reflect2.Type) ValDecoder + EncoderOf(typ reflect2.Type) ValEncoder +} + +// ConfigDefault the default API +var ConfigDefault = Config{ + EscapeHTML: true, +}.Froze() + +// ConfigCompatibleWithStandardLibrary tries to be 100% compatible with standard library behavior +var ConfigCompatibleWithStandardLibrary = Config{ + EscapeHTML: true, + SortMapKeys: true, + ValidateJsonRawMessage: true, +}.Froze() + +// ConfigFastest marshals float with only 6 digits precision +var ConfigFastest = Config{ + EscapeHTML: false, + MarshalFloatWith6Digits: true, // will lose precession + ObjectFieldMustBeSimpleString: true, // do not unescape object field +}.Froze() + +type frozenConfig struct { + configBeforeFrozen Config + sortMapKeys bool + indentionStep int + objectFieldMustBeSimpleString bool + onlyTaggedField bool + disallowUnknownFields bool + decoderCache *concurrent.Map + encoderCache *concurrent.Map + encoderExtension Extension + decoderExtension Extension + extraExtensions []Extension + streamPool *sync.Pool + iteratorPool *sync.Pool + caseSensitive bool +} + +func (cfg *frozenConfig) initCache() { + cfg.decoderCache = concurrent.NewMap() + cfg.encoderCache = concurrent.NewMap() +} + +func (cfg *frozenConfig) addDecoderToCache(cacheKey uintptr, decoder ValDecoder) { + cfg.decoderCache.Store(cacheKey, decoder) +} + +func (cfg *frozenConfig) addEncoderToCache(cacheKey uintptr, encoder ValEncoder) { + cfg.encoderCache.Store(cacheKey, encoder) +} + +func (cfg *frozenConfig) getDecoderFromCache(cacheKey uintptr) ValDecoder { + decoder, found := cfg.decoderCache.Load(cacheKey) + if found { + return decoder.(ValDecoder) + } + return nil +} + +func (cfg *frozenConfig) getEncoderFromCache(cacheKey uintptr) ValEncoder { + encoder, found := cfg.encoderCache.Load(cacheKey) + if found { + return encoder.(ValEncoder) + } + return nil +} + +var cfgCache = concurrent.NewMap() + +func getFrozenConfigFromCache(cfg Config) *frozenConfig { + obj, found := cfgCache.Load(cfg) + if found { + return obj.(*frozenConfig) + } + return nil +} + +func addFrozenConfigToCache(cfg Config, frozenConfig *frozenConfig) { + cfgCache.Store(cfg, frozenConfig) +} + +// Froze forge API from config +func (cfg Config) Froze() API { + api := &frozenConfig{ + sortMapKeys: cfg.SortMapKeys, + indentionStep: cfg.IndentionStep, + objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, + onlyTaggedField: cfg.OnlyTaggedField, + disallowUnknownFields: cfg.DisallowUnknownFields, + caseSensitive: cfg.CaseSensitive, + } + api.streamPool = &sync.Pool{ + New: func() interface{} { + return NewStream(api, nil, 512) + }, + } + api.iteratorPool = &sync.Pool{ + New: func() interface{} { + return NewIterator(api) + }, + } + api.initCache() + encoderExtension := EncoderExtension{} + decoderExtension := DecoderExtension{} + if cfg.MarshalFloatWith6Digits { + api.marshalFloatWith6Digits(encoderExtension) + } + if cfg.EscapeHTML { + api.escapeHTML(encoderExtension) + } + if cfg.UseNumber { + api.useNumber(decoderExtension) + } + if cfg.ValidateJsonRawMessage { + api.validateJsonRawMessage(encoderExtension) + } + api.encoderExtension = encoderExtension + api.decoderExtension = decoderExtension + api.configBeforeFrozen = cfg + return api +} + +func (cfg Config) frozeWithCacheReuse(extraExtensions []Extension) *frozenConfig { + api := getFrozenConfigFromCache(cfg) + if api != nil { + return api + } + api = cfg.Froze().(*frozenConfig) + for _, extension := range extraExtensions { + api.RegisterExtension(extension) + } + addFrozenConfigToCache(cfg, api) + return api +} + +func (cfg *frozenConfig) validateJsonRawMessage(extension EncoderExtension) { + encoder := &funcEncoder{func(ptr unsafe.Pointer, stream *Stream) { + rawMessage := *(*json.RawMessage)(ptr) + iter := cfg.BorrowIterator([]byte(rawMessage)) + defer cfg.ReturnIterator(iter) + iter.Read() + if iter.Error != nil && iter.Error != io.EOF { + stream.WriteRaw("null") + } else { + stream.WriteRaw(string(rawMessage)) + } + }, func(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 + }} + extension[reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem()] = encoder + extension[reflect2.TypeOfPtr((*RawMessage)(nil)).Elem()] = encoder +} + +func (cfg *frozenConfig) useNumber(extension DecoderExtension) { + extension[reflect2.TypeOfPtr((*interface{})(nil)).Elem()] = &funcDecoder{func(ptr unsafe.Pointer, iter *Iterator) { + exitingValue := *((*interface{})(ptr)) + if exitingValue != nil && reflect.TypeOf(exitingValue).Kind() == reflect.Ptr { + iter.ReadVal(exitingValue) + return + } + if iter.WhatIsNext() == NumberValue { + *((*interface{})(ptr)) = json.Number(iter.readNumberAsString()) + } else { + *((*interface{})(ptr)) = iter.Read() + } + }} +} +func (cfg *frozenConfig) getTagKey() string { + tagKey := cfg.configBeforeFrozen.TagKey + if tagKey == "" { + return "json" + } + return tagKey +} + +func (cfg *frozenConfig) RegisterExtension(extension Extension) { + cfg.extraExtensions = append(cfg.extraExtensions, extension) + copied := cfg.configBeforeFrozen + cfg.configBeforeFrozen = copied +} + +type lossyFloat32Encoder struct { +} + +func (encoder *lossyFloat32Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32Lossy(*((*float32)(ptr))) +} + +func (encoder *lossyFloat32Encoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type lossyFloat64Encoder struct { +} + +func (encoder *lossyFloat64Encoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64Lossy(*((*float64)(ptr))) +} + +func (encoder *lossyFloat64Encoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +// EnableLossyFloatMarshalling keeps 10**(-6) precision +// for float variables for better performance. +func (cfg *frozenConfig) marshalFloatWith6Digits(extension EncoderExtension) { + // for better performance + extension[reflect2.TypeOfPtr((*float32)(nil)).Elem()] = &lossyFloat32Encoder{} + extension[reflect2.TypeOfPtr((*float64)(nil)).Elem()] = &lossyFloat64Encoder{} +} + +type htmlEscapedStringEncoder struct { +} + +func (encoder *htmlEscapedStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteStringWithHTMLEscaped(str) +} + +func (encoder *htmlEscapedStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +func (cfg *frozenConfig) escapeHTML(encoderExtension EncoderExtension) { + encoderExtension[reflect2.TypeOfPtr((*string)(nil)).Elem()] = &htmlEscapedStringEncoder{} +} + +func (cfg *frozenConfig) cleanDecoders() { + typeDecoders = map[string]ValDecoder{} + fieldDecoders = map[string]ValDecoder{} + *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) +} + +func (cfg *frozenConfig) cleanEncoders() { + typeEncoders = map[string]ValEncoder{} + fieldEncoders = map[string]ValEncoder{} + *cfg = *(cfg.configBeforeFrozen.Froze().(*frozenConfig)) +} + +func (cfg *frozenConfig) MarshalToString(v interface{}) (string, error) { + stream := cfg.BorrowStream(nil) + defer cfg.ReturnStream(stream) + stream.WriteVal(v) + if stream.Error != nil { + return "", stream.Error + } + return string(stream.Buffer()), nil +} + +func (cfg *frozenConfig) Marshal(v interface{}) ([]byte, error) { + stream := cfg.BorrowStream(nil) + defer cfg.ReturnStream(stream) + stream.WriteVal(v) + if stream.Error != nil { + return nil, stream.Error + } + result := stream.Buffer() + copied := make([]byte, len(result)) + copy(copied, result) + return copied, nil +} + +func (cfg *frozenConfig) MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { + if prefix != "" { + panic("prefix is not supported") + } + for _, r := range indent { + if r != ' ' { + panic("indent can only be space") + } + } + newCfg := cfg.configBeforeFrozen + newCfg.IndentionStep = len(indent) + return newCfg.frozeWithCacheReuse(cfg.extraExtensions).Marshal(v) +} + +func (cfg *frozenConfig) UnmarshalFromString(str string, v interface{}) error { + data := []byte(str) + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.ReadVal(v) + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error + } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + return iter.Error +} + +func (cfg *frozenConfig) Get(data []byte, path ...interface{}) Any { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + return locatePath(iter, path) +} + +func (cfg *frozenConfig) Unmarshal(data []byte, v interface{}) error { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.ReadVal(v) + c := iter.nextToken() + if c == 0 { + if iter.Error == io.EOF { + return nil + } + return iter.Error + } + iter.ReportError("Unmarshal", "there are bytes left after unmarshal") + return iter.Error +} + +func (cfg *frozenConfig) NewEncoder(writer io.Writer) *Encoder { + stream := NewStream(cfg, writer, 512) + return &Encoder{stream} +} + +func (cfg *frozenConfig) NewDecoder(reader io.Reader) *Decoder { + iter := Parse(cfg, reader, 512) + return &Decoder{iter} +} + +func (cfg *frozenConfig) Valid(data []byte) bool { + iter := cfg.BorrowIterator(data) + defer cfg.ReturnIterator(iter) + iter.Skip() + return iter.Error == nil +} diff --git a/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md b/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md new file mode 100644 index 0000000..3095662 --- /dev/null +++ b/vendor/github.com/json-iterator/go/fuzzy_mode_convert_table.md @@ -0,0 +1,7 @@ +| json type \ dest type | bool | int | uint | float |string| +| --- | --- | --- | --- |--|--| +| number | positive => true
negative => true
zero => false| 23.2 => 23
-32.1 => -32| 12.1 => 12
-12.1 => 0|as normal|same as origin| +| string | empty string => false
string "0" => false
other strings => true | "123.32" => 123
"-123.4" => -123
"123.23xxxw" => 123
"abcde12" => 0
"-32.1" => -32| 13.2 => 13
-1.1 => 0 |12.1 => 12.1
-12.3 => -12.3
12.4xxa => 12.4
+1.1e2 =>110 |same as origin| +| bool | true => true
false => false| true => 1
false => 0 | true => 1
false => 0 |true => 1
false => 0|true => "true"
false => "false"| +| object | true | 0 | 0 |0|originnal json| +| array | empty array => false
nonempty array => true| [] => 0
[1,2] => 1 | [] => 0
[1,2] => 1 |[] => 0
[1,2] => 1|original json| \ No newline at end of file diff --git a/vendor/github.com/json-iterator/go/iter.go b/vendor/github.com/json-iterator/go/iter.go new file mode 100644 index 0000000..29b31cf --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter.go @@ -0,0 +1,349 @@ +package jsoniter + +import ( + "encoding/json" + "fmt" + "io" +) + +// ValueType the type for JSON element +type ValueType int + +const ( + // InvalidValue invalid JSON element + InvalidValue ValueType = iota + // StringValue JSON element "string" + StringValue + // NumberValue JSON element 100 or 0.10 + NumberValue + // NilValue JSON element null + NilValue + // BoolValue JSON element true or false + BoolValue + // ArrayValue JSON element [] + ArrayValue + // ObjectValue JSON element {} + ObjectValue +) + +var hexDigits []byte +var valueTypes []ValueType + +func init() { + hexDigits = make([]byte, 256) + for i := 0; i < len(hexDigits); i++ { + hexDigits[i] = 255 + } + for i := '0'; i <= '9'; i++ { + hexDigits[i] = byte(i - '0') + } + for i := 'a'; i <= 'f'; i++ { + hexDigits[i] = byte((i - 'a') + 10) + } + for i := 'A'; i <= 'F'; i++ { + hexDigits[i] = byte((i - 'A') + 10) + } + valueTypes = make([]ValueType, 256) + for i := 0; i < len(valueTypes); i++ { + valueTypes[i] = InvalidValue + } + valueTypes['"'] = StringValue + valueTypes['-'] = NumberValue + valueTypes['0'] = NumberValue + valueTypes['1'] = NumberValue + valueTypes['2'] = NumberValue + valueTypes['3'] = NumberValue + valueTypes['4'] = NumberValue + valueTypes['5'] = NumberValue + valueTypes['6'] = NumberValue + valueTypes['7'] = NumberValue + valueTypes['8'] = NumberValue + valueTypes['9'] = NumberValue + valueTypes['t'] = BoolValue + valueTypes['f'] = BoolValue + valueTypes['n'] = NilValue + valueTypes['['] = ArrayValue + valueTypes['{'] = ObjectValue +} + +// Iterator is a io.Reader like object, with JSON specific read functions. +// Error is not returned as return value, but stored as Error member on this iterator instance. +type Iterator struct { + cfg *frozenConfig + reader io.Reader + buf []byte + head int + tail int + depth int + captureStartedAt int + captured []byte + Error error + Attachment interface{} // open for customized decoder +} + +// NewIterator creates an empty Iterator instance +func NewIterator(cfg API) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: nil, + buf: nil, + head: 0, + tail: 0, + depth: 0, + } +} + +// Parse creates an Iterator instance from io.Reader +func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: reader, + buf: make([]byte, bufSize), + head: 0, + tail: 0, + depth: 0, + } +} + +// ParseBytes creates an Iterator instance from byte array +func ParseBytes(cfg API, input []byte) *Iterator { + return &Iterator{ + cfg: cfg.(*frozenConfig), + reader: nil, + buf: input, + head: 0, + tail: len(input), + depth: 0, + } +} + +// ParseString creates an Iterator instance from string +func ParseString(cfg API, input string) *Iterator { + return ParseBytes(cfg, []byte(input)) +} + +// Pool returns a pool can provide more iterator with same configuration +func (iter *Iterator) Pool() IteratorPool { + return iter.cfg +} + +// Reset reuse iterator instance by specifying another reader +func (iter *Iterator) Reset(reader io.Reader) *Iterator { + iter.reader = reader + iter.head = 0 + iter.tail = 0 + iter.depth = 0 + return iter +} + +// ResetBytes reuse iterator instance by specifying another byte array as input +func (iter *Iterator) ResetBytes(input []byte) *Iterator { + iter.reader = nil + iter.buf = input + iter.head = 0 + iter.tail = len(input) + iter.depth = 0 + return iter +} + +// WhatIsNext gets ValueType of relatively next json element +func (iter *Iterator) WhatIsNext() ValueType { + valueType := valueTypes[iter.nextToken()] + iter.unreadByte() + return valueType +} + +func (iter *Iterator) skipWhitespacesWithoutLoadMore() bool { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\t', '\r': + continue + } + iter.head = i + return false + } + return true +} + +func (iter *Iterator) isObjectEnd() bool { + c := iter.nextToken() + if c == ',' { + return false + } + if c == '}' { + return true + } + iter.ReportError("isObjectEnd", "object ended prematurely, unexpected char "+string([]byte{c})) + return true +} + +func (iter *Iterator) nextToken() byte { + // a variation of skip whitespaces, returning the next non-whitespace token + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\t', '\r': + continue + } + iter.head = i + 1 + return c + } + if !iter.loadMore() { + return 0 + } + } +} + +// ReportError record a error in iterator instance with current position. +func (iter *Iterator) ReportError(operation string, msg string) { + if iter.Error != nil { + if iter.Error != io.EOF { + return + } + } + peekStart := iter.head - 10 + if peekStart < 0 { + peekStart = 0 + } + peekEnd := iter.head + 10 + if peekEnd > iter.tail { + peekEnd = iter.tail + } + parsing := string(iter.buf[peekStart:peekEnd]) + contextStart := iter.head - 50 + if contextStart < 0 { + contextStart = 0 + } + contextEnd := iter.head + 50 + if contextEnd > iter.tail { + contextEnd = iter.tail + } + context := string(iter.buf[contextStart:contextEnd]) + iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", + operation, msg, iter.head-peekStart, parsing, context) +} + +// CurrentBuffer gets current buffer as string for debugging purpose +func (iter *Iterator) CurrentBuffer() string { + peekStart := iter.head - 10 + if peekStart < 0 { + peekStart = 0 + } + return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, + string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) +} + +func (iter *Iterator) readByte() (ret byte) { + if iter.head == iter.tail { + if iter.loadMore() { + ret = iter.buf[iter.head] + iter.head++ + return ret + } + return 0 + } + ret = iter.buf[iter.head] + iter.head++ + return ret +} + +func (iter *Iterator) loadMore() bool { + if iter.reader == nil { + if iter.Error == nil { + iter.head = iter.tail + iter.Error = io.EOF + } + return false + } + if iter.captured != nil { + iter.captured = append(iter.captured, + iter.buf[iter.captureStartedAt:iter.tail]...) + iter.captureStartedAt = 0 + } + for { + n, err := iter.reader.Read(iter.buf) + if n == 0 { + if err != nil { + if iter.Error == nil { + iter.Error = err + } + return false + } + } else { + iter.head = 0 + iter.tail = n + return true + } + } +} + +func (iter *Iterator) unreadByte() { + if iter.Error != nil { + return + } + iter.head-- + return +} + +// Read read the next JSON element as generic interface{}. +func (iter *Iterator) Read() interface{} { + valueType := iter.WhatIsNext() + switch valueType { + case StringValue: + return iter.ReadString() + case NumberValue: + if iter.cfg.configBeforeFrozen.UseNumber { + return json.Number(iter.readNumberAsString()) + } + return iter.ReadFloat64() + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + return nil + case BoolValue: + return iter.ReadBool() + case ArrayValue: + arr := []interface{}{} + iter.ReadArrayCB(func(iter *Iterator) bool { + var elem interface{} + iter.ReadVal(&elem) + arr = append(arr, elem) + return true + }) + return arr + case ObjectValue: + obj := map[string]interface{}{} + iter.ReadMapCB(func(Iter *Iterator, field string) bool { + var elem interface{} + iter.ReadVal(&elem) + obj[field] = elem + return true + }) + return obj + default: + iter.ReportError("Read", fmt.Sprintf("unexpected value type: %v", valueType)) + return nil + } +} + +// limit maximum depth of nesting, as allowed by https://tools.ietf.org/html/rfc7159#section-9 +const maxDepth = 10000 + +func (iter *Iterator) incrementDepth() (success bool) { + iter.depth++ + if iter.depth <= maxDepth { + return true + } + iter.ReportError("incrementDepth", "exceeded max depth") + return false +} + +func (iter *Iterator) decrementDepth() (success bool) { + iter.depth-- + if iter.depth >= 0 { + return true + } + iter.ReportError("decrementDepth", "unexpected negative nesting") + return false +} diff --git a/vendor/github.com/json-iterator/go/iter_array.go b/vendor/github.com/json-iterator/go/iter_array.go new file mode 100644 index 0000000..204fe0e --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_array.go @@ -0,0 +1,64 @@ +package jsoniter + +// ReadArray read array element, tells if the array has more element to read. +func (iter *Iterator) ReadArray() (ret bool) { + c := iter.nextToken() + switch c { + case 'n': + iter.skipThreeBytes('u', 'l', 'l') + return false // null + case '[': + c = iter.nextToken() + if c != ']' { + iter.unreadByte() + return true + } + return false + case ']': + return false + case ',': + return true + default: + iter.ReportError("ReadArray", "expect [ or , or ] or n, but found "+string([]byte{c})) + return + } +} + +// ReadArrayCB read array with callback +func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { + c := iter.nextToken() + if c == '[' { + if !iter.incrementDepth() { + return false + } + c = iter.nextToken() + if c != ']' { + iter.unreadByte() + if !callback(iter) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + for c == ',' { + if !callback(iter) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + } + if c != ']' { + iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) + iter.decrementDepth() + return false + } + return iter.decrementDepth() + } + return iter.decrementDepth() + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) + return false +} diff --git a/vendor/github.com/json-iterator/go/iter_float.go b/vendor/github.com/json-iterator/go/iter_float.go new file mode 100644 index 0000000..8a3d8b6 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_float.go @@ -0,0 +1,342 @@ +package jsoniter + +import ( + "encoding/json" + "io" + "math/big" + "strconv" + "strings" + "unsafe" +) + +var floatDigits []int8 + +const invalidCharForNumber = int8(-1) +const endOfNumber = int8(-2) +const dotInNumber = int8(-3) + +func init() { + floatDigits = make([]int8, 256) + for i := 0; i < len(floatDigits); i++ { + floatDigits[i] = invalidCharForNumber + } + for i := int8('0'); i <= int8('9'); i++ { + floatDigits[i] = i - int8('0') + } + floatDigits[','] = endOfNumber + floatDigits[']'] = endOfNumber + floatDigits['}'] = endOfNumber + floatDigits[' '] = endOfNumber + floatDigits['\t'] = endOfNumber + floatDigits['\n'] = endOfNumber + floatDigits['.'] = dotInNumber +} + +// ReadBigFloat read big.Float +func (iter *Iterator) ReadBigFloat() (ret *big.Float) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return nil + } + prec := 64 + if len(str) > prec { + prec = len(str) + } + val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) + if err != nil { + iter.Error = err + return nil + } + return val +} + +// ReadBigInt read big.Int +func (iter *Iterator) ReadBigInt() (ret *big.Int) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return nil + } + ret = big.NewInt(0) + var success bool + ret, success = ret.SetString(str, 10) + if !success { + iter.ReportError("ReadBigInt", "invalid big int") + return nil + } + return ret +} + +//ReadFloat32 read float32 +func (iter *Iterator) ReadFloat32() (ret float32) { + c := iter.nextToken() + if c == '-' { + return -iter.readPositiveFloat32() + } + iter.unreadByte() + return iter.readPositiveFloat32() +} + +func (iter *Iterator) readPositiveFloat32() (ret float32) { + i := iter.head + // first char + if i == iter.tail { + return iter.readFloat32SlowPath() + } + c := iter.buf[i] + i++ + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat32SlowPath() + case endOfNumber: + iter.ReportError("readFloat32", "empty number") + return + case dotInNumber: + iter.ReportError("readFloat32", "leading dot is invalid") + return + case 0: + if i == iter.tail { + return iter.readFloat32SlowPath() + } + c = iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.ReportError("readFloat32", "leading zero is invalid") + return + } + } + value := uint64(ind) + // chars before dot +non_decimal_loop: + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat32SlowPath() + case endOfNumber: + iter.head = i + return float32(value) + case dotInNumber: + break non_decimal_loop + } + if value > uint64SafeToMultiple10 { + return iter.readFloat32SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; + } + // chars after dot + if c == '.' { + i++ + decimalPlaces := 0 + if i == iter.tail { + return iter.readFloat32SlowPath() + } + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case endOfNumber: + if decimalPlaces > 0 && decimalPlaces < len(pow10) { + iter.head = i + return float32(float64(value) / float64(pow10[decimalPlaces])) + } + // too many decimal places + return iter.readFloat32SlowPath() + case invalidCharForNumber, dotInNumber: + return iter.readFloat32SlowPath() + } + decimalPlaces++ + if value > uint64SafeToMultiple10 { + return iter.readFloat32SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) + } + } + return iter.readFloat32SlowPath() +} + +func (iter *Iterator) readNumberAsString() (ret string) { + strBuf := [16]byte{} + str := strBuf[0:0] +load_loop: + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case '+', '-', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + str = append(str, c) + continue + default: + iter.head = i + break load_loop + } + } + if !iter.loadMore() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF { + return + } + if len(str) == 0 { + iter.ReportError("readNumberAsString", "invalid number") + } + return *(*string)(unsafe.Pointer(&str)) +} + +func (iter *Iterator) readFloat32SlowPath() (ret float32) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return + } + errMsg := validateFloat(str) + if errMsg != "" { + iter.ReportError("readFloat32SlowPath", errMsg) + return + } + val, err := strconv.ParseFloat(str, 32) + if err != nil { + iter.Error = err + return + } + return float32(val) +} + +// ReadFloat64 read float64 +func (iter *Iterator) ReadFloat64() (ret float64) { + c := iter.nextToken() + if c == '-' { + return -iter.readPositiveFloat64() + } + iter.unreadByte() + return iter.readPositiveFloat64() +} + +func (iter *Iterator) readPositiveFloat64() (ret float64) { + i := iter.head + // first char + if i == iter.tail { + return iter.readFloat64SlowPath() + } + c := iter.buf[i] + i++ + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat64SlowPath() + case endOfNumber: + iter.ReportError("readFloat64", "empty number") + return + case dotInNumber: + iter.ReportError("readFloat64", "leading dot is invalid") + return + case 0: + if i == iter.tail { + return iter.readFloat64SlowPath() + } + c = iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.ReportError("readFloat64", "leading zero is invalid") + return + } + } + value := uint64(ind) + // chars before dot +non_decimal_loop: + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case invalidCharForNumber: + return iter.readFloat64SlowPath() + case endOfNumber: + iter.head = i + return float64(value) + case dotInNumber: + break non_decimal_loop + } + if value > uint64SafeToMultiple10 { + return iter.readFloat64SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) // value = value * 10 + ind; + } + // chars after dot + if c == '.' { + i++ + decimalPlaces := 0 + if i == iter.tail { + return iter.readFloat64SlowPath() + } + for ; i < iter.tail; i++ { + c = iter.buf[i] + ind := floatDigits[c] + switch ind { + case endOfNumber: + if decimalPlaces > 0 && decimalPlaces < len(pow10) { + iter.head = i + return float64(value) / float64(pow10[decimalPlaces]) + } + // too many decimal places + return iter.readFloat64SlowPath() + case invalidCharForNumber, dotInNumber: + return iter.readFloat64SlowPath() + } + decimalPlaces++ + if value > uint64SafeToMultiple10 { + return iter.readFloat64SlowPath() + } + value = (value << 3) + (value << 1) + uint64(ind) + if value > maxFloat64 { + return iter.readFloat64SlowPath() + } + } + } + return iter.readFloat64SlowPath() +} + +func (iter *Iterator) readFloat64SlowPath() (ret float64) { + str := iter.readNumberAsString() + if iter.Error != nil && iter.Error != io.EOF { + return + } + errMsg := validateFloat(str) + if errMsg != "" { + iter.ReportError("readFloat64SlowPath", errMsg) + return + } + val, err := strconv.ParseFloat(str, 64) + if err != nil { + iter.Error = err + return + } + return val +} + +func validateFloat(str string) string { + // strconv.ParseFloat is not validating `1.` or `1.e1` + if len(str) == 0 { + return "empty number" + } + if str[0] == '-' { + return "-- is not valid" + } + dotPos := strings.IndexByte(str, '.') + if dotPos != -1 { + if dotPos == len(str)-1 { + return "dot can not be last character" + } + switch str[dotPos+1] { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + default: + return "missing digit after dot" + } + } + return "" +} + +// ReadNumber read json.Number +func (iter *Iterator) ReadNumber() (ret json.Number) { + return json.Number(iter.readNumberAsString()) +} diff --git a/vendor/github.com/json-iterator/go/iter_int.go b/vendor/github.com/json-iterator/go/iter_int.go new file mode 100644 index 0000000..d786a89 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_int.go @@ -0,0 +1,346 @@ +package jsoniter + +import ( + "math" + "strconv" +) + +var intDigits []int8 + +const uint32SafeToMultiply10 = uint32(0xffffffff)/10 - 1 +const uint64SafeToMultiple10 = uint64(0xffffffffffffffff)/10 - 1 +const maxFloat64 = 1<<53 - 1 + +func init() { + intDigits = make([]int8, 256) + for i := 0; i < len(intDigits); i++ { + intDigits[i] = invalidCharForNumber + } + for i := int8('0'); i <= int8('9'); i++ { + intDigits[i] = i - int8('0') + } +} + +// ReadUint read uint +func (iter *Iterator) ReadUint() uint { + if strconv.IntSize == 32 { + return uint(iter.ReadUint32()) + } + return uint(iter.ReadUint64()) +} + +// ReadInt read int +func (iter *Iterator) ReadInt() int { + if strconv.IntSize == 32 { + return int(iter.ReadInt32()) + } + return int(iter.ReadInt64()) +} + +// ReadInt8 read int8 +func (iter *Iterator) ReadInt8() (ret int8) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt8+1 { + iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int8(val) + } + val := iter.readUint32(c) + if val > math.MaxInt8 { + iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int8(val) +} + +// ReadUint8 read uint8 +func (iter *Iterator) ReadUint8() (ret uint8) { + val := iter.readUint32(iter.nextToken()) + if val > math.MaxUint8 { + iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return uint8(val) +} + +// ReadInt16 read int16 +func (iter *Iterator) ReadInt16() (ret int16) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt16+1 { + iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int16(val) + } + val := iter.readUint32(c) + if val > math.MaxInt16 { + iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int16(val) +} + +// ReadUint16 read uint16 +func (iter *Iterator) ReadUint16() (ret uint16) { + val := iter.readUint32(iter.nextToken()) + if val > math.MaxUint16 { + iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return uint16(val) +} + +// ReadInt32 read int32 +func (iter *Iterator) ReadInt32() (ret int32) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint32(iter.readByte()) + if val > math.MaxInt32+1 { + iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return -int32(val) + } + val := iter.readUint32(c) + if val > math.MaxInt32 { + iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) + return + } + return int32(val) +} + +// ReadUint32 read uint32 +func (iter *Iterator) ReadUint32() (ret uint32) { + return iter.readUint32(iter.nextToken()) +} + +func (iter *Iterator) readUint32(c byte) (ret uint32) { + ind := intDigits[c] + if ind == 0 { + iter.assertInteger() + return 0 // single zero + } + if ind == invalidCharForNumber { + iter.ReportError("readUint32", "unexpected character: "+string([]byte{byte(ind)})) + return + } + value := uint32(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint32(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint32(ind2)*10 + uint32(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint32(ind2)*100 + uint32(ind3)*10 + uint32(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint32(ind2)*1000 + uint32(ind3)*100 + uint32(ind4)*10 + uint32(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint32(ind2)*10000 + uint32(ind3)*1000 + uint32(ind4)*100 + uint32(ind5)*10 + uint32(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint32(ind2)*100000 + uint32(ind3)*10000 + uint32(ind4)*1000 + uint32(ind5)*100 + uint32(ind6)*10 + uint32(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint32(ind2)*1000000 + uint32(ind3)*100000 + uint32(ind4)*10000 + uint32(ind5)*1000 + uint32(ind6)*100 + uint32(ind7)*10 + uint32(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } + for { + for i := iter.head; i < iter.tail; i++ { + ind = intDigits[iter.buf[i]] + if ind == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + if value > uint32SafeToMultiply10 { + value2 := (value << 3) + (value << 1) + uint32(ind) + if value2 < value { + iter.ReportError("readUint32", "overflow") + return + } + value = value2 + continue + } + value = (value << 3) + (value << 1) + uint32(ind) + } + if !iter.loadMore() { + iter.assertInteger() + return value + } + } +} + +// ReadInt64 read int64 +func (iter *Iterator) ReadInt64() (ret int64) { + c := iter.nextToken() + if c == '-' { + val := iter.readUint64(iter.readByte()) + if val > math.MaxInt64+1 { + iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) + return + } + return -int64(val) + } + val := iter.readUint64(c) + if val > math.MaxInt64 { + iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) + return + } + return int64(val) +} + +// ReadUint64 read uint64 +func (iter *Iterator) ReadUint64() uint64 { + return iter.readUint64(iter.nextToken()) +} + +func (iter *Iterator) readUint64(c byte) (ret uint64) { + ind := intDigits[c] + if ind == 0 { + iter.assertInteger() + return 0 // single zero + } + if ind == invalidCharForNumber { + iter.ReportError("readUint64", "unexpected character: "+string([]byte{byte(ind)})) + return + } + value := uint64(ind) + if iter.tail-iter.head > 10 { + i := iter.head + ind2 := intDigits[iter.buf[i]] + if ind2 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + i++ + ind3 := intDigits[iter.buf[i]] + if ind3 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10 + uint64(ind2) + } + //iter.head = i + 1 + //value = value * 100 + uint32(ind2) * 10 + uint32(ind3) + i++ + ind4 := intDigits[iter.buf[i]] + if ind4 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100 + uint64(ind2)*10 + uint64(ind3) + } + i++ + ind5 := intDigits[iter.buf[i]] + if ind5 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000 + uint64(ind2)*100 + uint64(ind3)*10 + uint64(ind4) + } + i++ + ind6 := intDigits[iter.buf[i]] + if ind6 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*10000 + uint64(ind2)*1000 + uint64(ind3)*100 + uint64(ind4)*10 + uint64(ind5) + } + i++ + ind7 := intDigits[iter.buf[i]] + if ind7 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*100000 + uint64(ind2)*10000 + uint64(ind3)*1000 + uint64(ind4)*100 + uint64(ind5)*10 + uint64(ind6) + } + i++ + ind8 := intDigits[iter.buf[i]] + if ind8 == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value*1000000 + uint64(ind2)*100000 + uint64(ind3)*10000 + uint64(ind4)*1000 + uint64(ind5)*100 + uint64(ind6)*10 + uint64(ind7) + } + i++ + ind9 := intDigits[iter.buf[i]] + value = value*10000000 + uint64(ind2)*1000000 + uint64(ind3)*100000 + uint64(ind4)*10000 + uint64(ind5)*1000 + uint64(ind6)*100 + uint64(ind7)*10 + uint64(ind8) + iter.head = i + if ind9 == invalidCharForNumber { + iter.assertInteger() + return value + } + } + for { + for i := iter.head; i < iter.tail; i++ { + ind = intDigits[iter.buf[i]] + if ind == invalidCharForNumber { + iter.head = i + iter.assertInteger() + return value + } + if value > uint64SafeToMultiple10 { + value2 := (value << 3) + (value << 1) + uint64(ind) + if value2 < value { + iter.ReportError("readUint64", "overflow") + return + } + value = value2 + continue + } + value = (value << 3) + (value << 1) + uint64(ind) + } + if !iter.loadMore() { + iter.assertInteger() + return value + } + } +} + +func (iter *Iterator) assertInteger() { + if iter.head < iter.tail && iter.buf[iter.head] == '.' { + iter.ReportError("assertInteger", "can not decode float as int") + } +} diff --git a/vendor/github.com/json-iterator/go/iter_object.go b/vendor/github.com/json-iterator/go/iter_object.go new file mode 100644 index 0000000..58ee89c --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_object.go @@ -0,0 +1,267 @@ +package jsoniter + +import ( + "fmt" + "strings" +) + +// ReadObject read one field from object. +// If object ended, returns empty string. +// Otherwise, returns the field name. +func (iter *Iterator) ReadObject() (ret string) { + c := iter.nextToken() + switch c { + case 'n': + iter.skipThreeBytes('u', 'l', 'l') + return "" // null + case '{': + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field + } + if c == '}' { + return "" // end of object + } + iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) + return + case ',': + field := iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + return field + case '}': + return "" // end of object + default: + iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) + return + } +} + +// CaseInsensitive +func (iter *Iterator) readFieldHash() int64 { + hash := int64(0x811c9dc5) + c := iter.nextToken() + if c != '"' { + iter.ReportError("readFieldHash", `expect ", but found `+string([]byte{c})) + return 0 + } + for { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + b := iter.buf[i] + if b == '\\' { + iter.head = i + for _, b := range iter.readStringSlowPath() { + if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash + } + if b == '"' { + iter.head = i + 1 + c = iter.nextToken() + if c != ':' { + iter.ReportError("readFieldHash", `expect :, but found `+string([]byte{c})) + return 0 + } + return hash + } + if 'A' <= b && b <= 'Z' && !iter.cfg.caseSensitive { + b += 'a' - 'A' + } + hash ^= int64(b) + hash *= 0x1000193 + } + if !iter.loadMore() { + iter.ReportError("readFieldHash", `incomplete field name`) + return 0 + } + } +} + +func calcHash(str string, caseSensitive bool) int64 { + if !caseSensitive { + str = strings.ToLower(str) + } + hash := int64(0x811c9dc5) + for _, b := range []byte(str) { + hash ^= int64(b) + hash *= 0x1000193 + } + return int64(hash) +} + +// ReadObjectCB read object with callback, the key is ascii only and field name not copied +func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { + c := iter.nextToken() + var field string + if c == '{' { + if !iter.incrementDepth() { + return false + } + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + for c == ',' { + field = iter.ReadString() + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + } + if c != '}' { + iter.ReportError("ReadObjectCB", `object not ended with }`) + iter.decrementDepth() + return false + } + return iter.decrementDepth() + } + if c == '}' { + return iter.decrementDepth() + } + iter.ReportError("ReadObjectCB", `expect " after {, but found `+string([]byte{c})) + iter.decrementDepth() + return false + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) + return false +} + +// ReadMapCB read map with callback, the key can be any string +func (iter *Iterator) ReadMapCB(callback func(*Iterator, string) bool) bool { + c := iter.nextToken() + if c == '{' { + if !iter.incrementDepth() { + return false + } + c = iter.nextToken() + if c == '"' { + iter.unreadByte() + field := iter.ReadString() + if iter.nextToken() != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + iter.decrementDepth() + return false + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + for c == ',' { + field = iter.ReadString() + if iter.nextToken() != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + iter.decrementDepth() + return false + } + if !callback(iter, field) { + iter.decrementDepth() + return false + } + c = iter.nextToken() + } + if c != '}' { + iter.ReportError("ReadMapCB", `object not ended with }`) + iter.decrementDepth() + return false + } + return iter.decrementDepth() + } + if c == '}' { + return iter.decrementDepth() + } + iter.ReportError("ReadMapCB", `expect " after {, but found `+string([]byte{c})) + iter.decrementDepth() + return false + } + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return true // null + } + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return false +} + +func (iter *Iterator) readObjectStart() bool { + c := iter.nextToken() + if c == '{' { + c = iter.nextToken() + if c == '}' { + return false + } + iter.unreadByte() + return true + } else if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return false + } + iter.ReportError("readObjectStart", "expect { or n, but found "+string([]byte{c})) + return false +} + +func (iter *Iterator) readObjectFieldAsBytes() (ret []byte) { + str := iter.ReadStringAsSlice() + if iter.skipWhitespacesWithoutLoadMore() { + if ret == nil { + ret = make([]byte, len(str)) + copy(ret, str) + } + if !iter.loadMore() { + return + } + } + if iter.buf[iter.head] != ':' { + iter.ReportError("readObjectFieldAsBytes", "expect : after object field, but found "+string([]byte{iter.buf[iter.head]})) + return + } + iter.head++ + if iter.skipWhitespacesWithoutLoadMore() { + if ret == nil { + ret = make([]byte, len(str)) + copy(ret, str) + } + if !iter.loadMore() { + return + } + } + if ret == nil { + return str + } + return ret +} diff --git a/vendor/github.com/json-iterator/go/iter_skip.go b/vendor/github.com/json-iterator/go/iter_skip.go new file mode 100644 index 0000000..e91eefb --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip.go @@ -0,0 +1,130 @@ +package jsoniter + +import "fmt" + +// ReadNil reads a json object as nil and +// returns whether it's a nil or not +func (iter *Iterator) ReadNil() (ret bool) { + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') // null + return true + } + iter.unreadByte() + return false +} + +// ReadBool reads a json object as BoolValue +func (iter *Iterator) ReadBool() (ret bool) { + c := iter.nextToken() + if c == 't' { + iter.skipThreeBytes('r', 'u', 'e') + return true + } + if c == 'f' { + iter.skipFourBytes('a', 'l', 's', 'e') + return false + } + iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) + return +} + +// SkipAndReturnBytes skip next JSON element, and return its content as []byte. +// The []byte can be kept, it is a copy of data. +func (iter *Iterator) SkipAndReturnBytes() []byte { + iter.startCapture(iter.head) + iter.Skip() + return iter.stopCapture() +} + +// SkipAndAppendBytes skips next JSON element and appends its content to +// buffer, returning the result. +func (iter *Iterator) SkipAndAppendBytes(buf []byte) []byte { + iter.startCaptureTo(buf, iter.head) + iter.Skip() + return iter.stopCapture() +} + +func (iter *Iterator) startCaptureTo(buf []byte, captureStartedAt int) { + if iter.captured != nil { + panic("already in capture mode") + } + iter.captureStartedAt = captureStartedAt + iter.captured = buf +} + +func (iter *Iterator) startCapture(captureStartedAt int) { + iter.startCaptureTo(make([]byte, 0, 32), captureStartedAt) +} + +func (iter *Iterator) stopCapture() []byte { + if iter.captured == nil { + panic("not in capture mode") + } + captured := iter.captured + remaining := iter.buf[iter.captureStartedAt:iter.head] + iter.captureStartedAt = -1 + iter.captured = nil + return append(captured, remaining...) +} + +// Skip skips a json object and positions to relatively the next json object +func (iter *Iterator) Skip() { + c := iter.nextToken() + switch c { + case '"': + iter.skipString() + case 'n': + iter.skipThreeBytes('u', 'l', 'l') // null + case 't': + iter.skipThreeBytes('r', 'u', 'e') // true + case 'f': + iter.skipFourBytes('a', 'l', 's', 'e') // false + case '0': + iter.unreadByte() + iter.ReadFloat32() + case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': + iter.skipNumber() + case '[': + iter.skipArray() + case '{': + iter.skipObject() + default: + iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) + return + } +} + +func (iter *Iterator) skipFourBytes(b1, b2, b3, b4 byte) { + if iter.readByte() != b1 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b2 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b3 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } + if iter.readByte() != b4 { + iter.ReportError("skipFourBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3, b4}))) + return + } +} + +func (iter *Iterator) skipThreeBytes(b1, b2, b3 byte) { + if iter.readByte() != b1 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } + if iter.readByte() != b2 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } + if iter.readByte() != b3 { + iter.ReportError("skipThreeBytes", fmt.Sprintf("expect %s", string([]byte{b1, b2, b3}))) + return + } +} diff --git a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go new file mode 100644 index 0000000..9303de4 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go @@ -0,0 +1,163 @@ +//+build jsoniter_sloppy + +package jsoniter + +// sloppy but faster implementation, do not validate the input json + +func (iter *Iterator) skipNumber() { + for { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case ' ', '\n', '\r', '\t', ',', '}', ']': + iter.head = i + return + } + } + if !iter.loadMore() { + return + } + } +} + +func (iter *Iterator) skipArray() { + level := 1 + if !iter.incrementDepth() { + return + } + for { + for i := iter.head; i < iter.tail; i++ { + switch iter.buf[i] { + case '"': // If inside string, skip it + iter.head = i + 1 + iter.skipString() + i = iter.head - 1 // it will be i++ soon + case '[': // If open symbol, increase level + level++ + if !iter.incrementDepth() { + return + } + case ']': // If close symbol, increase level + level-- + if !iter.decrementDepth() { + return + } + + // If we have returned to the original level, we're done + if level == 0 { + iter.head = i + 1 + return + } + } + } + if !iter.loadMore() { + iter.ReportError("skipObject", "incomplete array") + return + } + } +} + +func (iter *Iterator) skipObject() { + level := 1 + if !iter.incrementDepth() { + return + } + + for { + for i := iter.head; i < iter.tail; i++ { + switch iter.buf[i] { + case '"': // If inside string, skip it + iter.head = i + 1 + iter.skipString() + i = iter.head - 1 // it will be i++ soon + case '{': // If open symbol, increase level + level++ + if !iter.incrementDepth() { + return + } + case '}': // If close symbol, increase level + level-- + if !iter.decrementDepth() { + return + } + + // If we have returned to the original level, we're done + if level == 0 { + iter.head = i + 1 + return + } + } + } + if !iter.loadMore() { + iter.ReportError("skipObject", "incomplete object") + return + } + } +} + +func (iter *Iterator) skipString() { + for { + end, escaped := iter.findStringEnd() + if end == -1 { + if !iter.loadMore() { + iter.ReportError("skipString", "incomplete string") + return + } + if escaped { + iter.head = 1 // skip the first char as last char read is \ + } + } else { + iter.head = end + return + } + } +} + +// adapted from: https://github.com/buger/jsonparser/blob/master/parser.go +// Tries to find the end of string +// Support if string contains escaped quote symbols. +func (iter *Iterator) findStringEnd() (int, bool) { + escaped := false + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + if !escaped { + return i + 1, false + } + j := i - 1 + for { + if j < iter.head || iter.buf[j] != '\\' { + // even number of backslashes + // either end of buffer, or " found + return i + 1, true + } + j-- + if j < iter.head || iter.buf[j] != '\\' { + // odd number of backslashes + // it is \" or \\\" + break + } + j-- + } + } else if c == '\\' { + escaped = true + } + } + j := iter.tail - 1 + for { + if j < iter.head || iter.buf[j] != '\\' { + // even number of backslashes + // either end of buffer, or " found + return -1, false // do not end with \ + } + j-- + if j < iter.head || iter.buf[j] != '\\' { + // odd number of backslashes + // it is \" or \\\" + break + } + j-- + + } + return -1, true // end with \ +} diff --git a/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go new file mode 100644 index 0000000..6cf66d0 --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_skip_strict.go @@ -0,0 +1,99 @@ +//+build !jsoniter_sloppy + +package jsoniter + +import ( + "fmt" + "io" +) + +func (iter *Iterator) skipNumber() { + if !iter.trySkipNumber() { + iter.unreadByte() + if iter.Error != nil && iter.Error != io.EOF { + return + } + iter.ReadFloat64() + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = nil + iter.ReadBigFloat() + } + } +} + +func (iter *Iterator) trySkipNumber() bool { + dotFound := false + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + case '.': + if dotFound { + iter.ReportError("validateNumber", `more than one dot found in number`) + return true // already failed + } + if i+1 == iter.tail { + return false + } + c = iter.buf[i+1] + switch c { + case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': + default: + iter.ReportError("validateNumber", `missing digit after dot`) + return true // already failed + } + dotFound = true + default: + switch c { + case ',', ']', '}', ' ', '\t', '\n', '\r': + if iter.head == i { + return false // if - without following digits + } + iter.head = i + return true // must be valid + } + return false // may be invalid + } + } + return false +} + +func (iter *Iterator) skipString() { + if !iter.trySkipString() { + iter.unreadByte() + iter.ReadString() + } +} + +func (iter *Iterator) trySkipString() bool { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + iter.head = i + 1 + return true // valid + } else if c == '\\' { + return false + } else if c < ' ' { + iter.ReportError("trySkipString", + fmt.Sprintf(`invalid control character found: %d`, c)) + return true // already failed + } + } + return false +} + +func (iter *Iterator) skipObject() { + iter.unreadByte() + iter.ReadObjectCB(func(iter *Iterator, field string) bool { + iter.Skip() + return true + }) +} + +func (iter *Iterator) skipArray() { + iter.unreadByte() + iter.ReadArrayCB(func(iter *Iterator) bool { + iter.Skip() + return true + }) +} diff --git a/vendor/github.com/json-iterator/go/iter_str.go b/vendor/github.com/json-iterator/go/iter_str.go new file mode 100644 index 0000000..adc487e --- /dev/null +++ b/vendor/github.com/json-iterator/go/iter_str.go @@ -0,0 +1,215 @@ +package jsoniter + +import ( + "fmt" + "unicode/utf16" +) + +// ReadString read string from iterator +func (iter *Iterator) ReadString() (ret string) { + c := iter.nextToken() + if c == '"' { + for i := iter.head; i < iter.tail; i++ { + c := iter.buf[i] + if c == '"' { + ret = string(iter.buf[iter.head:i]) + iter.head = i + 1 + return ret + } else if c == '\\' { + break + } else if c < ' ' { + iter.ReportError("ReadString", + fmt.Sprintf(`invalid control character found: %d`, c)) + return + } + } + return iter.readStringSlowPath() + } else if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return "" + } + iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) + return +} + +func (iter *Iterator) readStringSlowPath() (ret string) { + var str []byte + var c byte + for iter.Error == nil { + c = iter.readByte() + if c == '"' { + return string(str) + } + if c == '\\' { + c = iter.readByte() + str = iter.readEscapedChar(c, str) + } else { + str = append(str, c) + } + } + iter.ReportError("readStringSlowPath", "unexpected end of input") + return +} + +func (iter *Iterator) readEscapedChar(c byte, str []byte) []byte { + switch c { + case 'u': + r := iter.readU4() + if utf16.IsSurrogate(r) { + c = iter.readByte() + if iter.Error != nil { + return nil + } + if c != '\\' { + iter.unreadByte() + str = appendRune(str, r) + return str + } + c = iter.readByte() + if iter.Error != nil { + return nil + } + if c != 'u' { + str = appendRune(str, r) + return iter.readEscapedChar(c, str) + } + r2 := iter.readU4() + if iter.Error != nil { + return nil + } + combined := utf16.DecodeRune(r, r2) + if combined == '\uFFFD' { + str = appendRune(str, r) + str = appendRune(str, r2) + } else { + str = appendRune(str, combined) + } + } else { + str = appendRune(str, r) + } + case '"': + str = append(str, '"') + case '\\': + str = append(str, '\\') + case '/': + str = append(str, '/') + case 'b': + str = append(str, '\b') + case 'f': + str = append(str, '\f') + case 'n': + str = append(str, '\n') + case 'r': + str = append(str, '\r') + case 't': + str = append(str, '\t') + default: + iter.ReportError("readEscapedChar", + `invalid escape char after \`) + return nil + } + return str +} + +// ReadStringAsSlice read string from iterator without copying into string form. +// The []byte can not be kept, as it will change after next iterator call. +func (iter *Iterator) ReadStringAsSlice() (ret []byte) { + c := iter.nextToken() + if c == '"' { + for i := iter.head; i < iter.tail; i++ { + // require ascii string and no escape + // for: field name, base64, number + if iter.buf[i] == '"' { + // fast path: reuse the underlying buffer + ret = iter.buf[iter.head:i] + iter.head = i + 1 + return ret + } + } + readLen := iter.tail - iter.head + copied := make([]byte, readLen, readLen*2) + copy(copied, iter.buf[iter.head:iter.tail]) + iter.head = iter.tail + for iter.Error == nil { + c := iter.readByte() + if c == '"' { + return copied + } + copied = append(copied, c) + } + return copied + } + iter.ReportError("ReadStringAsSlice", `expects " or n, but found `+string([]byte{c})) + return +} + +func (iter *Iterator) readU4() (ret rune) { + for i := 0; i < 4; i++ { + c := iter.readByte() + if iter.Error != nil { + return + } + if c >= '0' && c <= '9' { + ret = ret*16 + rune(c-'0') + } else if c >= 'a' && c <= 'f' { + ret = ret*16 + rune(c-'a'+10) + } else if c >= 'A' && c <= 'F' { + ret = ret*16 + rune(c-'A'+10) + } else { + iter.ReportError("readU4", "expects 0~9 or a~f, but found "+string([]byte{c})) + return + } + } + return ret +} + +const ( + t1 = 0x00 // 0000 0000 + tx = 0x80 // 1000 0000 + t2 = 0xC0 // 1100 0000 + t3 = 0xE0 // 1110 0000 + t4 = 0xF0 // 1111 0000 + t5 = 0xF8 // 1111 1000 + + maskx = 0x3F // 0011 1111 + mask2 = 0x1F // 0001 1111 + mask3 = 0x0F // 0000 1111 + mask4 = 0x07 // 0000 0111 + + rune1Max = 1<<7 - 1 + rune2Max = 1<<11 - 1 + rune3Max = 1<<16 - 1 + + surrogateMin = 0xD800 + surrogateMax = 0xDFFF + + maxRune = '\U0010FFFF' // Maximum valid Unicode code point. + runeError = '\uFFFD' // the "error" Rune or "Unicode replacement character" +) + +func appendRune(p []byte, r rune) []byte { + // Negative values are erroneous. Making it unsigned addresses the problem. + switch i := uint32(r); { + case i <= rune1Max: + p = append(p, byte(r)) + return p + case i <= rune2Max: + p = append(p, t2|byte(r>>6)) + p = append(p, tx|byte(r)&maskx) + return p + case i > maxRune, surrogateMin <= i && i <= surrogateMax: + r = runeError + fallthrough + case i <= rune3Max: + p = append(p, t3|byte(r>>12)) + p = append(p, tx|byte(r>>6)&maskx) + p = append(p, tx|byte(r)&maskx) + return p + default: + p = append(p, t4|byte(r>>18)) + p = append(p, tx|byte(r>>12)&maskx) + p = append(p, tx|byte(r>>6)&maskx) + p = append(p, tx|byte(r)&maskx) + return p + } +} diff --git a/vendor/github.com/json-iterator/go/jsoniter.go b/vendor/github.com/json-iterator/go/jsoniter.go new file mode 100644 index 0000000..c2934f9 --- /dev/null +++ b/vendor/github.com/json-iterator/go/jsoniter.go @@ -0,0 +1,18 @@ +// Package jsoniter implements encoding and decoding of JSON as defined in +// RFC 4627 and provides interfaces with identical syntax of standard lib encoding/json. +// Converting from encoding/json to jsoniter is no more than replacing the package with jsoniter +// and variable type declarations (if any). +// jsoniter interfaces gives 100% compatibility with code using standard lib. +// +// "JSON and Go" +// (https://golang.org/doc/articles/json_and_go.html) +// gives a description of how Marshal/Unmarshal operate +// between arbitrary or predefined json objects and bytes, +// and it applies to jsoniter.Marshal/Unmarshal as well. +// +// Besides, jsoniter.Iterator provides a different set of interfaces +// iterating given bytes/string/reader +// and yielding parsed elements one by one. +// This set of interfaces reads input as required and gives +// better performance. +package jsoniter diff --git a/vendor/github.com/json-iterator/go/pool.go b/vendor/github.com/json-iterator/go/pool.go new file mode 100644 index 0000000..e2389b5 --- /dev/null +++ b/vendor/github.com/json-iterator/go/pool.go @@ -0,0 +1,42 @@ +package jsoniter + +import ( + "io" +) + +// IteratorPool a thread safe pool of iterators with same configuration +type IteratorPool interface { + BorrowIterator(data []byte) *Iterator + ReturnIterator(iter *Iterator) +} + +// StreamPool a thread safe pool of streams with same configuration +type StreamPool interface { + BorrowStream(writer io.Writer) *Stream + ReturnStream(stream *Stream) +} + +func (cfg *frozenConfig) BorrowStream(writer io.Writer) *Stream { + stream := cfg.streamPool.Get().(*Stream) + stream.Reset(writer) + return stream +} + +func (cfg *frozenConfig) ReturnStream(stream *Stream) { + stream.out = nil + stream.Error = nil + stream.Attachment = nil + cfg.streamPool.Put(stream) +} + +func (cfg *frozenConfig) BorrowIterator(data []byte) *Iterator { + iter := cfg.iteratorPool.Get().(*Iterator) + iter.ResetBytes(data) + return iter +} + +func (cfg *frozenConfig) ReturnIterator(iter *Iterator) { + iter.Error = nil + iter.Attachment = nil + cfg.iteratorPool.Put(iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect.go b/vendor/github.com/json-iterator/go/reflect.go new file mode 100644 index 0000000..39acb32 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect.go @@ -0,0 +1,337 @@ +package jsoniter + +import ( + "fmt" + "reflect" + "unsafe" + + "github.com/modern-go/reflect2" +) + +// ValDecoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValDecoder with json.Decoder. +// For json.Decoder's adapter, refer to jsoniter.AdapterDecoder(todo link). +// +// Reflection on type to create decoders, which is then cached +// Reflection on value is avoided as we can, as the reflect.Value itself will allocate, with following exceptions +// 1. create instance of new value, for example *int will need a int to be allocated +// 2. append to slice, if the existing cap is not enough, allocate will be done using Reflect.New +// 3. assignment to map, both key and value will be reflect.Value +// For a simple struct binding, it will be reflect.Value free and allocation free +type ValDecoder interface { + Decode(ptr unsafe.Pointer, iter *Iterator) +} + +// ValEncoder is an internal type registered to cache as needed. +// Don't confuse jsoniter.ValEncoder with json.Encoder. +// For json.Encoder's adapter, refer to jsoniter.AdapterEncoder(todo godoc link). +type ValEncoder interface { + IsEmpty(ptr unsafe.Pointer) bool + Encode(ptr unsafe.Pointer, stream *Stream) +} + +type checkIsEmpty interface { + IsEmpty(ptr unsafe.Pointer) bool +} + +type ctx struct { + *frozenConfig + prefix string + encoders map[reflect2.Type]ValEncoder + decoders map[reflect2.Type]ValDecoder +} + +func (b *ctx) caseSensitive() bool { + if b.frozenConfig == nil { + // default is case-insensitive + return false + } + return b.frozenConfig.caseSensitive +} + +func (b *ctx) append(prefix string) *ctx { + return &ctx{ + frozenConfig: b.frozenConfig, + prefix: b.prefix + " " + prefix, + encoders: b.encoders, + decoders: b.decoders, + } +} + +// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal +func (iter *Iterator) ReadVal(obj interface{}) { + depth := iter.depth + cacheKey := reflect2.RTypeOf(obj) + decoder := iter.cfg.getDecoderFromCache(cacheKey) + if decoder == nil { + typ := reflect2.TypeOf(obj) + if typ == nil || typ.Kind() != reflect.Ptr { + iter.ReportError("ReadVal", "can only unmarshal into pointer") + return + } + decoder = iter.cfg.DecoderOf(typ) + } + ptr := reflect2.PtrOf(obj) + if ptr == nil { + iter.ReportError("ReadVal", "can not read into nil pointer") + return + } + decoder.Decode(ptr, iter) + if iter.depth != depth { + iter.ReportError("ReadVal", "unexpected mismatched nesting") + return + } +} + +// WriteVal copy the go interface into underlying JSON, same as json.Marshal +func (stream *Stream) WriteVal(val interface{}) { + if nil == val { + stream.WriteNil() + return + } + cacheKey := reflect2.RTypeOf(val) + encoder := stream.cfg.getEncoderFromCache(cacheKey) + if encoder == nil { + typ := reflect2.TypeOf(val) + encoder = stream.cfg.EncoderOf(typ) + } + encoder.Encode(reflect2.PtrOf(val), stream) +} + +func (cfg *frozenConfig) DecoderOf(typ reflect2.Type) ValDecoder { + cacheKey := typ.RType() + decoder := cfg.getDecoderFromCache(cacheKey) + if decoder != nil { + return decoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + ptrType := typ.(*reflect2.UnsafePtrType) + decoder = decoderOfType(ctx, ptrType.Elem()) + cfg.addDecoderToCache(cacheKey, decoder) + return decoder +} + +func decoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfType(ctx, typ) + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) + for _, extension := range ctx.extraExtensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + return decoder +} + +func createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoders[typ] + if decoder != nil { + return decoder + } + placeholder := &placeholderDecoder{} + ctx.decoders[typ] = placeholder + decoder = _createDecoderOfType(ctx, typ) + placeholder.decoder = decoder + return decoder +} + +func _createDecoderOfType(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := createDecoderOfJsonRawMessage(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfJsonNumber(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfMarshaler(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfAny(ctx, typ) + if decoder != nil { + return decoder + } + decoder = createDecoderOfNative(ctx, typ) + if decoder != nil { + return decoder + } + switch typ.Kind() { + case reflect.Interface: + ifaceType, isIFace := typ.(*reflect2.UnsafeIFaceType) + if isIFace { + return &ifaceDecoder{valType: ifaceType} + } + return &efaceDecoder{} + case reflect.Struct: + return decoderOfStruct(ctx, typ) + case reflect.Array: + return decoderOfArray(ctx, typ) + case reflect.Slice: + return decoderOfSlice(ctx, typ) + case reflect.Map: + return decoderOfMap(ctx, typ) + case reflect.Ptr: + return decoderOfOptional(ctx, typ) + default: + return &lazyErrorDecoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +func (cfg *frozenConfig) EncoderOf(typ reflect2.Type) ValEncoder { + cacheKey := typ.RType() + encoder := cfg.getEncoderFromCache(cacheKey) + if encoder != nil { + return encoder + } + ctx := &ctx{ + frozenConfig: cfg, + prefix: "", + decoders: map[reflect2.Type]ValDecoder{}, + encoders: map[reflect2.Type]ValEncoder{}, + } + encoder = encoderOfType(ctx, typ) + if typ.LikePtr() { + encoder = &onePtrEncoder{encoder} + } + cfg.addEncoderToCache(cacheKey, encoder) + return encoder +} + +type onePtrEncoder struct { + encoder ValEncoder +} + +func (encoder *onePtrEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +func (encoder *onePtrEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func encoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfType(ctx, typ) + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) + for _, extension := range ctx.extraExtensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + return encoder +} + +func createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoders[typ] + if encoder != nil { + return encoder + } + placeholder := &placeholderEncoder{} + ctx.encoders[typ] = placeholder + encoder = _createEncoderOfType(ctx, typ) + placeholder.encoder = encoder + return encoder +} +func _createEncoderOfType(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := createEncoderOfJsonRawMessage(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfJsonNumber(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfMarshaler(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfAny(ctx, typ) + if encoder != nil { + return encoder + } + encoder = createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return encoderOfStruct(ctx, typ) + case reflect.Array: + return encoderOfArray(ctx, typ) + case reflect.Slice: + return encoderOfSlice(ctx, typ) + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return encoderOfOptional(ctx, typ) + default: + return &lazyErrorEncoder{err: fmt.Errorf("%s%s is unsupported type", ctx.prefix, typ.String())} + } +} + +type lazyErrorDecoder struct { + err error +} + +func (decoder *lazyErrorDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.WhatIsNext() != NilValue { + if iter.Error == nil { + iter.Error = decoder.err + } + } else { + iter.Skip() + } +} + +type lazyErrorEncoder struct { + err error +} + +func (encoder *lazyErrorEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if ptr == nil { + stream.WriteNil() + } else if stream.Error == nil { + stream.Error = encoder.err + } +} + +func (encoder *lazyErrorEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type placeholderDecoder struct { + decoder ValDecoder +} + +func (decoder *placeholderDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(ptr, iter) +} + +type placeholderEncoder struct { + encoder ValEncoder +} + +func (encoder *placeholderEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(ptr, stream) +} + +func (encoder *placeholderEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go new file mode 100644 index 0000000..13a0b7b --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -0,0 +1,104 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + decoder := decoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayDecoder{arrayType, decoder} +} + +func encoderOfArray(ctx *ctx, typ reflect2.Type) ValEncoder { + arrayType := typ.(*reflect2.UnsafeArrayType) + if arrayType.Len() == 0 { + return emptyArrayEncoder{} + } + encoder := encoderOfType(ctx.append("[arrayElem]"), arrayType.Elem()) + return &arrayEncoder{arrayType, encoder} +} + +type emptyArrayEncoder struct{} + +func (encoder emptyArrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyArray() +} + +func (encoder emptyArrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return true +} + +type arrayEncoder struct { + arrayType *reflect2.UnsafeArrayType + elemEncoder ValEncoder +} + +func (encoder *arrayEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteArrayStart() + elemPtr := unsafe.Pointer(ptr) + encoder.elemEncoder.Encode(elemPtr, stream) + for i := 1; i < encoder.arrayType.Len(); i++ { + stream.WriteMore() + elemPtr = encoder.arrayType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.arrayType, stream.Error.Error()) + } +} + +func (encoder *arrayEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type arrayDecoder struct { + arrayType *reflect2.UnsafeArrayType + elemDecoder ValDecoder +} + +func (decoder *arrayDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.arrayType, iter.Error.Error()) + } +} + +func (decoder *arrayDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + arrayType := decoder.arrayType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + return + } + if c != '[' { + iter.ReportError("decode array", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + return + } + iter.unreadByte() + elemPtr := arrayType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + if length >= arrayType.Len() { + iter.Skip() + continue + } + idx := length + length += 1 + elemPtr = arrayType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode array", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go new file mode 100644 index 0000000..8b6bc8b --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -0,0 +1,70 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "reflect" + "unsafe" +) + +type dynamicEncoder struct { + valType reflect2.Type +} + +func (encoder *dynamicEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + stream.WriteVal(obj) +} + +func (encoder *dynamicEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.valType.UnsafeIndirect(ptr) == nil +} + +type efaceDecoder struct { +} + +func (decoder *efaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + pObj := (*interface{})(ptr) + obj := *pObj + if obj == nil { + *pObj = iter.Read() + return + } + typ := reflect2.TypeOf(obj) + if typ.Kind() != reflect.Ptr { + *pObj = iter.Read() + return + } + ptrType := typ.(*reflect2.UnsafePtrType) + ptrElemType := ptrType.Elem() + if iter.WhatIsNext() == NilValue { + if ptrElemType.Kind() != reflect.Ptr { + iter.skipFourBytes('n', 'u', 'l', 'l') + *pObj = nil + return + } + } + if reflect2.IsNil(obj) { + obj := ptrElemType.New() + iter.ReadVal(obj) + *pObj = obj + return + } + iter.ReadVal(obj) +} + +type ifaceDecoder struct { + valType *reflect2.UnsafeIFaceType +} + +func (decoder *ifaceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + decoder.valType.UnsafeSet(ptr, decoder.valType.UnsafeNew()) + return + } + obj := decoder.valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + iter.ReportError("decode non empty interface", "can not unmarshal into nil") + return + } + iter.ReadVal(obj) +} diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go new file mode 100644 index 0000000..74a97bf --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -0,0 +1,483 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "reflect" + "sort" + "strings" + "unicode" + "unsafe" +) + +var typeDecoders = map[string]ValDecoder{} +var fieldDecoders = map[string]ValDecoder{} +var typeEncoders = map[string]ValEncoder{} +var fieldEncoders = map[string]ValEncoder{} +var extensions = []Extension{} + +// StructDescriptor describe how should we encode/decode the struct +type StructDescriptor struct { + Type reflect2.Type + Fields []*Binding +} + +// GetField get one field from the descriptor by its name. +// Can not use map here to keep field orders. +func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { + for _, binding := range structDescriptor.Fields { + if binding.Field.Name() == fieldName { + return binding + } + } + return nil +} + +// Binding describe how should we encode/decode the struct field +type Binding struct { + levels []int + Field reflect2.StructField + FromNames []string + ToNames []string + Encoder ValEncoder + Decoder ValDecoder +} + +// Extension the one for all SPI. Customize encoding/decoding by specifying alternate encoder/decoder. +// Can also rename fields by UpdateStructDescriptor. +type Extension interface { + UpdateStructDescriptor(structDescriptor *StructDescriptor) + CreateMapKeyDecoder(typ reflect2.Type) ValDecoder + CreateMapKeyEncoder(typ reflect2.Type) ValEncoder + CreateDecoder(typ reflect2.Type) ValDecoder + CreateEncoder(typ reflect2.Type) ValEncoder + DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder + DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder +} + +// DummyExtension embed this type get dummy implementation for all methods of Extension +type DummyExtension struct { +} + +// UpdateStructDescriptor No-op +func (extension *DummyExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension *DummyExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension *DummyExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// CreateDecoder No-op +func (extension *DummyExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder No-op +func (extension *DummyExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension *DummyExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension *DummyExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type EncoderExtension map[reflect2.Type]ValEncoder + +// UpdateStructDescriptor No-op +func (extension EncoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateDecoder No-op +func (extension EncoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateEncoder get encoder from map +func (extension EncoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return extension[typ] +} + +// CreateMapKeyDecoder No-op +func (extension EncoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension EncoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension EncoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension EncoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type DecoderExtension map[reflect2.Type]ValDecoder + +// UpdateStructDescriptor No-op +func (extension DecoderExtension) UpdateStructDescriptor(structDescriptor *StructDescriptor) { +} + +// CreateMapKeyDecoder No-op +func (extension DecoderExtension) CreateMapKeyDecoder(typ reflect2.Type) ValDecoder { + return nil +} + +// CreateMapKeyEncoder No-op +func (extension DecoderExtension) CreateMapKeyEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// CreateDecoder get decoder from map +func (extension DecoderExtension) CreateDecoder(typ reflect2.Type) ValDecoder { + return extension[typ] +} + +// CreateEncoder No-op +func (extension DecoderExtension) CreateEncoder(typ reflect2.Type) ValEncoder { + return nil +} + +// DecorateDecoder No-op +func (extension DecoderExtension) DecorateDecoder(typ reflect2.Type, decoder ValDecoder) ValDecoder { + return decoder +} + +// DecorateEncoder No-op +func (extension DecoderExtension) DecorateEncoder(typ reflect2.Type, encoder ValEncoder) ValEncoder { + return encoder +} + +type funcDecoder struct { + fun DecoderFunc +} + +func (decoder *funcDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.fun(ptr, iter) +} + +type funcEncoder struct { + fun EncoderFunc + isEmptyFunc func(ptr unsafe.Pointer) bool +} + +func (encoder *funcEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.fun(ptr, stream) +} + +func (encoder *funcEncoder) IsEmpty(ptr unsafe.Pointer) bool { + if encoder.isEmptyFunc == nil { + return false + } + return encoder.isEmptyFunc(ptr) +} + +// DecoderFunc the function form of TypeDecoder +type DecoderFunc func(ptr unsafe.Pointer, iter *Iterator) + +// EncoderFunc the function form of TypeEncoder +type EncoderFunc func(ptr unsafe.Pointer, stream *Stream) + +// RegisterTypeDecoderFunc register TypeDecoder for a type with function +func RegisterTypeDecoderFunc(typ string, fun DecoderFunc) { + typeDecoders[typ] = &funcDecoder{fun} +} + +// RegisterTypeDecoder register TypeDecoder for a typ +func RegisterTypeDecoder(typ string, decoder ValDecoder) { + typeDecoders[typ] = decoder +} + +// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function +func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { + RegisterFieldDecoder(typ, field, &funcDecoder{fun}) +} + +// RegisterFieldDecoder register TypeDecoder for a struct field +func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { + fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder +} + +// RegisterTypeEncoderFunc register TypeEncoder for a type with encode/isEmpty function +func RegisterTypeEncoderFunc(typ string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { + typeEncoders[typ] = &funcEncoder{fun, isEmptyFunc} +} + +// RegisterTypeEncoder register TypeEncoder for a type +func RegisterTypeEncoder(typ string, encoder ValEncoder) { + typeEncoders[typ] = encoder +} + +// RegisterFieldEncoderFunc register TypeEncoder for a struct field with encode/isEmpty function +func RegisterFieldEncoderFunc(typ string, field string, fun EncoderFunc, isEmptyFunc func(unsafe.Pointer) bool) { + RegisterFieldEncoder(typ, field, &funcEncoder{fun, isEmptyFunc}) +} + +// RegisterFieldEncoder register TypeEncoder for a struct field +func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { + fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder +} + +// RegisterExtension register extension +func RegisterExtension(extension Extension) { + extensions = append(extensions, extension) +} + +func getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := _getTypeDecoderFromExtension(ctx, typ) + if decoder != nil { + for _, extension := range extensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + decoder = ctx.decoderExtension.DecorateDecoder(typ, decoder) + for _, extension := range ctx.extraExtensions { + decoder = extension.DecorateDecoder(typ, decoder) + } + } + return decoder +} +func _getTypeDecoderFromExtension(ctx *ctx, typ reflect2.Type) ValDecoder { + for _, extension := range extensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } + decoder := ctx.decoderExtension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + for _, extension := range ctx.extraExtensions { + decoder := extension.CreateDecoder(typ) + if decoder != nil { + return decoder + } + } + typeName := typ.String() + decoder = typeDecoders[typeName] + if decoder != nil { + return decoder + } + if typ.Kind() == reflect.Ptr { + ptrType := typ.(*reflect2.UnsafePtrType) + decoder := typeDecoders[ptrType.Elem().String()] + if decoder != nil { + return &OptionalDecoder{ptrType.Elem(), decoder} + } + } + return nil +} + +func getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := _getTypeEncoderFromExtension(ctx, typ) + if encoder != nil { + for _, extension := range extensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + encoder = ctx.encoderExtension.DecorateEncoder(typ, encoder) + for _, extension := range ctx.extraExtensions { + encoder = extension.DecorateEncoder(typ, encoder) + } + } + return encoder +} + +func _getTypeEncoderFromExtension(ctx *ctx, typ reflect2.Type) ValEncoder { + for _, extension := range extensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } + encoder := ctx.encoderExtension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + for _, extension := range ctx.extraExtensions { + encoder := extension.CreateEncoder(typ) + if encoder != nil { + return encoder + } + } + typeName := typ.String() + encoder = typeEncoders[typeName] + if encoder != nil { + return encoder + } + if typ.Kind() == reflect.Ptr { + typePtr := typ.(*reflect2.UnsafePtrType) + encoder := typeEncoders[typePtr.Elem().String()] + if encoder != nil { + return &OptionalEncoder{encoder} + } + } + return nil +} + +func describeStruct(ctx *ctx, typ reflect2.Type) *StructDescriptor { + structType := typ.(*reflect2.UnsafeStructType) + embeddedBindings := []*Binding{} + bindings := []*Binding{} + for i := 0; i < structType.NumField(); i++ { + field := structType.Field(i) + tag, hastag := field.Tag().Lookup(ctx.getTagKey()) + if ctx.onlyTaggedField && !hastag && !field.Anonymous() { + continue + } + if tag == "-" || field.Name() == "_" { + continue + } + tagParts := strings.Split(tag, ",") + if field.Anonymous() && (tag == "" || tagParts[0] == "") { + if field.Type().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, field.Type()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue + } else if field.Type().Kind() == reflect.Ptr { + ptrType := field.Type().(*reflect2.UnsafePtrType) + if ptrType.Elem().Kind() == reflect.Struct { + structDescriptor := describeStruct(ctx, ptrType.Elem()) + for _, binding := range structDescriptor.Fields { + binding.levels = append([]int{i}, binding.levels...) + omitempty := binding.Encoder.(*structFieldEncoder).omitempty + binding.Encoder = &dereferenceEncoder{binding.Encoder} + binding.Encoder = &structFieldEncoder{field, binding.Encoder, omitempty} + binding.Decoder = &dereferenceDecoder{ptrType.Elem(), binding.Decoder} + binding.Decoder = &structFieldDecoder{field, binding.Decoder} + embeddedBindings = append(embeddedBindings, binding) + } + continue + } + } + } + fieldNames := calcFieldNames(field.Name(), tagParts[0], tag) + fieldCacheKey := fmt.Sprintf("%s/%s", typ.String(), field.Name()) + decoder := fieldDecoders[fieldCacheKey] + if decoder == nil { + decoder = decoderOfType(ctx.append(field.Name()), field.Type()) + } + encoder := fieldEncoders[fieldCacheKey] + if encoder == nil { + encoder = encoderOfType(ctx.append(field.Name()), field.Type()) + } + binding := &Binding{ + Field: field, + FromNames: fieldNames, + ToNames: fieldNames, + Decoder: decoder, + Encoder: encoder, + } + binding.levels = []int{i} + bindings = append(bindings, binding) + } + return createStructDescriptor(ctx, typ, bindings, embeddedBindings) +} +func createStructDescriptor(ctx *ctx, typ reflect2.Type, bindings []*Binding, embeddedBindings []*Binding) *StructDescriptor { + structDescriptor := &StructDescriptor{ + Type: typ, + Fields: bindings, + } + for _, extension := range extensions { + extension.UpdateStructDescriptor(structDescriptor) + } + ctx.encoderExtension.UpdateStructDescriptor(structDescriptor) + ctx.decoderExtension.UpdateStructDescriptor(structDescriptor) + for _, extension := range ctx.extraExtensions { + extension.UpdateStructDescriptor(structDescriptor) + } + processTags(structDescriptor, ctx.frozenConfig) + // merge normal & embedded bindings & sort with original order + allBindings := sortableBindings(append(embeddedBindings, structDescriptor.Fields...)) + sort.Sort(allBindings) + structDescriptor.Fields = allBindings + return structDescriptor +} + +type sortableBindings []*Binding + +func (bindings sortableBindings) Len() int { + return len(bindings) +} + +func (bindings sortableBindings) Less(i, j int) bool { + left := bindings[i].levels + right := bindings[j].levels + k := 0 + for { + if left[k] < right[k] { + return true + } else if left[k] > right[k] { + return false + } + k++ + } +} + +func (bindings sortableBindings) Swap(i, j int) { + bindings[i], bindings[j] = bindings[j], bindings[i] +} + +func processTags(structDescriptor *StructDescriptor, cfg *frozenConfig) { + for _, binding := range structDescriptor.Fields { + shouldOmitEmpty := false + tagParts := strings.Split(binding.Field.Tag().Get(cfg.getTagKey()), ",") + for _, tagPart := range tagParts[1:] { + if tagPart == "omitempty" { + shouldOmitEmpty = true + } else if tagPart == "string" { + if binding.Field.Type().Kind() == reflect.String { + binding.Decoder = &stringModeStringDecoder{binding.Decoder, cfg} + binding.Encoder = &stringModeStringEncoder{binding.Encoder, cfg} + } else { + binding.Decoder = &stringModeNumberDecoder{binding.Decoder} + binding.Encoder = &stringModeNumberEncoder{binding.Encoder} + } + } + } + binding.Decoder = &structFieldDecoder{binding.Field, binding.Decoder} + binding.Encoder = &structFieldEncoder{binding.Field, binding.Encoder, shouldOmitEmpty} + } +} + +func calcFieldNames(originalFieldName string, tagProvidedFieldName string, wholeTag string) []string { + // ignore? + if wholeTag == "-" { + return []string{} + } + // rename? + var fieldNames []string + if tagProvidedFieldName == "" { + fieldNames = []string{originalFieldName} + } else { + fieldNames = []string{tagProvidedFieldName} + } + // private? + isNotExported := unicode.IsLower(rune(originalFieldName[0])) || originalFieldName[0] == '_' + if isNotExported { + fieldNames = []string{} + } + return fieldNames +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go new file mode 100644 index 0000000..98d45c1 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -0,0 +1,112 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "strconv" + "unsafe" +) + +type Number string + +// String returns the literal text of the number. +func (n Number) String() string { return string(n) } + +// Float64 returns the number as a float64. +func (n Number) Float64() (float64, error) { + return strconv.ParseFloat(string(n), 64) +} + +// Int64 returns the number as an int64. +func (n Number) Int64() (int64, error) { + return strconv.ParseInt(string(n), 10, 64) +} + +func CastJsonNumber(val interface{}) (string, bool) { + switch typedVal := val.(type) { + case json.Number: + return string(typedVal), true + case Number: + return string(typedVal), true + } + return "", false +} + +var jsonNumberType = reflect2.TypeOfPtr((*json.Number)(nil)).Elem() +var jsoniterNumberType = reflect2.TypeOfPtr((*Number)(nil)).Elem() + +func createDecoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +func createEncoderOfJsonNumber(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.AssignableTo(jsonNumberType) { + return &jsonNumberCodec{} + } + if typ.AssignableTo(jsoniterNumberType) { + return &jsoniterNumberCodec{} + } + return nil +} + +type jsonNumberCodec struct { +} + +func (codec *jsonNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*json.Number)(ptr)) = json.Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*json.Number)(ptr)) = "" + default: + *((*json.Number)(ptr)) = json.Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsonNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*json.Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsonNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.Number)(ptr))) == 0 +} + +type jsoniterNumberCodec struct { +} + +func (codec *jsoniterNumberCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + switch iter.WhatIsNext() { + case StringValue: + *((*Number)(ptr)) = Number(iter.ReadString()) + case NilValue: + iter.skipFourBytes('n', 'u', 'l', 'l') + *((*Number)(ptr)) = "" + default: + *((*Number)(ptr)) = Number([]byte(iter.readNumberAsString())) + } +} + +func (codec *jsoniterNumberCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + number := *((*Number)(ptr)) + if len(number) == 0 { + stream.writeByte('0') + } else { + stream.WriteRaw(string(number)) + } +} + +func (codec *jsoniterNumberCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*Number)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go new file mode 100644 index 0000000..eba434f --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -0,0 +1,76 @@ +package jsoniter + +import ( + "encoding/json" + "github.com/modern-go/reflect2" + "unsafe" +) + +var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() +var jsoniterRawMessageType = reflect2.TypeOfPtr((*RawMessage)(nil)).Elem() + +func createEncoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +func createDecoderOfJsonRawMessage(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ == jsonRawMessageType { + return &jsonRawMessageCodec{} + } + if typ == jsoniterRawMessageType { + return &jsoniterRawMessageCodec{} + } + return nil +} + +type jsonRawMessageCodec struct { +} + +func (codec *jsonRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*json.RawMessage)(ptr)) = nil + } else { + *((*json.RawMessage)(ptr)) = iter.SkipAndReturnBytes() + } +} + +func (codec *jsonRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*json.RawMessage)(ptr)) == nil { + stream.WriteNil() + } else { + stream.WriteRaw(string(*((*json.RawMessage)(ptr)))) + } +} + +func (codec *jsonRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*json.RawMessage)(ptr))) == 0 +} + +type jsoniterRawMessageCodec struct { +} + +func (codec *jsoniterRawMessageCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*RawMessage)(ptr)) = nil + } else { + *((*RawMessage)(ptr)) = iter.SkipAndReturnBytes() + } +} + +func (codec *jsoniterRawMessageCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*RawMessage)(ptr)) == nil { + stream.WriteNil() + } else { + stream.WriteRaw(string(*((*RawMessage)(ptr)))) + } +} + +func (codec *jsoniterRawMessageCodec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*RawMessage)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go new file mode 100644 index 0000000..5829671 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -0,0 +1,346 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "sort" + "unsafe" +) + +func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { + mapType := typ.(*reflect2.UnsafeMapType) + keyDecoder := decoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()) + elemDecoder := decoderOfType(ctx.append("[mapElem]"), mapType.Elem()) + return &mapDecoder{ + mapType: mapType, + keyType: mapType.Key(), + elemType: mapType.Elem(), + keyDecoder: keyDecoder, + elemDecoder: elemDecoder, + } +} + +func encoderOfMap(ctx *ctx, typ reflect2.Type) ValEncoder { + mapType := typ.(*reflect2.UnsafeMapType) + if ctx.sortMapKeys { + return &sortKeysMapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } + } + return &mapEncoder{ + mapType: mapType, + keyEncoder: encoderOfMapKey(ctx.append("[mapKey]"), mapType.Key()), + elemEncoder: encoderOfType(ctx.append("[mapElem]"), mapType.Elem()), + } +} + +func decoderOfMapKey(ctx *ctx, typ reflect2.Type) ValDecoder { + decoder := ctx.decoderExtension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + for _, extension := range ctx.extraExtensions { + decoder := extension.CreateMapKeyDecoder(typ) + if decoder != nil { + return decoder + } + } + + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(unmarshalerType) { + return &referenceDecoder{ + &unmarshalerDecoder{ + valType: ptrType, + }, + } + } + if typ.Implements(unmarshalerType) { + return &unmarshalerDecoder{ + valType: typ, + } + } + if ptrType.Implements(textUnmarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ + valType: ptrType, + }, + } + } + if typ.Implements(textUnmarshalerType) { + return &textUnmarshalerDecoder{ + valType: typ, + } + } + + switch typ.Kind() { + case reflect.String: + return decoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyDecoder{decoderOfType(ctx, typ)} + default: + return &lazyErrorDecoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +func encoderOfMapKey(ctx *ctx, typ reflect2.Type) ValEncoder { + encoder := ctx.encoderExtension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + for _, extension := range ctx.extraExtensions { + encoder := extension.CreateMapKeyEncoder(typ) + if encoder != nil { + return encoder + } + } + + if typ == textMarshalerType { + return &directTextMarshalerEncoder{ + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + if typ.Implements(textMarshalerType) { + return &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + } + + switch typ.Kind() { + case reflect.String: + return encoderOfType(ctx, reflect2.DefaultTypeOfKind(reflect.String)) + case reflect.Bool, + reflect.Uint8, reflect.Int8, + reflect.Uint16, reflect.Int16, + reflect.Uint32, reflect.Int32, + reflect.Uint64, reflect.Int64, + reflect.Uint, reflect.Int, + reflect.Float32, reflect.Float64, + reflect.Uintptr: + typ = reflect2.DefaultTypeOfKind(typ.Kind()) + return &numericMapKeyEncoder{encoderOfType(ctx, typ)} + default: + if typ.Kind() == reflect.Interface { + return &dynamicMapKeyEncoder{ctx, typ} + } + return &lazyErrorEncoder{err: fmt.Errorf("unsupported map key type: %v", typ)} + } +} + +type mapDecoder struct { + mapType *reflect2.UnsafeMapType + keyType reflect2.Type + elemType reflect2.Type + keyDecoder ValDecoder + elemDecoder ValDecoder +} + +func (decoder *mapDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + mapType := decoder.mapType + c := iter.nextToken() + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + *(*unsafe.Pointer)(ptr) = nil + mapType.UnsafeSet(ptr, mapType.UnsafeNew()) + return + } + if mapType.UnsafeIsNil(ptr) { + mapType.UnsafeSet(ptr, mapType.UnsafeMakeMap(0)) + } + if c != '{' { + iter.ReportError("ReadMapCB", `expect { or n, but found `+string([]byte{c})) + return + } + c = iter.nextToken() + if c == '}' { + return + } + iter.unreadByte() + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + key := decoder.keyType.UnsafeNew() + decoder.keyDecoder.Decode(key, iter) + c = iter.nextToken() + if c != ':' { + iter.ReportError("ReadMapCB", "expect : after object field, but found "+string([]byte{c})) + return + } + elem := decoder.elemType.UnsafeNew() + decoder.elemDecoder.Decode(elem, iter) + decoder.mapType.UnsafeSetIndex(ptr, key, elem) + } + if c != '}' { + iter.ReportError("ReadMapCB", `expect }, but found `+string([]byte{c})) + } +} + +type numericMapKeyDecoder struct { + decoder ValDecoder +} + +func (decoder *numericMapKeyDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } + decoder.decoder.Decode(ptr, iter) + c = iter.nextToken() + if c != '"' { + iter.ReportError("ReadMapCB", `expect ", but found `+string([]byte{c})) + return + } +} + +type numericMapKeyEncoder struct { + encoder ValEncoder +} + +func (encoder *numericMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.encoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *numericMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type dynamicMapKeyEncoder struct { + ctx *ctx + valType reflect2.Type +} + +func (encoder *dynamicMapKeyEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).Encode(reflect2.PtrOf(obj), stream) +} + +func (encoder *dynamicMapKeyEncoder) IsEmpty(ptr unsafe.Pointer) bool { + obj := encoder.valType.UnsafeIndirect(ptr) + return encoderOfMapKey(encoder.ctx, reflect2.TypeOf(obj)).IsEmpty(reflect2.PtrOf(obj)) +} + +type mapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *mapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } + stream.WriteObjectStart() + iter := encoder.mapType.UnsafeIterate(ptr) + for i := 0; iter.HasNext(); i++ { + if i != 0 { + stream.WriteMore() + } + key, elem := iter.UnsafeNext() + encoder.keyEncoder.Encode(key, stream) + if stream.indention > 0 { + stream.writeTwoBytes(byte(':'), byte(' ')) + } else { + stream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, stream) + } + stream.WriteObjectEnd() +} + +func (encoder *mapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type sortKeysMapEncoder struct { + mapType *reflect2.UnsafeMapType + keyEncoder ValEncoder + elemEncoder ValEncoder +} + +func (encoder *sortKeysMapEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *(*unsafe.Pointer)(ptr) == nil { + stream.WriteNil() + return + } + stream.WriteObjectStart() + mapIter := encoder.mapType.UnsafeIterate(ptr) + subStream := stream.cfg.BorrowStream(nil) + subStream.Attachment = stream.Attachment + subIter := stream.cfg.BorrowIterator(nil) + keyValues := encodedKeyValues{} + for mapIter.HasNext() { + key, elem := mapIter.UnsafeNext() + subStreamIndex := subStream.Buffered() + encoder.keyEncoder.Encode(key, subStream) + if subStream.Error != nil && subStream.Error != io.EOF && stream.Error == nil { + stream.Error = subStream.Error + } + encodedKey := subStream.Buffer()[subStreamIndex:] + subIter.ResetBytes(encodedKey) + decodedKey := subIter.ReadString() + if stream.indention > 0 { + subStream.writeTwoBytes(byte(':'), byte(' ')) + } else { + subStream.writeByte(':') + } + encoder.elemEncoder.Encode(elem, subStream) + keyValues = append(keyValues, encodedKV{ + key: decodedKey, + keyValue: subStream.Buffer()[subStreamIndex:], + }) + } + sort.Sort(keyValues) + for i, keyValue := range keyValues { + if i != 0 { + stream.WriteMore() + } + stream.Write(keyValue.keyValue) + } + if subStream.Error != nil && stream.Error == nil { + stream.Error = subStream.Error + } + stream.WriteObjectEnd() + stream.cfg.ReturnStream(subStream) + stream.cfg.ReturnIterator(subIter) +} + +func (encoder *sortKeysMapEncoder) IsEmpty(ptr unsafe.Pointer) bool { + iter := encoder.mapType.UnsafeIterate(ptr) + return !iter.HasNext() +} + +type encodedKeyValues []encodedKV + +type encodedKV struct { + key string + keyValue []byte +} + +func (sv encodedKeyValues) Len() int { return len(sv) } +func (sv encodedKeyValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } +func (sv encodedKeyValues) Less(i, j int) bool { return sv[i].key < sv[j].key } diff --git a/vendor/github.com/json-iterator/go/reflect_marshaler.go b/vendor/github.com/json-iterator/go/reflect_marshaler.go new file mode 100644 index 0000000..3e21f37 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_marshaler.go @@ -0,0 +1,225 @@ +package jsoniter + +import ( + "encoding" + "encoding/json" + "unsafe" + + "github.com/modern-go/reflect2" +) + +var marshalerType = reflect2.TypeOfPtr((*json.Marshaler)(nil)).Elem() +var unmarshalerType = reflect2.TypeOfPtr((*json.Unmarshaler)(nil)).Elem() +var textMarshalerType = reflect2.TypeOfPtr((*encoding.TextMarshaler)(nil)).Elem() +var textUnmarshalerType = reflect2.TypeOfPtr((*encoding.TextUnmarshaler)(nil)).Elem() + +func createDecoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := reflect2.PtrTo(typ) + if ptrType.Implements(unmarshalerType) { + return &referenceDecoder{ + &unmarshalerDecoder{ptrType}, + } + } + if ptrType.Implements(textUnmarshalerType) { + return &referenceDecoder{ + &textUnmarshalerDecoder{ptrType}, + } + } + return nil +} + +func createEncoderOfMarshaler(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ == marshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + } + return encoder + } + if typ.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &marshalerEncoder{ + valType: typ, + checkIsEmpty: checkIsEmpty, + } + return encoder + } + ptrType := reflect2.PtrTo(typ) + if ctx.prefix != "" && ptrType.Implements(marshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &marshalerEncoder{ + valType: ptrType, + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + if typ == textMarshalerType { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &directTextMarshalerEncoder{ + checkIsEmpty: checkIsEmpty, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + } + return encoder + } + if typ.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, typ) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: typ, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return encoder + } + // if prefix is empty, the type is the root type + if ctx.prefix != "" && ptrType.Implements(textMarshalerType) { + checkIsEmpty := createCheckIsEmpty(ctx, ptrType) + var encoder ValEncoder = &textMarshalerEncoder{ + valType: ptrType, + stringEncoder: ctx.EncoderOf(reflect2.TypeOf("")), + checkIsEmpty: checkIsEmpty, + } + return &referenceEncoder{encoder} + } + return nil +} + +type marshalerEncoder struct { + checkIsEmpty checkIsEmpty + valType reflect2.Type +} + +func (encoder *marshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := obj.(json.Marshaler) + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + // html escape was already done by jsoniter + // but the extra '\n' should be trimed + l := len(bytes) + if l > 0 && bytes[l-1] == '\n' { + bytes = bytes[:l-1] + } + stream.Write(bytes) + } +} + +func (encoder *marshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directMarshalerEncoder struct { + checkIsEmpty checkIsEmpty +} + +func (encoder *directMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*json.Marshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalJSON() + if err != nil { + stream.Error = err + } else { + stream.Write(bytes) + } +} + +func (encoder *directMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type textMarshalerEncoder struct { + valType reflect2.Type + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *textMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + obj := encoder.valType.UnsafeIndirect(ptr) + if encoder.valType.IsNullable() && reflect2.IsNil(obj) { + stream.WriteNil() + return + } + marshaler := (obj).(encoding.TextMarshaler) + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *textMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type directTextMarshalerEncoder struct { + stringEncoder ValEncoder + checkIsEmpty checkIsEmpty +} + +func (encoder *directTextMarshalerEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + marshaler := *(*encoding.TextMarshaler)(ptr) + if marshaler == nil { + stream.WriteNil() + return + } + bytes, err := marshaler.MarshalText() + if err != nil { + stream.Error = err + } else { + str := string(bytes) + encoder.stringEncoder.Encode(unsafe.Pointer(&str), stream) + } +} + +func (encoder *directTextMarshalerEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.checkIsEmpty.IsEmpty(ptr) +} + +type unmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *unmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + unmarshaler := obj.(json.Unmarshaler) + iter.nextToken() + iter.unreadByte() // skip spaces + bytes := iter.SkipAndReturnBytes() + err := unmarshaler.UnmarshalJSON(bytes) + if err != nil { + iter.ReportError("unmarshalerDecoder", err.Error()) + } +} + +type textUnmarshalerDecoder struct { + valType reflect2.Type +} + +func (decoder *textUnmarshalerDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valType := decoder.valType + obj := valType.UnsafeIndirect(ptr) + if reflect2.IsNil(obj) { + ptrType := valType.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elem := elemType.UnsafeNew() + ptrType.UnsafeSet(ptr, unsafe.Pointer(&elem)) + obj = valType.UnsafeIndirect(ptr) + } + unmarshaler := (obj).(encoding.TextUnmarshaler) + str := iter.ReadString() + err := unmarshaler.UnmarshalText([]byte(str)) + if err != nil { + iter.ReportError("textUnmarshalerDecoder", err.Error()) + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_native.go b/vendor/github.com/json-iterator/go/reflect_native.go new file mode 100644 index 0000000..f88722d --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_native.go @@ -0,0 +1,453 @@ +package jsoniter + +import ( + "encoding/base64" + "reflect" + "strconv" + "unsafe" + + "github.com/modern-go/reflect2" +) + +const ptrSize = 32 << uintptr(^uintptr(0)>>63) + +func createEncoderOfNative(ctx *ctx, typ reflect2.Type) ValEncoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + kind := typ.Kind() + switch kind { + case reflect.String: + if typeName != "string" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return encoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +func createDecoderOfNative(ctx *ctx, typ reflect2.Type) ValDecoder { + if typ.Kind() == reflect.Slice && typ.(reflect2.SliceType).Elem().Kind() == reflect.Uint8 { + sliceDecoder := decoderOfSlice(ctx, typ) + return &base64Codec{sliceDecoder: sliceDecoder} + } + typeName := typ.String() + switch typ.Kind() { + case reflect.String: + if typeName != "string" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*string)(nil)).Elem()) + } + return &stringCodec{} + case reflect.Int: + if typeName != "int" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &int32Codec{} + } + return &int64Codec{} + case reflect.Int8: + if typeName != "int8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int8)(nil)).Elem()) + } + return &int8Codec{} + case reflect.Int16: + if typeName != "int16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int16)(nil)).Elem()) + } + return &int16Codec{} + case reflect.Int32: + if typeName != "int32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int32)(nil)).Elem()) + } + return &int32Codec{} + case reflect.Int64: + if typeName != "int64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*int64)(nil)).Elem()) + } + return &int64Codec{} + case reflect.Uint: + if typeName != "uint" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint)(nil)).Elem()) + } + if strconv.IntSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint8: + if typeName != "uint8" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint8)(nil)).Elem()) + } + return &uint8Codec{} + case reflect.Uint16: + if typeName != "uint16" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint16)(nil)).Elem()) + } + return &uint16Codec{} + case reflect.Uint32: + if typeName != "uint32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint32)(nil)).Elem()) + } + return &uint32Codec{} + case reflect.Uintptr: + if typeName != "uintptr" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uintptr)(nil)).Elem()) + } + if ptrSize == 32 { + return &uint32Codec{} + } + return &uint64Codec{} + case reflect.Uint64: + if typeName != "uint64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*uint64)(nil)).Elem()) + } + return &uint64Codec{} + case reflect.Float32: + if typeName != "float32" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float32)(nil)).Elem()) + } + return &float32Codec{} + case reflect.Float64: + if typeName != "float64" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*float64)(nil)).Elem()) + } + return &float64Codec{} + case reflect.Bool: + if typeName != "bool" { + return decoderOfType(ctx, reflect2.TypeOfPtr((*bool)(nil)).Elem()) + } + return &boolCodec{} + } + return nil +} + +type stringCodec struct { +} + +func (codec *stringCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + *((*string)(ptr)) = iter.ReadString() +} + +func (codec *stringCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + str := *((*string)(ptr)) + stream.WriteString(str) +} + +func (codec *stringCodec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*string)(ptr)) == "" +} + +type int8Codec struct { +} + +func (codec *int8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int8)(ptr)) = iter.ReadInt8() + } +} + +func (codec *int8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt8(*((*int8)(ptr))) +} + +func (codec *int8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int8)(ptr)) == 0 +} + +type int16Codec struct { +} + +func (codec *int16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int16)(ptr)) = iter.ReadInt16() + } +} + +func (codec *int16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt16(*((*int16)(ptr))) +} + +func (codec *int16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int16)(ptr)) == 0 +} + +type int32Codec struct { +} + +func (codec *int32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int32)(ptr)) = iter.ReadInt32() + } +} + +func (codec *int32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt32(*((*int32)(ptr))) +} + +func (codec *int32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int32)(ptr)) == 0 +} + +type int64Codec struct { +} + +func (codec *int64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*int64)(ptr)) = iter.ReadInt64() + } +} + +func (codec *int64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteInt64(*((*int64)(ptr))) +} + +func (codec *int64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*int64)(ptr)) == 0 +} + +type uint8Codec struct { +} + +func (codec *uint8Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint8)(ptr)) = iter.ReadUint8() + } +} + +func (codec *uint8Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint8(*((*uint8)(ptr))) +} + +func (codec *uint8Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint8)(ptr)) == 0 +} + +type uint16Codec struct { +} + +func (codec *uint16Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint16)(ptr)) = iter.ReadUint16() + } +} + +func (codec *uint16Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint16(*((*uint16)(ptr))) +} + +func (codec *uint16Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint16)(ptr)) == 0 +} + +type uint32Codec struct { +} + +func (codec *uint32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint32)(ptr)) = iter.ReadUint32() + } +} + +func (codec *uint32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint32(*((*uint32)(ptr))) +} + +func (codec *uint32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint32)(ptr)) == 0 +} + +type uint64Codec struct { +} + +func (codec *uint64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*uint64)(ptr)) = iter.ReadUint64() + } +} + +func (codec *uint64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteUint64(*((*uint64)(ptr))) +} + +func (codec *uint64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*uint64)(ptr)) == 0 +} + +type float32Codec struct { +} + +func (codec *float32Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float32)(ptr)) = iter.ReadFloat32() + } +} + +func (codec *float32Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat32(*((*float32)(ptr))) +} + +func (codec *float32Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float32)(ptr)) == 0 +} + +type float64Codec struct { +} + +func (codec *float64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*float64)(ptr)) = iter.ReadFloat64() + } +} + +func (codec *float64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteFloat64(*((*float64)(ptr))) +} + +func (codec *float64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return *((*float64)(ptr)) == 0 +} + +type boolCodec struct { +} + +func (codec *boolCodec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.ReadNil() { + *((*bool)(ptr)) = iter.ReadBool() + } +} + +func (codec *boolCodec) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteBool(*((*bool)(ptr))) +} + +func (codec *boolCodec) IsEmpty(ptr unsafe.Pointer) bool { + return !(*((*bool)(ptr))) +} + +type base64Codec struct { + sliceType *reflect2.UnsafeSliceType + sliceDecoder ValDecoder +} + +func (codec *base64Codec) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + codec.sliceType.UnsafeSetNil(ptr) + return + } + switch iter.WhatIsNext() { + case StringValue: + src := iter.ReadString() + dst, err := base64.StdEncoding.DecodeString(src) + if err != nil { + iter.ReportError("decode base64", err.Error()) + } else { + codec.sliceType.UnsafeSet(ptr, unsafe.Pointer(&dst)) + } + case ArrayValue: + codec.sliceDecoder.Decode(ptr, iter) + default: + iter.ReportError("base64Codec", "invalid input") + } +} + +func (codec *base64Codec) Encode(ptr unsafe.Pointer, stream *Stream) { + if codec.sliceType.UnsafeIsNil(ptr) { + stream.WriteNil() + return + } + src := *((*[]byte)(ptr)) + encoding := base64.StdEncoding + stream.writeByte('"') + if len(src) != 0 { + size := encoding.EncodedLen(len(src)) + buf := make([]byte, size) + encoding.Encode(buf, src) + stream.buf = append(stream.buf, buf...) + } + stream.writeByte('"') +} + +func (codec *base64Codec) IsEmpty(ptr unsafe.Pointer) bool { + return len(*((*[]byte)(ptr))) == 0 +} diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go new file mode 100644 index 0000000..fa71f47 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -0,0 +1,129 @@ +package jsoniter + +import ( + "github.com/modern-go/reflect2" + "unsafe" +) + +func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + decoder := decoderOfType(ctx, elemType) + return &OptionalDecoder{elemType, decoder} +} + +func encoderOfOptional(ctx *ctx, typ reflect2.Type) ValEncoder { + ptrType := typ.(*reflect2.UnsafePtrType) + elemType := ptrType.Elem() + elemEncoder := encoderOfType(ctx, elemType) + encoder := &OptionalEncoder{elemEncoder} + return encoder +} + +type OptionalDecoder struct { + ValueType reflect2.Type + ValueDecoder ValDecoder +} + +func (decoder *OptionalDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.ReadNil() { + *((*unsafe.Pointer)(ptr)) = nil + } else { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.ValueType.UnsafeNew() + decoder.ValueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.ValueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } + } +} + +type dereferenceDecoder struct { + // only to deference a pointer + valueType reflect2.Type + valueDecoder ValDecoder +} + +func (decoder *dereferenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if *((*unsafe.Pointer)(ptr)) == nil { + //pointer to null, we have to allocate memory to hold the value + newPtr := decoder.valueType.UnsafeNew() + decoder.valueDecoder.Decode(newPtr, iter) + *((*unsafe.Pointer)(ptr)) = newPtr + } else { + //reuse existing instance + decoder.valueDecoder.Decode(*((*unsafe.Pointer)(ptr)), iter) + } +} + +type OptionalEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *OptionalEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *OptionalEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return *((*unsafe.Pointer)(ptr)) == nil +} + +type dereferenceEncoder struct { + ValueEncoder ValEncoder +} + +func (encoder *dereferenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if *((*unsafe.Pointer)(ptr)) == nil { + stream.WriteNil() + } else { + encoder.ValueEncoder.Encode(*((*unsafe.Pointer)(ptr)), stream) + } +} + +func (encoder *dereferenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + dePtr := *((*unsafe.Pointer)(ptr)) + if dePtr == nil { + return true + } + return encoder.ValueEncoder.IsEmpty(dePtr) +} + +func (encoder *dereferenceEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + deReferenced := *((*unsafe.Pointer)(ptr)) + if deReferenced == nil { + return true + } + isEmbeddedPtrNil, converted := encoder.ValueEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := unsafe.Pointer(deReferenced) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type referenceEncoder struct { + encoder ValEncoder +} + +func (encoder *referenceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + encoder.encoder.Encode(unsafe.Pointer(&ptr), stream) +} + +func (encoder *referenceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.encoder.IsEmpty(unsafe.Pointer(&ptr)) +} + +type referenceDecoder struct { + decoder ValDecoder +} + +func (decoder *referenceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.decoder.Decode(unsafe.Pointer(&ptr), iter) +} diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go new file mode 100644 index 0000000..9441d79 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -0,0 +1,99 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "unsafe" +) + +func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + decoder := decoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceDecoder{sliceType, decoder} +} + +func encoderOfSlice(ctx *ctx, typ reflect2.Type) ValEncoder { + sliceType := typ.(*reflect2.UnsafeSliceType) + encoder := encoderOfType(ctx.append("[sliceElem]"), sliceType.Elem()) + return &sliceEncoder{sliceType, encoder} +} + +type sliceEncoder struct { + sliceType *reflect2.UnsafeSliceType + elemEncoder ValEncoder +} + +func (encoder *sliceEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + if encoder.sliceType.UnsafeIsNil(ptr) { + stream.WriteNil() + return + } + length := encoder.sliceType.UnsafeLengthOf(ptr) + if length == 0 { + stream.WriteEmptyArray() + return + } + stream.WriteArrayStart() + encoder.elemEncoder.Encode(encoder.sliceType.UnsafeGetIndex(ptr, 0), stream) + for i := 1; i < length; i++ { + stream.WriteMore() + elemPtr := encoder.sliceType.UnsafeGetIndex(ptr, i) + encoder.elemEncoder.Encode(elemPtr, stream) + } + stream.WriteArrayEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v: %s", encoder.sliceType, stream.Error.Error()) + } +} + +func (encoder *sliceEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.sliceType.UnsafeLengthOf(ptr) == 0 +} + +type sliceDecoder struct { + sliceType *reflect2.UnsafeSliceType + elemDecoder ValDecoder +} + +func (decoder *sliceDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.doDecode(ptr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%v: %s", decoder.sliceType, iter.Error.Error()) + } +} + +func (decoder *sliceDecoder) doDecode(ptr unsafe.Pointer, iter *Iterator) { + c := iter.nextToken() + sliceType := decoder.sliceType + if c == 'n' { + iter.skipThreeBytes('u', 'l', 'l') + sliceType.UnsafeSetNil(ptr) + return + } + if c != '[' { + iter.ReportError("decode slice", "expect [ or n, but found "+string([]byte{c})) + return + } + c = iter.nextToken() + if c == ']' { + sliceType.UnsafeSet(ptr, sliceType.UnsafeMakeSlice(0, 0)) + return + } + iter.unreadByte() + sliceType.UnsafeGrow(ptr, 1) + elemPtr := sliceType.UnsafeGetIndex(ptr, 0) + decoder.elemDecoder.Decode(elemPtr, iter) + length := 1 + for c = iter.nextToken(); c == ','; c = iter.nextToken() { + idx := length + length += 1 + sliceType.UnsafeGrow(ptr, length) + elemPtr = sliceType.UnsafeGetIndex(ptr, idx) + decoder.elemDecoder.Decode(elemPtr, iter) + } + if c != ']' { + iter.ReportError("decode slice", "expect ], but found "+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_decoder.go b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go new file mode 100644 index 0000000..92ae912 --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_struct_decoder.go @@ -0,0 +1,1097 @@ +package jsoniter + +import ( + "fmt" + "io" + "strings" + "unsafe" + + "github.com/modern-go/reflect2" +) + +func decoderOfStruct(ctx *ctx, typ reflect2.Type) ValDecoder { + bindings := map[string]*Binding{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, fromName := range binding.FromNames { + old := bindings[fromName] + if old == nil { + bindings[fromName] = binding + continue + } + ignoreOld, ignoreNew := resolveConflictBinding(ctx.frozenConfig, old, binding) + if ignoreOld { + delete(bindings, fromName) + } + if !ignoreNew { + bindings[fromName] = binding + } + } + } + fields := map[string]*structFieldDecoder{} + for k, binding := range bindings { + fields[k] = binding.Decoder.(*structFieldDecoder) + } + + if !ctx.caseSensitive() { + for k, binding := range bindings { + if _, found := fields[strings.ToLower(k)]; !found { + fields[strings.ToLower(k)] = binding.Decoder.(*structFieldDecoder) + } + } + } + + return createStructDecoder(ctx, typ, fields) +} + +func createStructDecoder(ctx *ctx, typ reflect2.Type, fields map[string]*structFieldDecoder) ValDecoder { + if ctx.disallowUnknownFields { + return &generalStructDecoder{typ: typ, fields: fields, disallowUnknownFields: true} + } + knownHash := map[int64]struct{}{ + 0: {}, + } + + switch len(fields) { + case 0: + return &skipObjectDecoder{typ} + case 1: + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + return &oneFieldStructDecoder{typ, fieldHash, fieldDecoder} + } + case 2: + var fieldHash1 int64 + var fieldHash2 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldHash1 == 0 { + fieldHash1 = fieldHash + fieldDecoder1 = fieldDecoder + } else { + fieldHash2 = fieldHash + fieldDecoder2 = fieldDecoder + } + } + return &twoFieldsStructDecoder{typ, fieldHash1, fieldDecoder1, fieldHash2, fieldDecoder2} + case 3: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } + } + return &threeFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3} + case 4: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } + } + return &fourFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4} + case 5: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } + } + return &fiveFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5} + case 6: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } + } + return &sixFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6} + case 7: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } + } + return &sevenFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7} + case 8: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } + } + return &eightFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8} + case 9: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + var fieldDecoder9 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else if fieldName8 == 0 { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } else { + fieldName9 = fieldHash + fieldDecoder9 = fieldDecoder + } + } + return &nineFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9} + case 10: + var fieldName1 int64 + var fieldName2 int64 + var fieldName3 int64 + var fieldName4 int64 + var fieldName5 int64 + var fieldName6 int64 + var fieldName7 int64 + var fieldName8 int64 + var fieldName9 int64 + var fieldName10 int64 + var fieldDecoder1 *structFieldDecoder + var fieldDecoder2 *structFieldDecoder + var fieldDecoder3 *structFieldDecoder + var fieldDecoder4 *structFieldDecoder + var fieldDecoder5 *structFieldDecoder + var fieldDecoder6 *structFieldDecoder + var fieldDecoder7 *structFieldDecoder + var fieldDecoder8 *structFieldDecoder + var fieldDecoder9 *structFieldDecoder + var fieldDecoder10 *structFieldDecoder + for fieldName, fieldDecoder := range fields { + fieldHash := calcHash(fieldName, ctx.caseSensitive()) + _, known := knownHash[fieldHash] + if known { + return &generalStructDecoder{typ, fields, false} + } + knownHash[fieldHash] = struct{}{} + if fieldName1 == 0 { + fieldName1 = fieldHash + fieldDecoder1 = fieldDecoder + } else if fieldName2 == 0 { + fieldName2 = fieldHash + fieldDecoder2 = fieldDecoder + } else if fieldName3 == 0 { + fieldName3 = fieldHash + fieldDecoder3 = fieldDecoder + } else if fieldName4 == 0 { + fieldName4 = fieldHash + fieldDecoder4 = fieldDecoder + } else if fieldName5 == 0 { + fieldName5 = fieldHash + fieldDecoder5 = fieldDecoder + } else if fieldName6 == 0 { + fieldName6 = fieldHash + fieldDecoder6 = fieldDecoder + } else if fieldName7 == 0 { + fieldName7 = fieldHash + fieldDecoder7 = fieldDecoder + } else if fieldName8 == 0 { + fieldName8 = fieldHash + fieldDecoder8 = fieldDecoder + } else if fieldName9 == 0 { + fieldName9 = fieldHash + fieldDecoder9 = fieldDecoder + } else { + fieldName10 = fieldHash + fieldDecoder10 = fieldDecoder + } + } + return &tenFieldsStructDecoder{typ, + fieldName1, fieldDecoder1, + fieldName2, fieldDecoder2, + fieldName3, fieldDecoder3, + fieldName4, fieldDecoder4, + fieldName5, fieldDecoder5, + fieldName6, fieldDecoder6, + fieldName7, fieldDecoder7, + fieldName8, fieldDecoder8, + fieldName9, fieldDecoder9, + fieldName10, fieldDecoder10} + } + return &generalStructDecoder{typ, fields, false} +} + +type generalStructDecoder struct { + typ reflect2.Type + fields map[string]*structFieldDecoder + disallowUnknownFields bool +} + +func (decoder *generalStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + var c byte + for c = ','; c == ','; c = iter.nextToken() { + decoder.decodeOneField(ptr, iter) + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + if c != '}' { + iter.ReportError("struct Decode", `expect }, but found `+string([]byte{c})) + } + iter.decrementDepth() +} + +func (decoder *generalStructDecoder) decodeOneField(ptr unsafe.Pointer, iter *Iterator) { + var field string + var fieldDecoder *structFieldDecoder + if iter.cfg.objectFieldMustBeSimpleString { + fieldBytes := iter.ReadStringAsSlice() + field = *(*string)(unsafe.Pointer(&fieldBytes)) + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil && !iter.cfg.caseSensitive { + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } else { + field = iter.ReadString() + fieldDecoder = decoder.fields[field] + if fieldDecoder == nil && !iter.cfg.caseSensitive { + fieldDecoder = decoder.fields[strings.ToLower(field)] + } + } + if fieldDecoder == nil { + if decoder.disallowUnknownFields { + msg := "found unknown field: " + field + iter.ReportError("ReadObject", msg) + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + iter.Skip() + return + } + c := iter.nextToken() + if c != ':' { + iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) + } + fieldDecoder.Decode(ptr, iter) +} + +type skipObjectDecoder struct { + typ reflect2.Type +} + +func (decoder *skipObjectDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + valueType := iter.WhatIsNext() + if valueType != ObjectValue && valueType != NilValue { + iter.ReportError("skipObjectDecoder", "expect object or null") + return + } + iter.Skip() +} + +type oneFieldStructDecoder struct { + typ reflect2.Type + fieldHash int64 + fieldDecoder *structFieldDecoder +} + +func (decoder *oneFieldStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + if iter.readFieldHash() == decoder.fieldHash { + decoder.fieldDecoder.Decode(ptr, iter) + } else { + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type twoFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder +} + +func (decoder *twoFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type threeFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder +} + +func (decoder *threeFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type fourFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder +} + +func (decoder *fourFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type fiveFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder +} + +func (decoder *fiveFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type sixFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder +} + +func (decoder *sixFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type sevenFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder +} + +func (decoder *sevenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type eightFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder +} + +func (decoder *eightFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type nineFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder + fieldHash9 int64 + fieldDecoder9 *structFieldDecoder +} + +func (decoder *nineFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + case decoder.fieldHash9: + decoder.fieldDecoder9.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type tenFieldsStructDecoder struct { + typ reflect2.Type + fieldHash1 int64 + fieldDecoder1 *structFieldDecoder + fieldHash2 int64 + fieldDecoder2 *structFieldDecoder + fieldHash3 int64 + fieldDecoder3 *structFieldDecoder + fieldHash4 int64 + fieldDecoder4 *structFieldDecoder + fieldHash5 int64 + fieldDecoder5 *structFieldDecoder + fieldHash6 int64 + fieldDecoder6 *structFieldDecoder + fieldHash7 int64 + fieldDecoder7 *structFieldDecoder + fieldHash8 int64 + fieldDecoder8 *structFieldDecoder + fieldHash9 int64 + fieldDecoder9 *structFieldDecoder + fieldHash10 int64 + fieldDecoder10 *structFieldDecoder +} + +func (decoder *tenFieldsStructDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if !iter.readObjectStart() { + return + } + if !iter.incrementDepth() { + return + } + for { + switch iter.readFieldHash() { + case decoder.fieldHash1: + decoder.fieldDecoder1.Decode(ptr, iter) + case decoder.fieldHash2: + decoder.fieldDecoder2.Decode(ptr, iter) + case decoder.fieldHash3: + decoder.fieldDecoder3.Decode(ptr, iter) + case decoder.fieldHash4: + decoder.fieldDecoder4.Decode(ptr, iter) + case decoder.fieldHash5: + decoder.fieldDecoder5.Decode(ptr, iter) + case decoder.fieldHash6: + decoder.fieldDecoder6.Decode(ptr, iter) + case decoder.fieldHash7: + decoder.fieldDecoder7.Decode(ptr, iter) + case decoder.fieldHash8: + decoder.fieldDecoder8.Decode(ptr, iter) + case decoder.fieldHash9: + decoder.fieldDecoder9.Decode(ptr, iter) + case decoder.fieldHash10: + decoder.fieldDecoder10.Decode(ptr, iter) + default: + iter.Skip() + } + if iter.isObjectEnd() { + break + } + } + if iter.Error != nil && iter.Error != io.EOF && len(decoder.typ.Type1().Name()) != 0 { + iter.Error = fmt.Errorf("%v.%s", decoder.typ, iter.Error.Error()) + } + iter.decrementDepth() +} + +type structFieldDecoder struct { + field reflect2.StructField + fieldDecoder ValDecoder +} + +func (decoder *structFieldDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + fieldPtr := decoder.field.UnsafeGet(ptr) + decoder.fieldDecoder.Decode(fieldPtr, iter) + if iter.Error != nil && iter.Error != io.EOF { + iter.Error = fmt.Errorf("%s: %s", decoder.field.Name(), iter.Error.Error()) + } +} + +type stringModeStringDecoder struct { + elemDecoder ValDecoder + cfg *frozenConfig +} + +func (decoder *stringModeStringDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + decoder.elemDecoder.Decode(ptr, iter) + str := *((*string)(ptr)) + tempIter := decoder.cfg.BorrowIterator([]byte(str)) + defer decoder.cfg.ReturnIterator(tempIter) + *((*string)(ptr)) = tempIter.ReadString() +} + +type stringModeNumberDecoder struct { + elemDecoder ValDecoder +} + +func (decoder *stringModeNumberDecoder) Decode(ptr unsafe.Pointer, iter *Iterator) { + if iter.WhatIsNext() == NilValue { + decoder.elemDecoder.Decode(ptr, iter) + return + } + + c := iter.nextToken() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } + decoder.elemDecoder.Decode(ptr, iter) + if iter.Error != nil { + return + } + c = iter.readByte() + if c != '"' { + iter.ReportError("stringModeNumberDecoder", `expect ", but found `+string([]byte{c})) + return + } +} diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go new file mode 100644 index 0000000..152e3ef --- /dev/null +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -0,0 +1,211 @@ +package jsoniter + +import ( + "fmt" + "github.com/modern-go/reflect2" + "io" + "reflect" + "unsafe" +) + +func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { + type bindingTo struct { + binding *Binding + toName string + ignored bool + } + orderedBindings := []*bindingTo{} + structDescriptor := describeStruct(ctx, typ) + for _, binding := range structDescriptor.Fields { + for _, toName := range binding.ToNames { + new := &bindingTo{ + binding: binding, + toName: toName, + } + for _, old := range orderedBindings { + if old.toName != toName { + continue + } + old.ignored, new.ignored = resolveConflictBinding(ctx.frozenConfig, old.binding, new.binding) + } + orderedBindings = append(orderedBindings, new) + } + } + if len(orderedBindings) == 0 { + return &emptyStructEncoder{} + } + finalOrderedFields := []structFieldTo{} + for _, bindingTo := range orderedBindings { + if !bindingTo.ignored { + finalOrderedFields = append(finalOrderedFields, structFieldTo{ + encoder: bindingTo.binding.Encoder.(*structFieldEncoder), + toName: bindingTo.toName, + }) + } + } + return &structEncoder{typ, finalOrderedFields} +} + +func createCheckIsEmpty(ctx *ctx, typ reflect2.Type) checkIsEmpty { + encoder := createEncoderOfNative(ctx, typ) + if encoder != nil { + return encoder + } + kind := typ.Kind() + switch kind { + case reflect.Interface: + return &dynamicEncoder{typ} + case reflect.Struct: + return &structEncoder{typ: typ} + case reflect.Array: + return &arrayEncoder{} + case reflect.Slice: + return &sliceEncoder{} + case reflect.Map: + return encoderOfMap(ctx, typ) + case reflect.Ptr: + return &OptionalEncoder{} + default: + return &lazyErrorEncoder{err: fmt.Errorf("unsupported type: %v", typ)} + } +} + +func resolveConflictBinding(cfg *frozenConfig, old, new *Binding) (ignoreOld, ignoreNew bool) { + newTagged := new.Field.Tag().Get(cfg.getTagKey()) != "" + oldTagged := old.Field.Tag().Get(cfg.getTagKey()) != "" + if newTagged { + if oldTagged { + if len(old.levels) > len(new.levels) { + return true, false + } else if len(new.levels) > len(old.levels) { + return false, true + } else { + return true, true + } + } else { + return true, false + } + } else { + if oldTagged { + return true, false + } + if len(old.levels) > len(new.levels) { + return true, false + } else if len(new.levels) > len(old.levels) { + return false, true + } else { + return true, true + } + } +} + +type structFieldEncoder struct { + field reflect2.StructField + fieldEncoder ValEncoder + omitempty bool +} + +func (encoder *structFieldEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + fieldPtr := encoder.field.UnsafeGet(ptr) + encoder.fieldEncoder.Encode(fieldPtr, stream) + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%s: %s", encoder.field.Name(), stream.Error.Error()) + } +} + +func (encoder *structFieldEncoder) IsEmpty(ptr unsafe.Pointer) bool { + fieldPtr := encoder.field.UnsafeGet(ptr) + return encoder.fieldEncoder.IsEmpty(fieldPtr) +} + +func (encoder *structFieldEncoder) IsEmbeddedPtrNil(ptr unsafe.Pointer) bool { + isEmbeddedPtrNil, converted := encoder.fieldEncoder.(IsEmbeddedPtrNil) + if !converted { + return false + } + fieldPtr := encoder.field.UnsafeGet(ptr) + return isEmbeddedPtrNil.IsEmbeddedPtrNil(fieldPtr) +} + +type IsEmbeddedPtrNil interface { + IsEmbeddedPtrNil(ptr unsafe.Pointer) bool +} + +type structEncoder struct { + typ reflect2.Type + fields []structFieldTo +} + +type structFieldTo struct { + encoder *structFieldEncoder + toName string +} + +func (encoder *structEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteObjectStart() + isNotFirst := false + for _, field := range encoder.fields { + if field.encoder.omitempty && field.encoder.IsEmpty(ptr) { + continue + } + if field.encoder.IsEmbeddedPtrNil(ptr) { + continue + } + if isNotFirst { + stream.WriteMore() + } + stream.WriteObjectField(field.toName) + field.encoder.Encode(ptr, stream) + isNotFirst = true + } + stream.WriteObjectEnd() + if stream.Error != nil && stream.Error != io.EOF { + stream.Error = fmt.Errorf("%v.%s", encoder.typ, stream.Error.Error()) + } +} + +func (encoder *structEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type emptyStructEncoder struct { +} + +func (encoder *emptyStructEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.WriteEmptyObject() +} + +func (encoder *emptyStructEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return false +} + +type stringModeNumberEncoder struct { + elemEncoder ValEncoder +} + +func (encoder *stringModeNumberEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + stream.writeByte('"') + encoder.elemEncoder.Encode(ptr, stream) + stream.writeByte('"') +} + +func (encoder *stringModeNumberEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} + +type stringModeStringEncoder struct { + elemEncoder ValEncoder + cfg *frozenConfig +} + +func (encoder *stringModeStringEncoder) Encode(ptr unsafe.Pointer, stream *Stream) { + tempStream := encoder.cfg.BorrowStream(nil) + tempStream.Attachment = stream.Attachment + defer encoder.cfg.ReturnStream(tempStream) + encoder.elemEncoder.Encode(ptr, tempStream) + stream.WriteString(string(tempStream.Buffer())) +} + +func (encoder *stringModeStringEncoder) IsEmpty(ptr unsafe.Pointer) bool { + return encoder.elemEncoder.IsEmpty(ptr) +} diff --git a/vendor/github.com/json-iterator/go/stream.go b/vendor/github.com/json-iterator/go/stream.go new file mode 100644 index 0000000..23d8a3a --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream.go @@ -0,0 +1,210 @@ +package jsoniter + +import ( + "io" +) + +// stream is a io.Writer like object, with JSON specific write functions. +// Error is not returned as return value, but stored as Error member on this stream instance. +type Stream struct { + cfg *frozenConfig + out io.Writer + buf []byte + Error error + indention int + Attachment interface{} // open for customized encoder +} + +// NewStream create new stream instance. +// cfg can be jsoniter.ConfigDefault. +// out can be nil if write to internal buffer. +// bufSize is the initial size for the internal buffer in bytes. +func NewStream(cfg API, out io.Writer, bufSize int) *Stream { + return &Stream{ + cfg: cfg.(*frozenConfig), + out: out, + buf: make([]byte, 0, bufSize), + Error: nil, + indention: 0, + } +} + +// Pool returns a pool can provide more stream with same configuration +func (stream *Stream) Pool() StreamPool { + return stream.cfg +} + +// Reset reuse this stream instance by assign a new writer +func (stream *Stream) Reset(out io.Writer) { + stream.out = out + stream.buf = stream.buf[:0] +} + +// Available returns how many bytes are unused in the buffer. +func (stream *Stream) Available() int { + return cap(stream.buf) - len(stream.buf) +} + +// Buffered returns the number of bytes that have been written into the current buffer. +func (stream *Stream) Buffered() int { + return len(stream.buf) +} + +// Buffer if writer is nil, use this method to take the result +func (stream *Stream) Buffer() []byte { + return stream.buf +} + +// SetBuffer allows to append to the internal buffer directly +func (stream *Stream) SetBuffer(buf []byte) { + stream.buf = buf +} + +// Write writes the contents of p into the buffer. +// It returns the number of bytes written. +// If nn < len(p), it also returns an error explaining +// why the write is short. +func (stream *Stream) Write(p []byte) (nn int, err error) { + stream.buf = append(stream.buf, p...) + if stream.out != nil { + nn, err = stream.out.Write(stream.buf) + stream.buf = stream.buf[nn:] + return + } + return len(p), nil +} + +// WriteByte writes a single byte. +func (stream *Stream) writeByte(c byte) { + stream.buf = append(stream.buf, c) +} + +func (stream *Stream) writeTwoBytes(c1 byte, c2 byte) { + stream.buf = append(stream.buf, c1, c2) +} + +func (stream *Stream) writeThreeBytes(c1 byte, c2 byte, c3 byte) { + stream.buf = append(stream.buf, c1, c2, c3) +} + +func (stream *Stream) writeFourBytes(c1 byte, c2 byte, c3 byte, c4 byte) { + stream.buf = append(stream.buf, c1, c2, c3, c4) +} + +func (stream *Stream) writeFiveBytes(c1 byte, c2 byte, c3 byte, c4 byte, c5 byte) { + stream.buf = append(stream.buf, c1, c2, c3, c4, c5) +} + +// Flush writes any buffered data to the underlying io.Writer. +func (stream *Stream) Flush() error { + if stream.out == nil { + return nil + } + if stream.Error != nil { + return stream.Error + } + _, err := stream.out.Write(stream.buf) + if err != nil { + if stream.Error == nil { + stream.Error = err + } + return err + } + stream.buf = stream.buf[:0] + return nil +} + +// WriteRaw write string out without quotes, just like []byte +func (stream *Stream) WriteRaw(s string) { + stream.buf = append(stream.buf, s...) +} + +// WriteNil write null to stream +func (stream *Stream) WriteNil() { + stream.writeFourBytes('n', 'u', 'l', 'l') +} + +// WriteTrue write true to stream +func (stream *Stream) WriteTrue() { + stream.writeFourBytes('t', 'r', 'u', 'e') +} + +// WriteFalse write false to stream +func (stream *Stream) WriteFalse() { + stream.writeFiveBytes('f', 'a', 'l', 's', 'e') +} + +// WriteBool write true or false into stream +func (stream *Stream) WriteBool(val bool) { + if val { + stream.WriteTrue() + } else { + stream.WriteFalse() + } +} + +// WriteObjectStart write { with possible indention +func (stream *Stream) WriteObjectStart() { + stream.indention += stream.cfg.indentionStep + stream.writeByte('{') + stream.writeIndention(0) +} + +// WriteObjectField write "field": with possible indention +func (stream *Stream) WriteObjectField(field string) { + stream.WriteString(field) + if stream.indention > 0 { + stream.writeTwoBytes(':', ' ') + } else { + stream.writeByte(':') + } +} + +// WriteObjectEnd write } with possible indention +func (stream *Stream) WriteObjectEnd() { + stream.writeIndention(stream.cfg.indentionStep) + stream.indention -= stream.cfg.indentionStep + stream.writeByte('}') +} + +// WriteEmptyObject write {} +func (stream *Stream) WriteEmptyObject() { + stream.writeByte('{') + stream.writeByte('}') +} + +// WriteMore write , with possible indention +func (stream *Stream) WriteMore() { + stream.writeByte(',') + stream.writeIndention(0) +} + +// WriteArrayStart write [ with possible indention +func (stream *Stream) WriteArrayStart() { + stream.indention += stream.cfg.indentionStep + stream.writeByte('[') + stream.writeIndention(0) +} + +// WriteEmptyArray write [] +func (stream *Stream) WriteEmptyArray() { + stream.writeTwoBytes('[', ']') +} + +// WriteArrayEnd write ] with possible indention +func (stream *Stream) WriteArrayEnd() { + stream.writeIndention(stream.cfg.indentionStep) + stream.indention -= stream.cfg.indentionStep + stream.writeByte(']') +} + +func (stream *Stream) writeIndention(delta int) { + if stream.indention == 0 { + return + } + stream.writeByte('\n') + toWrite := stream.indention - delta + for i := 0; i < toWrite; i++ { + stream.buf = append(stream.buf, ' ') + } +} diff --git a/vendor/github.com/json-iterator/go/stream_float.go b/vendor/github.com/json-iterator/go/stream_float.go new file mode 100644 index 0000000..826aa59 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_float.go @@ -0,0 +1,111 @@ +package jsoniter + +import ( + "fmt" + "math" + "strconv" +) + +var pow10 []uint64 + +func init() { + pow10 = []uint64{1, 10, 100, 1000, 10000, 100000, 1000000} +} + +// WriteFloat32 write float32 to stream +func (stream *Stream) WriteFloat32(val float32) { + if math.IsInf(float64(val), 0) || math.IsNaN(float64(val)) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + abs := math.Abs(float64(val)) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if float32(abs) < 1e-6 || float32(abs) >= 1e21 { + fmt = 'e' + } + } + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 32) +} + +// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster +func (stream *Stream) WriteFloat32Lossy(val float32) { + if math.IsInf(float64(val), 0) || math.IsNaN(float64(val)) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + if val < 0 { + stream.writeByte('-') + val = -val + } + if val > 0x4ffffff { + stream.WriteFloat32(val) + return + } + precision := 6 + exp := uint64(1000000) // 6 + lval := uint64(float64(val)*float64(exp) + 0.5) + stream.WriteUint64(lval / exp) + fval := lval % exp + if fval == 0 { + return + } + stream.writeByte('.') + for p := precision - 1; p > 0 && fval < pow10[p]; p-- { + stream.writeByte('0') + } + stream.WriteUint64(fval) + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] + } +} + +// WriteFloat64 write float64 to stream +func (stream *Stream) WriteFloat64(val float64) { + if math.IsInf(val, 0) || math.IsNaN(val) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + abs := math.Abs(val) + fmt := byte('f') + // Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right. + if abs != 0 { + if abs < 1e-6 || abs >= 1e21 { + fmt = 'e' + } + } + stream.buf = strconv.AppendFloat(stream.buf, float64(val), fmt, -1, 64) +} + +// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster +func (stream *Stream) WriteFloat64Lossy(val float64) { + if math.IsInf(val, 0) || math.IsNaN(val) { + stream.Error = fmt.Errorf("unsupported value: %f", val) + return + } + if val < 0 { + stream.writeByte('-') + val = -val + } + if val > 0x4ffffff { + stream.WriteFloat64(val) + return + } + precision := 6 + exp := uint64(1000000) // 6 + lval := uint64(val*float64(exp) + 0.5) + stream.WriteUint64(lval / exp) + fval := lval % exp + if fval == 0 { + return + } + stream.writeByte('.') + for p := precision - 1; p > 0 && fval < pow10[p]; p-- { + stream.writeByte('0') + } + stream.WriteUint64(fval) + for stream.buf[len(stream.buf)-1] == '0' { + stream.buf = stream.buf[:len(stream.buf)-1] + } +} diff --git a/vendor/github.com/json-iterator/go/stream_int.go b/vendor/github.com/json-iterator/go/stream_int.go new file mode 100644 index 0000000..d1059ee --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_int.go @@ -0,0 +1,190 @@ +package jsoniter + +var digits []uint32 + +func init() { + digits = make([]uint32, 1000) + for i := uint32(0); i < 1000; i++ { + digits[i] = (((i / 100) + '0') << 16) + ((((i / 10) % 10) + '0') << 8) + i%10 + '0' + if i < 10 { + digits[i] += 2 << 24 + } else if i < 100 { + digits[i] += 1 << 24 + } + } +} + +func writeFirstBuf(space []byte, v uint32) []byte { + start := v >> 24 + if start == 0 { + space = append(space, byte(v>>16), byte(v>>8)) + } else if start == 1 { + space = append(space, byte(v>>8)) + } + space = append(space, byte(v)) + return space +} + +func writeBuf(buf []byte, v uint32) []byte { + return append(buf, byte(v>>16), byte(v>>8), byte(v)) +} + +// WriteUint8 write uint8 to stream +func (stream *Stream) WriteUint8(val uint8) { + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteInt8 write int8 to stream +func (stream *Stream) WriteInt8(nval int8) { + var val uint8 + if nval < 0 { + val = uint8(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint8(nval) + } + stream.buf = writeFirstBuf(stream.buf, digits[val]) +} + +// WriteUint16 write uint16 to stream +func (stream *Stream) WriteUint16(val uint16) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return +} + +// WriteInt16 write int16 to stream +func (stream *Stream) WriteInt16(nval int16) { + var val uint16 + if nval < 0 { + val = uint16(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint16(nval) + } + stream.WriteUint16(val) +} + +// WriteUint32 write uint32 to stream +func (stream *Stream) WriteUint32(val uint32) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + } else { + r3 := q2 - q3*1000 + stream.buf = append(stream.buf, byte(q3+'0')) + stream.buf = writeBuf(stream.buf, digits[r3]) + } + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt32 write int32 to stream +func (stream *Stream) WriteInt32(nval int32) { + var val uint32 + if nval < 0 { + val = uint32(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint32(nval) + } + stream.WriteUint32(val) +} + +// WriteUint64 write uint64 to stream +func (stream *Stream) WriteUint64(val uint64) { + q1 := val / 1000 + if q1 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[val]) + return + } + r1 := val - q1*1000 + q2 := q1 / 1000 + if q2 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q1]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r2 := q1 - q2*1000 + q3 := q2 / 1000 + if q3 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q2]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r3 := q2 - q3*1000 + q4 := q3 / 1000 + if q4 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q3]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r4 := q3 - q4*1000 + q5 := q4 / 1000 + if q5 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q4]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) + return + } + r5 := q4 - q5*1000 + q6 := q5 / 1000 + if q6 == 0 { + stream.buf = writeFirstBuf(stream.buf, digits[q5]) + } else { + stream.buf = writeFirstBuf(stream.buf, digits[q6]) + r6 := q5 - q6*1000 + stream.buf = writeBuf(stream.buf, digits[r6]) + } + stream.buf = writeBuf(stream.buf, digits[r5]) + stream.buf = writeBuf(stream.buf, digits[r4]) + stream.buf = writeBuf(stream.buf, digits[r3]) + stream.buf = writeBuf(stream.buf, digits[r2]) + stream.buf = writeBuf(stream.buf, digits[r1]) +} + +// WriteInt64 write int64 to stream +func (stream *Stream) WriteInt64(nval int64) { + var val uint64 + if nval < 0 { + val = uint64(-nval) + stream.buf = append(stream.buf, '-') + } else { + val = uint64(nval) + } + stream.WriteUint64(val) +} + +// WriteInt write int to stream +func (stream *Stream) WriteInt(val int) { + stream.WriteInt64(int64(val)) +} + +// WriteUint write uint to stream +func (stream *Stream) WriteUint(val uint) { + stream.WriteUint64(uint64(val)) +} diff --git a/vendor/github.com/json-iterator/go/stream_str.go b/vendor/github.com/json-iterator/go/stream_str.go new file mode 100644 index 0000000..54c2ba0 --- /dev/null +++ b/vendor/github.com/json-iterator/go/stream_str.go @@ -0,0 +1,372 @@ +package jsoniter + +import ( + "unicode/utf8" +) + +// htmlSafeSet holds the value true if the ASCII character with the given +// array position can be safely represented inside a JSON string, embedded +// inside of HTML