Compare commits
373
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11d705124d | ||
|
|
b8ef777339 | ||
|
|
7589203719 | ||
|
|
67e9b563b4 | ||
|
|
bca4b4adaf | ||
|
|
14224c2de5 | ||
|
|
4e01670ceb | ||
|
|
e0a35868af | ||
|
|
888a71df57 | ||
|
|
4fecfaa701 | ||
|
|
884aa6a439 | ||
|
|
c14f8441fb | ||
|
|
5bd389757c | ||
|
|
c32459f73d | ||
|
|
911a5bdf46 | ||
|
|
3ee480f5e3 | ||
|
|
5daaea50a1 | ||
|
|
3a66223a89 | ||
|
|
674dd99f92 | ||
|
|
eb066cb055 | ||
|
|
5175d87e08 | ||
|
|
1db559469f | ||
|
|
84c3529a66 | ||
|
|
896f08a8cb | ||
|
|
86e96b79b1 | ||
|
|
f23359dfcb | ||
|
|
ea81d2716f | ||
|
|
e43a27e5d3 | ||
|
|
f122ad081b | ||
|
|
81c8e86eb4 | ||
|
|
d81961e9d6 | ||
|
|
45bc24711e | ||
|
|
c9ce1158ea | ||
|
|
b1c4322c98 | ||
|
|
5625f00174 | ||
|
|
f2c3f9dea5 | ||
|
|
2d7adad800 | ||
|
|
939a94b704 | ||
|
|
bbeb6eb735 | ||
|
|
5ee5854831 | ||
|
|
5ee9d85682 | ||
|
|
0442513f43 | ||
|
|
69664d764a | ||
|
|
67ff6571be | ||
|
|
a2c5dab4a7 | ||
|
|
d2da566f25 | ||
|
|
d19bb44bb6 | ||
|
|
c036063534 | ||
|
|
ec327424c9 | ||
|
|
71e0768231 | ||
|
|
4da0d51b5b | ||
|
|
1976e3aa29 | ||
|
|
07540b762e | ||
|
|
641aef0150 | ||
|
|
c17970678b | ||
|
|
b1d5aae316 | ||
|
|
2637770d82 | ||
|
|
051c2f08c4 | ||
|
|
7de82862bd | ||
|
|
187e1f07a0 | ||
|
|
f693afee79 | ||
|
|
d489c4281e | ||
|
|
e11f65ac05 | ||
|
|
41ce47f7e0 | ||
|
|
09dbce4125 | ||
|
|
20f3fb7b5e | ||
|
|
a18deb8762 | ||
|
|
72b37d77e2 | ||
|
|
494ffac97c | ||
|
|
841c75b457 | ||
|
|
fbd64f9d47 | ||
|
|
9b09326317 | ||
|
|
601a690901 | ||
|
|
4947ac5d4e | ||
|
|
df693c0294 | ||
|
|
3f65b11a65 | ||
|
|
38f22dfdf8 | ||
|
|
302e9b7a54 | ||
|
|
996abfda16 | ||
|
|
fb882e5c5c | ||
|
|
3a2ad9219c | ||
|
|
7514be3309 | ||
|
|
4f67872d3f | ||
|
|
558682da1e | ||
|
|
40b37f8900 | ||
|
|
4791c6dbaf | ||
|
|
05ac07c3bb | ||
|
|
4cc5edeed0 | ||
|
|
830ef54663 | ||
|
|
0cb61c184a | ||
|
|
e9030f6282 | ||
|
|
51081ca964 | ||
|
|
cb59605eba | ||
|
|
d7779efdbd | ||
|
|
b89e10a0bd | ||
|
|
9bf05f1e9d | ||
|
|
8f80bf5742 | ||
|
|
1746acd559 | ||
|
|
b16ac80053 | ||
|
|
635046d221 | ||
|
|
46fc51275e | ||
|
|
055921d711 | ||
|
|
bf8cfff7fa | ||
|
|
3be63ce95a | ||
|
|
f5a38117b1 | ||
|
|
21714e0603 | ||
|
|
c966a2cca5 | ||
|
|
c2f154da02 | ||
|
|
2343940930 | ||
|
|
2d6398224f | ||
|
|
ac1457e534 | ||
|
|
b59a5ce858 | ||
|
|
4352c400b4 | ||
|
|
1653289e01 | ||
|
|
cf20571a7d | ||
|
|
e4755abdc8 | ||
|
|
e7935499b6 | ||
|
|
6f48eea3c9 | ||
|
|
4251ca3da9 | ||
|
|
3a564dfae8 | ||
|
|
c4871f210d | ||
|
|
fcebffe4b6 | ||
|
|
a741135dc3 | ||
|
|
7d60f6d51d | ||
|
|
fb0a08ea13 | ||
|
|
10e316049d | ||
|
|
753af57524 | ||
|
|
1f232c4271 | ||
|
|
a7ec10fa39 | ||
|
|
d799b5be60 | ||
|
|
03bbdd1761 | ||
|
|
72a62d1996 | ||
|
|
3552e08f29 | ||
|
|
c2e7c5ab2b | ||
|
|
3b3fc9dcfb | ||
|
|
db7a668875 | ||
|
|
a4b3bfa390 | ||
|
|
c77ab9d5f8 | ||
|
|
e65f5ac03c | ||
|
|
c08782855b | ||
|
|
a5a4dab813 | ||
|
|
03a7b16026 | ||
|
|
9a12e08181 | ||
|
|
cd04e996e1 | ||
|
|
051dea1674 | ||
|
|
c1263fce77 | ||
|
|
f3bc3ce657 | ||
|
|
3beb23d4de | ||
|
|
3f177eb436 | ||
|
|
df15ae228a | ||
|
|
61bdaeaa3d | ||
|
|
03580260e7 | ||
|
|
cf42bed9bf | ||
|
|
c4c0f2ea10 | ||
|
|
c1d4680a02 | ||
|
|
1517f744d3 | ||
|
|
6af7ed9cb8 | ||
|
|
5cff5df97b | ||
|
|
d208ad633e | ||
|
|
a664d5db4a | ||
|
|
7b5e1362be | ||
|
|
b2305c0f12 | ||
|
|
73ab09dc7d | ||
|
|
150d61fb18 | ||
|
|
158962dcfe | ||
|
|
41479adbb0 | ||
|
|
2c1c655fed | ||
|
|
669542b546 | ||
|
|
92021b8a0e | ||
|
|
1bbe8c71ce | ||
|
|
98b79732fa | ||
|
|
d2f56ca43e | ||
|
|
6fcc9e45e3 | ||
|
|
7f7a827a69 | ||
|
|
a915bdf633 | ||
|
|
ef0028c091 | ||
|
|
4cad9cbbb4 | ||
|
|
7f7216b91a | ||
|
|
7e899197ec | ||
|
|
c25d6e3d3b | ||
|
|
da3ae21766 | ||
|
|
84888e8202 | ||
|
|
cccb1fc80b | ||
|
|
d3747e6ff3 | ||
|
|
036200a765 | ||
|
|
fa89426bcc | ||
|
|
8a2752fdaa | ||
|
|
efc521f8fe | ||
|
|
dbf35fc383 | ||
|
|
6e9918dc7b | ||
|
|
b21154afd7 | ||
|
|
234ea0ca38 | ||
|
|
e81028722f | ||
|
|
557491ed05 | ||
|
|
1e6c72ead2 | ||
|
|
bcf3fd576a | ||
|
|
fa3d8f5f14 | ||
|
|
74625d0525 | ||
|
|
a355338d40 | ||
|
|
60fc5d9170 | ||
|
|
0877e05811 | ||
|
|
abcf2162a7 | ||
|
|
0cea0d4f0a | ||
|
|
205c4724d4 | ||
|
|
917982cff1 | ||
|
|
4d1c17f9ae | ||
|
|
45810b4ec8 | ||
|
|
fdd46409cd | ||
|
|
72e89b1c9f | ||
|
|
060c5a09de | ||
|
|
0d5b55f3a1 | ||
|
|
3d29805df6 | ||
|
|
2561479816 | ||
|
|
447d33747a | ||
|
|
56e38174bf | ||
|
|
f90f21ebef | ||
|
|
c6f5f4096b | ||
|
|
d2a1b2394b | ||
|
|
0a2eab739e | ||
|
|
f26b953a3f | ||
|
|
882f6a47bf | ||
|
|
2d3179180e | ||
|
|
5d6616652d | ||
|
|
b349af7351 | ||
|
|
c843bce25d | ||
|
|
607539d47b | ||
|
|
b2ec20421f | ||
|
|
14d526e033 | ||
|
|
e2df3f377d | ||
|
|
670957db36 | ||
|
|
c1e4aded9d | ||
|
|
ca4554f514 | ||
|
|
39911e3a09 | ||
|
|
17559ce3ba | ||
|
|
b79ed21c10 | ||
|
|
850abfd93c | ||
|
|
5af15ed13a | ||
|
|
d3ffa31e00 | ||
|
|
ece61a0e87 | ||
|
|
bb4c8cd8ad | ||
|
|
f54132443c | ||
|
|
82009842a6 | ||
|
|
312f4fbd24 | ||
|
|
8fa3be2d17 | ||
|
|
a7147a0c06 | ||
|
|
b40c180471 | ||
|
|
1ab60e0a29 | ||
|
|
68e15a3c78 | ||
|
|
c90721bb13 | ||
|
|
0f368d304a | ||
|
|
a98d4db606 | ||
|
|
848df1830f | ||
|
|
a9485516b6 | ||
|
|
4c3559bffd | ||
|
|
5f1d8c8fd4 | ||
|
|
4e6b21a7d9 | ||
|
|
7be37bc52d | ||
|
|
208dbe7b58 | ||
|
|
193adeed9c | ||
|
|
198f5633d4 | ||
|
|
e2e8bf5f45 | ||
|
|
932d5cb725 | ||
|
|
5bb4da2650 | ||
|
|
2cf17a20d0 | ||
|
|
f3accb56b5 | ||
|
|
9ecc52a8eb | ||
|
|
27bc07fcd9 | ||
|
|
fcade81bf5 | ||
|
|
a720cef797 | ||
|
|
abd9a937a1 | ||
|
|
7feb2d6507 | ||
|
|
06818e5616 | ||
|
|
ca8d278566 | ||
|
|
d3068c1947 | ||
|
|
4d6094b384 | ||
|
|
0ee80926ef | ||
|
|
a72862f94e | ||
|
|
0e8afa6cd6 | ||
|
|
5456e59f0b | ||
|
|
e2549ebffe | ||
|
|
23c6b16a7c | ||
|
|
5b61803868 | ||
|
|
07acc3b087 | ||
|
|
d8f9a6940d | ||
|
|
7bde532b31 | ||
|
|
12811d119a | ||
|
|
21ab57ddc2 | ||
|
|
80880c2f69 | ||
|
|
38d065ab86 | ||
|
|
685520ef8d | ||
|
|
974eac515e | ||
|
|
1db5a1a82e | ||
|
|
dfc78ddc71 | ||
|
|
6bac52cdea | ||
|
|
48e310d4b0 | ||
|
|
bf6a8de246 | ||
|
|
416013ed1d | ||
|
|
f5ab9c768f | ||
|
|
bbb9d200ce | ||
|
|
2a53d5b19d | ||
|
|
2135dfca96 | ||
|
|
32ef7a7097 | ||
|
|
faaa642b0b | ||
|
|
a5b8620e39 | ||
|
|
724c25ecd6 | ||
|
|
4091b62817 | ||
|
|
5cc4936962 | ||
|
|
677c49216f | ||
|
|
251505f9f7 | ||
|
|
cccb276493 | ||
|
|
495ff06bbe | ||
|
|
72b163e22d | ||
|
|
3e77f00d16 | ||
|
|
00c43353f2 | ||
|
|
82a3f877a7 | ||
|
|
edf17d6434 | ||
|
|
7c1fd79af1 | ||
|
|
c281fb1e01 | ||
|
|
ddaf57df6c | ||
|
|
011aaa50e8 | ||
|
|
0d956b6bf6 | ||
|
|
8f2a6a58f2 | ||
|
|
24dc1fe615 | ||
|
|
dc5ca4b1c6 | ||
|
|
9884712392 | ||
|
|
0c5b23b790 | ||
|
|
edd51c67c4 | ||
|
|
05341ad604 | ||
|
|
493f105055 | ||
|
|
f5d46fcaba | ||
|
|
8533f1aaad | ||
|
|
419c3799f6 | ||
|
|
00c0e4949b | ||
|
|
88fc42f8ec | ||
|
|
d28b0c09de | ||
|
|
412a150d1e | ||
|
|
405f6f8cee | ||
|
|
d8ca8e4116 | ||
|
|
dcb2d5943d | ||
|
|
8da7fab51f | ||
|
|
8408f574a1 | ||
|
|
973812230a | ||
|
|
2c45cb2887 | ||
|
|
1cd2b08524 | ||
|
|
61afe79506 | ||
|
|
b97e82c2dd | ||
|
|
d40d78d098 | ||
|
|
6e59ef4e8d | ||
|
|
d0f0642c45 | ||
|
|
577c1fd1a6 | ||
|
|
1b7eef2443 | ||
|
|
6fc835dacb | ||
|
|
1cad4a158e | ||
|
|
b0c9033c06 | ||
|
|
b224f0d4a1 | ||
|
|
b4d913d517 | ||
|
|
c28e08d7a2 | ||
|
|
7b7bccbca2 | ||
|
|
8c0513d394 | ||
|
|
7ab0e77a97 | ||
|
|
cbca0e9fa9 | ||
|
|
1b92bd9d7d | ||
|
|
be84492c3d | ||
|
|
00f555442d | ||
|
|
dc572d0f65 | ||
|
|
256dc78e5b | ||
|
|
b6e13fb4af | ||
|
|
1109b9f12e | ||
|
|
0bdedc65ad | ||
|
|
7ffe48855f | ||
|
|
266a5cb5d8 | ||
|
|
678147c9ed | ||
|
|
4e608d872a |
No files matched your search
@@ -20,7 +20,12 @@ linters:
|
||||
- wsl_v5 # расставление пробелов очень индивидуально
|
||||
- godoclint # ругается на // nolint, не удобно
|
||||
- prealloc # слишком аггресивный, в большинстве случаев не требуется
|
||||
- gomodguard # deprecated
|
||||
- goconst # слишком агрессивный
|
||||
settings:
|
||||
exhaustruct_v5:
|
||||
allow-empty: true
|
||||
explicit-mode: true
|
||||
cyclop:
|
||||
max-complexity: 15 # по умолчанию 10 мало
|
||||
funlen:
|
||||
@@ -60,6 +65,9 @@ linters:
|
||||
- unqueryvet
|
||||
- prealloc
|
||||
path: ".*_test\\.go$"
|
||||
- linters:
|
||||
- goconst
|
||||
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
|
||||
paths:
|
||||
- third_party$
|
||||
- builtin$
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
### v7.2.0
|
||||
* Добавлено поле `application_group` в таблицу `roles`
|
||||
* Добавлен для запросов `admin/role/create` и `admin/role/update`, необязателен
|
||||
* Изменен эндпоинт `admin/role/all`, теперь результаты фильтруются по группе из тела запроса, при пустом теле без фильтрации
|
||||
### v7.1.0
|
||||
* переименование авторизации через SUDIR в OAuth:
|
||||
* Эндпоинты: `admin/auth/login_with_oauth`, `admin/ui_settings/oauth`
|
||||
|
||||
+4
-3
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
type roleService interface {
|
||||
All(ctx context.Context) ([]domain.Role, error)
|
||||
All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error)
|
||||
Create(ctx context.Context, req domain.CreateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Update(ctx context.Context, req domain.UpdateRoleRequest, adminId int64) (*domain.Role, error)
|
||||
Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId int64) error
|
||||
@@ -35,12 +35,13 @@ func NewRole(roleService roleService) Role {
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-AUTH-ADMIN header string true "Токен администратора"
|
||||
// @Param body body domain.RoleAllRequest true "Тело запроса"
|
||||
// @Success 200 {array} domain.Role
|
||||
// @Failure 400 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /role/all [POST]
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx)
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
users, err := u.roleService.All(ctx, req)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get roles")
|
||||
}
|
||||
|
||||
@@ -385,6 +385,15 @@
|
||||
"name": "X-AUTH-ADMIN",
|
||||
"in": "header",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Тело запроса",
|
||||
"name": "body",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/domain.RoleAllRequest"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -1564,6 +1573,10 @@
|
||||
"domain.CreateRoleRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Группа приложений",
|
||||
"type": "string"
|
||||
},
|
||||
"changeMessage": {
|
||||
"description": "Причина изменений",
|
||||
"type": "string"
|
||||
@@ -1805,6 +1818,10 @@
|
||||
"domain.Role": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Группа приложений",
|
||||
"type": "string"
|
||||
},
|
||||
"changeMessage": {
|
||||
"description": "Причина изменений",
|
||||
"type": "string"
|
||||
@@ -1844,6 +1861,15 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.RoleAllRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Фильтр по группе приложений",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain.SecureAuthRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
@@ -2049,6 +2075,10 @@
|
||||
"domain.UpdateRoleRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"applicationGroup": {
|
||||
"description": "Группа приложений",
|
||||
"type": "string"
|
||||
},
|
||||
"changeMessage": {
|
||||
"description": "Причина изменений",
|
||||
"type": "string"
|
||||
|
||||
+25
-18
@@ -5,32 +5,39 @@ import (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time // Дата создания
|
||||
UpdatedAt time.Time // Дата обновления
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time // Дата создания
|
||||
UpdatedAt time.Time // Дата обновления
|
||||
}
|
||||
|
||||
type CreateRoleRequest struct {
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
}
|
||||
|
||||
type UpdateRoleRequest struct {
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
Id int // Идентификатор роли
|
||||
Name string // Название роли
|
||||
ExternalGroup string // Внешнее название группы
|
||||
ApplicationGroup string // Группа приложений
|
||||
ChangeMessage string // Причина изменений
|
||||
Permissions []string // Набор прав
|
||||
}
|
||||
|
||||
type DeleteRoleRequest struct {
|
||||
Id int // Идентификатор роли
|
||||
}
|
||||
|
||||
type RoleAllRequest struct {
|
||||
ApplicationGroup *string `validate:"omitnil,min=1"` // Фильтр по группе приложений
|
||||
}
|
||||
+9
-8
@@ -13,14 +13,15 @@ const (
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
Permissions PermList
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
Id int
|
||||
Name string
|
||||
ExternalGroup string
|
||||
ApplicationGroup string
|
||||
Permissions PermList
|
||||
Immutable bool
|
||||
Exclusive bool
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type PermList []string
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module isp-admin-service
|
||||
|
||||
go 1.26.0
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/Masterminds/squirrel v1.5.4
|
||||
@@ -8,11 +8,11 @@ require (
|
||||
github.com/iancoleman/strcase v0.3.0
|
||||
github.com/stretchr/testify v1.12.1
|
||||
github.com/txix-open/bgjob v1.6.0
|
||||
github.com/txix-open/isp-kit v1.74.1
|
||||
github.com/txix-open/isp-kit v1.76.0
|
||||
github.com/txix-open/jsonschema v1.3.0
|
||||
golang.org/x/crypto v0.55.0
|
||||
golang.org/x/sync v0.22.0
|
||||
google.golang.org/grpc v1.83.2
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/sync v0.25.0
|
||||
google.golang.org/grpc v1.85.0
|
||||
)
|
||||
|
||||
require (
|
||||
@@ -22,61 +22,63 @@ require (
|
||||
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/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/gabriel-vasile/mimetype v1.4.16 // indirect
|
||||
github.com/getsentry/sentry-go v0.50.0 // indirect
|
||||
github.com/go-faker/faker/v4 v4.12.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.30.0 // indirect
|
||||
github.com/go-playground/locales v0.14.2 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.2 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.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/jackc/pgx/v5 v5.13.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.4 // indirect
|
||||
github.com/jmoiron/sqlx v1.4.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/compress v1.19.2 // indirect
|
||||
github.com/klauspost/compress v1.20.4 // indirect
|
||||
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
|
||||
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
|
||||
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/mfridman/interpolate v0.2.0 // 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/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.70.1 // indirect
|
||||
github.com/prometheus/procfs v0.21.1 // indirect
|
||||
github.com/pandatix/go-abnf v0.5.5 // indirect
|
||||
github.com/pressly/goose/v3 v3.30.1 // indirect
|
||||
github.com/prometheus/client_golang v1.25.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.3 // indirect
|
||||
github.com/prometheus/common v0.74.0 // indirect
|
||||
github.com/prometheus/procfs v0.23.0 // indirect
|
||||
github.com/robfig/cron/v3 v3.0.1 // indirect
|
||||
github.com/sethvargo/go-retry v0.4.0 // indirect
|
||||
github.com/sethvargo/go-retry v0.5.0 // indirect
|
||||
github.com/txix-open/bellows v1.2.0 // 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/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 // 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.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.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect
|
||||
go.opentelemetry.io/otel v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/log v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.47.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.uber.org/zap v1.28.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.5 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.6 // indirect
|
||||
golang.org/x/net v0.63.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f // indirect
|
||||
google.golang.org/protobuf v1.36.12 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
@@ -21,16 +21,23 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSs
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15/go.mod h1:azpTcoLcDZRNgFou5j+APrqQx9HqVPWa6ijYQIIVswQ=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E=
|
||||
github.com/gabriel-vasile/mimetype v1.4.16/go.mod h1:3oFFwxX8kTklZwzIl2aQEDZT0lKY8xH92ST88bAwba4=
|
||||
github.com/getsentry/sentry-go v0.49.0 h1:Ehejknu1l023Ub7QoRBVLAI7g3Jnhqku4oWx4B4Sh5s=
|
||||
github.com/getsentry/sentry-go v0.49.0/go.mod h1:nuMJAoCfe1u0Bts2ocyNI+TW8HT84vRMqwA5Qq/SKUI=
|
||||
github.com/getsentry/sentry-go v0.50.0 h1:gkO59rn/i0RCAXUUTflC5QVbTQGPXbaFabs2olVzc9g=
|
||||
github.com/getsentry/sentry-go v0.50.0/go.mod h1:+xsDuN+SoRN/xfs1hdq78wnrE3omIZf+FCuh9FOW1C8=
|
||||
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
|
||||
github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-faker/faker/v4 v4.11.0 h1:HeIFTzafXsgrlxKE2QySGGTQocfGdQ8sGqU2CXvs120=
|
||||
github.com/go-faker/faker/v4 v4.11.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-faker/faker/v4 v4.12.0 h1:yZXxuoQjxN+C2PVgYoDSHGiD9wj6dX1/Ful4p7QQV0k=
|
||||
github.com/go-faker/faker/v4 v4.12.0/go.mod h1:VFIEwWDd16EdYDLF6NJ5gAAzEp7vz5LgKgJ2iZ17Tdg=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
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=
|
||||
@@ -40,13 +47,18 @@ github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lY
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/locales v0.14.2 h1:d8UmcrM6Nip0hfGZKLGpAvZH37XB4TS0xzK9B56YNCY=
|
||||
github.com/go-playground/locales v0.14.2/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU=
|
||||
github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk=
|
||||
github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=
|
||||
github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw=
|
||||
github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk=
|
||||
github.com/go-sql-driver/mysql v1.10.1 h1:arlSnNLq6a5yxGxV7qg9lF4j0C+KwD6NbQyKr9QL6ME=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
@@ -56,6 +68,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0 h1:/Tnpcb2E0Pz/tN9s3bfEY2Q8ePCEX9iuS+cneUwncnw=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.30.0/go.mod h1:zOBXOsUaBSjKgmH4OGzV1esUpR3oUSCPYVd2cUBjKYY=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 h1:vzlTzzi4tHLa/JQdIE5LeXw6SEX5EVVhq/VPqKHnKOk=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0/go.mod h1:FHXQZnW5pA0txiMr3jApv9uNJzZ+7mYZd+u+PPenCFU=
|
||||
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
|
||||
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
@@ -64,8 +78,12 @@ github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7Ulw
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
|
||||
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
@@ -74,6 +92,8 @@ github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4d
|
||||
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI=
|
||||
github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -92,10 +112,13 @@ github.com/mailru/easyjson v0.9.2 h1:dX8U45hQsZpxd80nLvDGihsQ/OxlvTkVUXH2r/8cb2M
|
||||
github.com/mailru/easyjson v0.9.2/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY=
|
||||
github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg=
|
||||
github.com/mfridman/interpolate v0.2.0 h1:HM9ID8p6CUxoMJX+fECOtGQ2Mu7TW/GIMPyu48nnvUg=
|
||||
github.com/mfridman/interpolate v0.2.0/go.mod h1:8SfDy95IaPNnIokZh9mvIppmc3fGl8fx+Gu7uusuO9Q=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -107,6 +130,9 @@ github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk=
|
||||
github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM=
|
||||
github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc=
|
||||
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
|
||||
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
@@ -114,16 +140,27 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA=
|
||||
github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY=
|
||||
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
|
||||
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
|
||||
github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU=
|
||||
github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE=
|
||||
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
|
||||
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
|
||||
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
|
||||
github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY=
|
||||
github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc=
|
||||
github.com/prometheus/common v0.74.0 h1:6iYW8MsYvmEnXFD9zLGgF0qmReaRhs3OMONu1c/nrLI=
|
||||
github.com/prometheus/common v0.74.0/go.mod h1:i/02C+FCst5B1etKgWesNrD49n+onplJCqUCtUKkOeA=
|
||||
github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI=
|
||||
github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY=
|
||||
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
|
||||
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ=
|
||||
github.com/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=
|
||||
@@ -132,6 +169,8 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/sethvargo/go-retry v0.4.0 h1:9qy1OoIAxBL+gBYnkTnTnWle5wlfsXQlwRzIbbpdqPw=
|
||||
github.com/sethvargo/go-retry v0.4.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/sethvargo/go-retry v0.5.0 h1:JYfFKmVJ8ER06GReN1efzc5cm52BrVsFVzmcHiKJwfY=
|
||||
github.com/sethvargo/go-retry v0.5.0/go.mod h1:tvsjdKG6xfiCx4LSiUZ06kcv38xvdVQwv8R6/VnnVWg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
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=
|
||||
@@ -155,10 +194,14 @@ github.com/txix-open/grmq v1.12.0 h1:lSPYvwLfTL0+b0xDQmuuN6RaKS3NCEJNK9ccWpOWa8Y
|
||||
github.com/txix-open/grmq v1.12.0/go.mod h1:6m9CCTQao/HAFalu5rFOZGJ5KLEP6WzzIwj80Ml3KGE=
|
||||
github.com/txix-open/isp-kit v1.74.1 h1:2WQl1+e6E1TXcgkm554kYpiyORgZiyJa/zQIks4cUCw=
|
||||
github.com/txix-open/isp-kit v1.74.1/go.mod h1:i4g+hgfVQAXa02kHqr104TqYEsiW2em17RZF0KjkB78=
|
||||
github.com/txix-open/isp-kit v1.76.0 h1:kqhX2DuoTfeW7BIshedG26TRIfOgX0QOInm606ssGVg=
|
||||
github.com/txix-open/isp-kit v1.76.0/go.mod h1:hR9iAlh3x9gEg5GfALrrkN/2SbGkgZQCmwO2GZWjC1M=
|
||||
github.com/txix-open/jsonschema v1.3.0 h1:XGuOTg22G7PdqfKypjajM20/i5FyGfFYsJKmheebKi4=
|
||||
github.com/txix-open/jsonschema v1.3.0/go.mod h1:l8YDZ1nvJrw6uxWowSVOxCV/ebiMJyapffW87ZEqH00=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb h1:UJgT4u/QMv5QHKOQeJ7igShHa36c2/vIRqJiRLdDlf0=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20250506161033-f8ce404fffdb/go.mod h1:0biAFE0bgbcKeBBAwgEDhbZz6uT1vuSETCrFQlv2RiA=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3 h1:1jE11HLmMHDYYAcE+UmQ5VHgz4stzz0+daJbDWS+sEs=
|
||||
github.com/txix-open/validator/v10 v10.0.0-20261027072444-85f3391fc5c3/go.mod h1:Yf41v210LFyYAj+tGmDh7PHdGsTaZjdBzHG0ptUvihw=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
|
||||
github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
|
||||
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
|
||||
@@ -172,24 +215,44 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0 h1:oFNJW32h2SXnET7XXstgT7pVh4vN+jW+GfiIaBguIZE=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.71.0/go.mod h1:+H3sPOFwag14eMHTPMElZtV0e4YfVZ/85KgrKUCB5FI=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
go.opentelemetry.io/otel v1.46.0/go.mod h1:Gj3SEScelsNC45tp4nSxRYlS+f5iez7W8XPMCt905kE=
|
||||
go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM=
|
||||
go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0 h1:OFnwLJr+pF3iHrlGSzbxyuo6/6HyBlnlN1CWEJmBVcw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.46.0/go.mod h1:716wFneO0ov19A2beH5hjfh9AK5z/VWNAtDijp1Y0/g=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0 h1:KrC1YrQeSt46ITMWAbgQx1M1eV1/1TKzttrBzymPmss=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.46.0/go.mod h1:zDSEzoEqsOrgBeGvH66KRgxh90VonFyJqBHA0Pk3+rM=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0 h1:aXZXsZ012wOgVkqaiQv+Z/d8V0xKjmg70F6m4CE94lc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.47.0/go.mod h1:ziu1gUIJhAaxM3EV1e3Ralk5AAyL1UOYz3lJJ4VSI38=
|
||||
go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI=
|
||||
go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw=
|
||||
go.opentelemetry.io/otel/metric v1.46.0 h1:yBnkXvgV7AXFILZc5K6IZe/CBFF3OS7BJ8ov6/lj0K8=
|
||||
go.opentelemetry.io/otel/metric v1.46.0/go.mod h1:iPmdWqifKUdzziPkvvzIJXITl56fQx2mGM/DHLB3/2o=
|
||||
go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY=
|
||||
go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0 h1:h5CNQQjEbuQXY/JfZtgt3i7HVFV3aHPO2OAwO2eTYPI=
|
||||
go.opentelemetry.io/otel/sdk v1.46.0/go.mod h1:GAERFXFt5SYCEB+YiKUbMBeza6UaDH7GmGOZEfh2gSM=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I=
|
||||
go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0 h1:0piZ26EG4RBfebb2jhDH6ERCYHoVWduc3kLgPCwSnSE=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.46.0/go.mod h1:I1PbKrdVc8Qu8HYVDNtqVIwLwjNrhsV/uFuxfwg8mO4=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw=
|
||||
go.opentelemetry.io/otel/trace v1.46.0 h1:OULy7ccdJnZtJ0UDYFOIGaCmiWzJ8Vi2G/Rsu60qs1c=
|
||||
go.opentelemetry.io/otel/trace v1.46.0/go.mod h1:J7GAXweO77XSFkB/rmAqk9D6ihszhFjLU+d9WuUxDLI=
|
||||
go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM=
|
||||
go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
|
||||
go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1 h1:SCrPqH9NE5CmBrOqpjNCiT0X5mGwMyGERXdogfR7Yjw=
|
||||
go.opentelemetry.io/proto/otlp v1.11.1/go.mod h1:wq8W4aSf6bOy8RZyESOeQFr9Pu7wydWX/TY4sgvrTPg=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
@@ -198,26 +261,45 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v2 v2.4.5 h1:a5nxWvYi94DRl6QSLlTbLpVmutgx2qg8EVjnJtuFpwI=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5 h1:izFU9hz7aeLI/Mi1J0991ae+xcwRLr7hTqWnB/9aIIU=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260825221802-da73d73af1c5/go.mod h1:3LhxRw4YYkf+ylAfgaY9JlVLFKhokkCV8duhLLe7+t0=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5 h1:1VUiZAXyC+zmiFYi+WLtBzr68Cj8wOofHjjrA/kkizc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260825221802-da73d73af1c5/go.mod h1:DjtHYE8FKJLivXcBEjGwndXfIC23G0VpXiXKqG179uA=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
|
||||
google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8=
|
||||
google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw=
|
||||
google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ=
|
||||
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
|
||||
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=
|
||||
@@ -230,9 +312,12 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
|
||||
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/libc v1.80.2 h1:3+a4fJZvvzg920ZC0mOepnKPGn7cqCaVeDxm/UnrM1A=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/sqlite v1.62.0 h1:gMaCjSM1qpl+iOjiWhR1LYP3zqrYDI+5GYLGt6veP2g=
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
ALTER TABLE roles ADD COLUMN application_group TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- +goose Down
|
||||
ALTER TABLE roles DROP COLUMN application_group;
|
||||
+20
-4
@@ -25,6 +25,7 @@ const (
|
||||
updatedAtRolesColumn = "updated_at"
|
||||
permissionsRolesColumn = "permissions"
|
||||
externalGroupRolesColumn = "external_group"
|
||||
applicationGroupColumn = "application_group"
|
||||
immutableRolesColumn = "immutable"
|
||||
exclusiveRolesColumn = "exclusive"
|
||||
)
|
||||
@@ -37,7 +38,7 @@ func (r Role) GetRoleByIds(ctx context.Context, id []int) ([]entity.Role, error)
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.GetRoleByIds")
|
||||
|
||||
q, args, err := query.New().
|
||||
Select("id, name, external_group, permissions, created_at, updated_at").
|
||||
Select("id, name, external_group, application_group, permissions, created_at, updated_at").
|
||||
From("roles").
|
||||
Where(squirrel.Eq{"id": id}).
|
||||
ToSql()
|
||||
@@ -67,6 +68,7 @@ func (r Role) GetRoleByName(ctx context.Context, name string) (*entity.Role, err
|
||||
updatedAtRolesColumn,
|
||||
permissionsRolesColumn,
|
||||
externalGroupRolesColumn,
|
||||
applicationGroupColumn,
|
||||
immutableRolesColumn,
|
||||
exclusiveRolesColumn,
|
||||
).
|
||||
@@ -101,6 +103,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
||||
updatedAtRolesColumn,
|
||||
permissionsRolesColumn,
|
||||
externalGroupRolesColumn,
|
||||
applicationGroupColumn,
|
||||
immutableRolesColumn,
|
||||
exclusiveRolesColumn,
|
||||
).
|
||||
@@ -122,7 +125,7 @@ func (r Role) GetRolesByExternalGroup(ctx context.Context, groups []string) ([]e
|
||||
|
||||
func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.All")
|
||||
q := "select id, name, external_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||
q := "select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at from roles order by created_at"
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, q)
|
||||
if err != nil {
|
||||
@@ -131,12 +134,24 @@ func (r Role) All(ctx context.Context) ([]entity.Role, error) {
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.AllWithFilter")
|
||||
roles := make([]entity.Role, 0)
|
||||
err := r.db.Select(ctx, &roles, `
|
||||
select id, name, external_group, application_group, permissions, immutable, exclusive, created_at, updated_at
|
||||
from roles where application_group=$1 order by created_at`, applicationGroup)
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "select all roles")
|
||||
}
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
func (r Role) InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error) {
|
||||
ctx = sql_metrics.OperationLabelToContext(ctx, "Role.InsertRole")
|
||||
|
||||
q, args, err := query.New().Insert("roles").
|
||||
Columns("name", "permissions", "external_group").
|
||||
Values(role.Name, role.Permissions, role.ExternalGroup).
|
||||
Columns("name", "permissions", "external_group", "application_group").
|
||||
Values(role.Name, role.Permissions, role.ExternalGroup, role.ApplicationGroup).
|
||||
Suffix("RETURNING *").ToSql()
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "build query")
|
||||
@@ -158,6 +173,7 @@ func (r Role) Update(ctx context.Context, role entity.Role) (*entity.Role, error
|
||||
Set("name", role.Name).
|
||||
Set("permissions", role.Permissions).
|
||||
Set("external_group", role.ExternalGroup).
|
||||
Set("application_group", role.ApplicationGroup).
|
||||
Where(squirrel.Eq{"id": role.Id}).
|
||||
Suffix("RETURNING *").ToSql()
|
||||
if err != nil {
|
||||
|
||||
+46
-29
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
type roleRoleRepo interface {
|
||||
All(ctx context.Context) ([]entity.Role, error)
|
||||
AllWithFilter(ctx context.Context, applicationGroup string) ([]entity.Role, error)
|
||||
InsertRole(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Update(ctx context.Context, role entity.Role) (*entity.Role, error)
|
||||
Delete(ctx context.Context, id int) error
|
||||
@@ -32,8 +33,17 @@ func NewRole(roleRepo roleRoleRepo, audit auditService) Role {
|
||||
}
|
||||
}
|
||||
|
||||
func (u Role) All(ctx context.Context) ([]domain.Role, error) {
|
||||
roles, err := u.roleRepo.All(ctx)
|
||||
func (u Role) All(ctx context.Context, req domain.RoleAllRequest) ([]domain.Role, error) {
|
||||
var (
|
||||
roles []entity.Role
|
||||
err error
|
||||
)
|
||||
switch {
|
||||
case req.ApplicationGroup != nil:
|
||||
roles, err = u.roleRepo.AllWithFilter(ctx, *req.ApplicationGroup)
|
||||
default:
|
||||
roles, err = u.roleRepo.All(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, errors.WithMessage(err, "get all roles")
|
||||
}
|
||||
@@ -58,9 +68,10 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
||||
}
|
||||
|
||||
role, err = u.roleRepo.InsertRole(ctx, entity.Role{
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
Permissions: req.Permissions,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ApplicationGroup: req.ApplicationGroup,
|
||||
Permissions: req.Permissions,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -69,13 +80,15 @@ func (u Role) Create(ctx context.Context, req domain.CreateRoleRequest, adminId
|
||||
|
||||
slices.Sort(role.Permissions)
|
||||
diff := diffToString(map[string]any{
|
||||
"Название": "",
|
||||
"Группа ЕСК": "",
|
||||
"Разрешения": []int{},
|
||||
"Название": "",
|
||||
"Группа ЕСК": "",
|
||||
"Группа приложений": "",
|
||||
"Разрешения": []int{},
|
||||
}, map[string]any{
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Группа приложений": role.ApplicationGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
})
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
fmt.Sprintf("Роль. Создание новой роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
|
||||
@@ -106,10 +119,11 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
||||
oldRole := roles[0]
|
||||
|
||||
role, err := u.roleRepo.Update(ctx, entity.Role{
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
Permissions: req.Permissions,
|
||||
Id: req.Id,
|
||||
Name: req.Name,
|
||||
ExternalGroup: req.ExternalGroup,
|
||||
ApplicationGroup: req.ApplicationGroup,
|
||||
Permissions: req.Permissions,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
@@ -119,13 +133,15 @@ func (u Role) Update(ctx context.Context, req domain.UpdateRoleRequest, adminId
|
||||
slices.Sort(oldRole.Permissions)
|
||||
slices.Sort(role.Permissions)
|
||||
diff := diffToString(map[string]any{
|
||||
"Название": oldRole.Name,
|
||||
"Группа ЕСК": oldRole.ExternalGroup,
|
||||
"Разрешения": oldRole.Permissions,
|
||||
"Название": oldRole.Name,
|
||||
"Группа ЕСК": oldRole.ExternalGroup,
|
||||
"Группа приложений": oldRole.ApplicationGroup,
|
||||
"Разрешения": oldRole.Permissions,
|
||||
}, map[string]any{
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
"Название": role.Name,
|
||||
"Группа ЕСК": role.ExternalGroup,
|
||||
"Группа приложений": role.ApplicationGroup,
|
||||
"Разрешения": role.Permissions,
|
||||
})
|
||||
u.auditService.SaveAuditAsync(ctx, adminId,
|
||||
fmt.Sprintf("Роль. Изменение роли %s. Причина: %s. \n %s", req.Name, req.ChangeMessage, diff),
|
||||
@@ -148,13 +164,14 @@ func (u Role) Delete(ctx context.Context, req domain.DeleteRoleRequest, adminId
|
||||
|
||||
func (u Role) toDomain(role entity.Role) domain.Role {
|
||||
return domain.Role{
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
ExternalGroup: role.ExternalGroup,
|
||||
Permissions: role.Permissions,
|
||||
Immutable: role.Immutable,
|
||||
Exclusive: role.Exclusive,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
Id: role.Id,
|
||||
Name: role.Name,
|
||||
ExternalGroup: role.ExternalGroup,
|
||||
ApplicationGroup: role.ApplicationGroup,
|
||||
Permissions: role.Permissions,
|
||||
Immutable: role.Immutable,
|
||||
Exclusive: role.Exclusive,
|
||||
CreatedAt: role.CreatedAt,
|
||||
UpdatedAt: role.UpdatedAt,
|
||||
}
|
||||
}
|
||||
+2
-4
@@ -183,10 +183,8 @@ func (s *AuditSuite) Test_SetEvents_InvalidEvent() {
|
||||
|
||||
func (s *AuditSuite) Test_All_Logs() {
|
||||
request := domain.AuditPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 3,
|
||||
Offset: 5,
|
||||
},
|
||||
Limit: 3,
|
||||
Offset: 5,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "user_id",
|
||||
Type: "desc",
|
||||
|
||||
+2
-4
@@ -241,10 +241,8 @@ func (s *AuthTestSuite) Test_Logout_NotFound() {
|
||||
time.Sleep(time.Second)
|
||||
audit := repository.NewAudit(s.db)
|
||||
auditList, err := audit.AllByRequest(s.T().Context(), domain.AuditPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "created_at",
|
||||
Type: "desc",
|
||||
|
||||
@@ -42,9 +42,13 @@ func InsertRole(db *dbt.TestDb, role entity.Role) int64 {
|
||||
}
|
||||
q, args, err := query.New().
|
||||
Insert("roles").
|
||||
Columns("name", "permissions").
|
||||
Values(role.Name, role.Permissions).
|
||||
Suffix("ON CONFLICT (name) DO UPDATE SET name = EXCLUDED.name, permissions = EXCLUDED.permissions RETURNING id").
|
||||
Columns("name", "permissions", "application_group").
|
||||
Values(role.Name, role.Permissions, role.ApplicationGroup).
|
||||
Suffix(`ON CONFLICT (name) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
permissions = EXCLUDED.permissions,
|
||||
application_group = EXCLUDED.application_group
|
||||
RETURNING id`).
|
||||
ToSql()
|
||||
if err != nil {
|
||||
panic(errors.WithMessagef(err, "insert role"))
|
||||
|
||||
@@ -49,10 +49,8 @@ func TestInactiveWorker(t *testing.T) {
|
||||
require.True(user.Blocked)
|
||||
|
||||
list, err := repository.NewAudit(db).AllByRequest(t.Context(), domain.AuditPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "created_at",
|
||||
Type: "desc",
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package tests_test
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-admin-service/assembly"
|
||||
"isp-admin-service/conf"
|
||||
"isp-admin-service/domain"
|
||||
"isp-admin-service/entity"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/dbx"
|
||||
"github.com/txix-open/isp-kit/errors"
|
||||
"github.com/txix-open/isp-kit/grpc/client"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/dbt"
|
||||
"github.com/txix-open/isp-kit/test/grpct"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
func TestRoleTestSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, &RoleTestSuite{})
|
||||
}
|
||||
|
||||
type RoleTestSuite struct {
|
||||
suite.Suite
|
||||
|
||||
test *test.Test
|
||||
db *dbt.TestDb
|
||||
grpcCli *client.Client
|
||||
adminId int64
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) SetupTest() {
|
||||
testInstance, _ := test.New(s.T())
|
||||
s.test = testInstance
|
||||
s.db = dbt.New(testInstance, dbx.WithMigrationRunner("../migrations", testInstance.Logger()))
|
||||
|
||||
remote := conf.Remote{
|
||||
ExpireSec: 0,
|
||||
}
|
||||
cfg, err := assembly.NewLocator(testInstance.Logger(), httpcli.New(), s.db).
|
||||
Config(s.T().Context(), remote, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
|
||||
server, apiCli := grpct.TestServer(testInstance, cfg.Handler)
|
||||
s.grpcCli = apiCli
|
||||
|
||||
testInstance.T().Cleanup(func() {
|
||||
server.Shutdown()
|
||||
})
|
||||
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
Name: "admin_test",
|
||||
Permissions: []string{
|
||||
"role_view",
|
||||
"role_add",
|
||||
"role_update",
|
||||
},
|
||||
})
|
||||
s.adminId = InsertUser(s.db, entity.User{
|
||||
Email: "admin@test.ru",
|
||||
})
|
||||
InsertUserRole(s.db, entity.UserRole{
|
||||
UserId: int(s.adminId),
|
||||
RoleId: int(roleId),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesWithoutFilter() {
|
||||
InsertRole(s.db, entity.Role{Name: "empty"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupA_1", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupA_2", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{}, &roles))
|
||||
|
||||
groups := make(map[string]string, len(roles))
|
||||
for _, role := range roles {
|
||||
groups[role.Name] = role.ApplicationGroup
|
||||
}
|
||||
|
||||
s.Require().Empty(groups["empty"])
|
||||
s.Require().Equal("groupA", groups["groupA_1"])
|
||||
s.Require().Equal("groupA", groups["groupA_2"])
|
||||
s.Require().Equal("groupB", groups["groupB"])
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesInvalidArgument() {
|
||||
roles := []domain.Role{}
|
||||
err := s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("")}, &roles)
|
||||
|
||||
s.Require().Error(err)
|
||||
st, ok := status.FromError(err)
|
||||
s.Require().True(ok)
|
||||
s.Require().Equal(codes.InvalidArgument, st.Code())
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestAllRolesFilterByApplicationGroup() {
|
||||
InsertRole(s.db, entity.Role{Name: "groupA", ApplicationGroup: "groupA"})
|
||||
InsertRole(s.db, entity.Role{Name: "groupB", ApplicationGroup: "groupB"})
|
||||
|
||||
roles := []domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupA")}, &roles))
|
||||
|
||||
s.Require().Len(roles, 1)
|
||||
s.Require().Equal("groupA", roles[0].ApplicationGroup)
|
||||
|
||||
roles = []domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/all", domain.RoleAllRequest{ApplicationGroup: new("groupC")}, &roles))
|
||||
|
||||
s.Require().Empty(roles)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestCreateRoleApplicationGroup() {
|
||||
role := domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group",
|
||||
Permissions: []string{},
|
||||
}, &role))
|
||||
|
||||
roleEmpty := domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/create", domain.CreateRoleRequest{
|
||||
Name: "role_empty",
|
||||
Permissions: []string{},
|
||||
}, &roleEmpty))
|
||||
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group", role.ApplicationGroup)
|
||||
s.Require().Equal("role_empty", roleEmpty.Name)
|
||||
s.Require().Empty(roleEmpty.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) TestUpdateRoleApplicationGroup() {
|
||||
roleId := InsertRole(s.db, entity.Role{
|
||||
Name: "role_old",
|
||||
ApplicationGroup: "group_old",
|
||||
})
|
||||
|
||||
role := domain.Role{}
|
||||
s.Require().NoError(s.invoke("admin/role/update", domain.UpdateRoleRequest{
|
||||
Id: int(roleId),
|
||||
Name: "role_new",
|
||||
ApplicationGroup: "group_new",
|
||||
Permissions: []string{},
|
||||
}, &role))
|
||||
|
||||
s.Require().Equal("role_new", role.Name)
|
||||
s.Require().Equal("group_new", role.ApplicationGroup)
|
||||
}
|
||||
|
||||
func (s *RoleTestSuite) invoke(path string, req, resp any) error {
|
||||
err := s.grpcCli.Invoke(path).
|
||||
JsonRequestBody(req).
|
||||
JsonResponseBody(resp).
|
||||
AppendMetadata(domain.AdminAuthIdHeader, strconv.Itoa(int(s.adminId))).
|
||||
Do(s.T().Context())
|
||||
if err != nil {
|
||||
return errors.WithMessagef(err, "invoke %s", path)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -117,10 +117,8 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
|
||||
// Дефолт сортировка, лимит и оффсет
|
||||
request := domain.SessionPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
}
|
||||
|
||||
var response *domain.SessionResponse
|
||||
@@ -208,10 +206,8 @@ func (s *SessionSuite) Test_All_Session() {
|
||||
}
|
||||
|
||||
request = domain.SessionPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "desc",
|
||||
|
||||
+8
-16
@@ -186,10 +186,8 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 1,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "email",
|
||||
Type: "asc",
|
||||
@@ -214,10 +212,8 @@ func (s *UserTestSuite) TestGetUsers() {
|
||||
email = "test@mail.ru"
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "id",
|
||||
Type: "asc",
|
||||
@@ -298,10 +294,8 @@ func (s *UserTestSuite) TestGetUsersFilterByLastActiveAt() {
|
||||
response := domain.UsersResponse{}
|
||||
err = s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 5,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "lastSessionCreatedAt",
|
||||
Type: "desc",
|
||||
@@ -334,10 +328,8 @@ func (s *UserTestSuite) TestGetUsersSortByName() {
|
||||
response := domain.UsersResponse{}
|
||||
err := s.grpcCli.Invoke("admin/user/get_users").
|
||||
JsonRequestBody(domain.UsersPageRequest{
|
||||
LimitOffestParams: domain.LimitOffestParams{
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
},
|
||||
Limit: 10,
|
||||
Offset: 0,
|
||||
Order: &domain.OrderParams{
|
||||
Field: "userId",
|
||||
Type: "asc",
|
||||
|
||||
+3
@@ -13,6 +13,9 @@
|
||||
<a href="https://pkg.go.dev/github.com/gabriel-vasile/mimetype">
|
||||
<img alt="Go Reference" src="https://pkg.go.dev/badge/github.com/gabriel-vasile/mimetype.svg">
|
||||
</a>
|
||||
<a href="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml">
|
||||
<img alt="Tests" src="https://github.com/gabriel-vasile/mimetype/actions/workflows/go.yml/badge.svg">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/gabriel-vasile/mimetype">
|
||||
<img alt="Code coverage" src="https://codecov.io/gh/gabriel-vasile/mimetype/graph/badge.svg">
|
||||
</a>
|
||||
|
||||
+142
-29
@@ -46,12 +46,14 @@ type cdf struct {
|
||||
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
|
||||
ssatSecs int32s // list of SSAT sector ids, precomputed from the firstSSAT chain
|
||||
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
|
||||
rootChild int32 // directory id of the root storage's child tree
|
||||
rootStorageUUID [16]byte
|
||||
}
|
||||
|
||||
// parse reads the entire on-disk structure required for type detection. It
|
||||
@@ -81,35 +83,108 @@ func parse(raw []byte, c *cdf) bool {
|
||||
masterSAT := int32s{b: raw[76 : 76+4*masterSATSize]}
|
||||
|
||||
c.buildSAT(masterSAT, firstMSAT, nMSAT)
|
||||
c.buildSSAT()
|
||||
c.dirRaw = c.readLong(firstDirSec, 0)
|
||||
|
||||
c.rootStreamFirst = -1
|
||||
c.rootChild = -1
|
||||
var d dirEntry
|
||||
for i, n := 0, c.dirLen(); i < n; i++ {
|
||||
c.dirAt(i, &d)
|
||||
if d.typ != dirTypeRootStorage || d.streamFirst < 0 {
|
||||
if d.typ != dirTypeRootStorage {
|
||||
continue
|
||||
}
|
||||
c.rootStorageUUID = d.storageUUID[:]
|
||||
copy(c.rootStorageUUID[:], d.storageUUID[:])
|
||||
c.rootChild = d.child
|
||||
// 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
|
||||
if d.streamFirst >= 0 {
|
||||
c.rootStreamFirst = d.streamFirst
|
||||
c.rootStreamSize = d.size
|
||||
}
|
||||
break
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// rootChildIter iterates over the directory entries that are direct children
|
||||
// of the root storage, walking the red-black sibling tree hanging off the root
|
||||
// entry's child pointer. Restricting detection to root-level entries matters:
|
||||
// embedded OLE objects (e.g. an Excel sheet inside a Word document) carry
|
||||
// their own SummaryInformation streams deeper in the hierarchy, and a flat
|
||||
// directory scan can pick those up instead of the document's own.
|
||||
// If the tree is unusable (no valid root child) iteration degrades to a flat
|
||||
// scan of all entries so truncated or malformed files still get best-effort
|
||||
// detection. The iterator lives entirely on the caller's stack: it allocates
|
||||
// nothing and decodes each visited entry into its inline d field.
|
||||
type rootChildIter struct {
|
||||
c *cdf
|
||||
d dirEntry // entry decoded by the latest successful next call
|
||||
n int // total directory entries
|
||||
i int // next index for the flat fallback scan
|
||||
flat bool // no usable tree; scan all entries instead
|
||||
visited int // entries visited so far; guards against cyclic trees
|
||||
sp int // number of ids on stack
|
||||
stack [64]int32
|
||||
}
|
||||
|
||||
// rootChildren returns an iterator over the root storage's direct children.
|
||||
// Usage: for it := c.rootChildren(); it.next(); { ... use it.d ... }
|
||||
func (c *cdf) rootChildren() rootChildIter {
|
||||
it := rootChildIter{c: c, n: c.dirLen()}
|
||||
if c.rootChild >= 0 && int(c.rootChild) < it.n {
|
||||
it.stack[0] = c.rootChild
|
||||
it.sp = 1
|
||||
} else {
|
||||
it.flat = true
|
||||
}
|
||||
return it
|
||||
}
|
||||
|
||||
// next advances to the next entry, decoding it into it.d. It reports false
|
||||
// when iteration is done.
|
||||
func (it *rootChildIter) next() bool {
|
||||
if it.flat {
|
||||
if it.i >= it.n {
|
||||
return false
|
||||
}
|
||||
it.c.dirAt(it.i, &it.d)
|
||||
it.i++
|
||||
return true
|
||||
}
|
||||
for it.sp > 0 {
|
||||
it.sp--
|
||||
id := it.stack[it.sp]
|
||||
if id < 0 || int(id) >= it.n {
|
||||
continue
|
||||
}
|
||||
if it.visited++; it.visited > it.n {
|
||||
return false // cyclic sibling pointers in a malformed directory
|
||||
}
|
||||
it.c.dirAt(int(id), &it.d)
|
||||
// Push the siblings. A valid red-black tree of n entries is at most
|
||||
// 2*log2(n) deep, so the fixed-size stack cannot overflow for any
|
||||
// real directory; if a malformed tree overflows it, the excess
|
||||
// branches are dropped and detection degrades gracefully.
|
||||
for _, sib := range [2]int32{it.d.left, it.d.right} {
|
||||
if sib >= 0 && it.sp < len(it.stack) {
|
||||
it.stack[it.sp] = sib
|
||||
it.sp++
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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 {
|
||||
for it := c.rootChildren(); it.next(); {
|
||||
if t, ok := lookupSection(it.d.nameBytes(), it.d.typ); ok {
|
||||
return t
|
||||
}
|
||||
}
|
||||
@@ -120,7 +195,7 @@ func (c *cdf) detect() CDFType {
|
||||
// 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) {
|
||||
if bytes.Equal(c.rootStorageUUID[:], msiCLSID) {
|
||||
return CDFTypeInstaller, true
|
||||
}
|
||||
raw, ok := c.userStream(streamName)
|
||||
@@ -132,13 +207,11 @@ func (c *cdf) detectFromSummary(streamName string) (CDFType, bool) {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
for i, n := 0, c.dirLen(); i < n; i++ {
|
||||
var d dirEntry
|
||||
c.dirAt(i, &d)
|
||||
if d.nameLen == 0 {
|
||||
for it := c.rootChildren(); it.next(); {
|
||||
if it.d.nameLen == 0 {
|
||||
continue
|
||||
}
|
||||
if t, ok := lookupSubstring(d.nameBytes(), name2type); ok {
|
||||
if t, ok := lookupSubstring(it.d.nameBytes(), name2type); ok {
|
||||
return t, true
|
||||
}
|
||||
}
|
||||
@@ -164,6 +237,9 @@ type dirEntry struct {
|
||||
name [32]byte
|
||||
nameLen uint8
|
||||
typ uint8
|
||||
left int32 // left sibling directory id
|
||||
right int32 // right sibling directory id
|
||||
child int32 // first child directory id (for storages)
|
||||
streamFirst int32
|
||||
size uint32
|
||||
storageUUID [16]byte
|
||||
@@ -172,23 +248,56 @@ type dirEntry struct {
|
||||
// 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 {
|
||||
// buildSSAT records the list of SSAT sector ids by walking the firstSSAT chain
|
||||
// through the SAT once. The SSAT contents are not materialized; ssatAt computes
|
||||
// the requested entry directly from c.data via ssatSecs, mirroring satSecs/satAt.
|
||||
// The walk is bounded by the number of sectors in the file so a cyclic SAT
|
||||
// (a self-looping sector) cannot spin forever.
|
||||
func (c *cdf) buildSSAT() {
|
||||
maxIDs := len(c.data)/c.secSize + 1
|
||||
buf := make([]byte, 0, 4*8)
|
||||
var tmp [4]byte
|
||||
for sid := c.firstSSAT; sid >= 0; {
|
||||
if int(sid) >= c.satLen() {
|
||||
break // SAT is truncated; stop collecting
|
||||
}
|
||||
buf, ok := c.sector(sid)
|
||||
if !ok {
|
||||
if _, ok := c.sector(sid); !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
|
||||
binary.LittleEndian.PutUint32(tmp[:], uint32(sid)) //nolint:gosec // reinterpret sector id
|
||||
buf = append(buf, tmp[:]...)
|
||||
if len(buf)/4 > maxIDs {
|
||||
break // cyclic SAT chain; stop allocating
|
||||
}
|
||||
i -= lbuf
|
||||
sid = c.satAt(sid)
|
||||
}
|
||||
return -1
|
||||
c.ssatSecs = int32s{b: buf}
|
||||
}
|
||||
|
||||
// ssatAt returns the i-th SSAT entry (a short-sector id) by indexing directly
|
||||
// into the precomputed ssatSecs, the same way satAt indexes satSecs. It returns
|
||||
// -1 when i is past the end of the SSAT or the backing sector is truncated.
|
||||
func (c *cdf) ssatAt(i int32) int32 {
|
||||
if i < 0 {
|
||||
return -1
|
||||
}
|
||||
perSec := int32(c.secSize / 4) //nolint:gosec // secSize is a small power of two
|
||||
secIdx := int(i / perSec)
|
||||
if secIdx >= c.ssatSecs.len() {
|
||||
return -1
|
||||
}
|
||||
sid := c.ssatSecs.at(secIdx)
|
||||
buf, ok := c.sector(sid)
|
||||
if !ok {
|
||||
return -1
|
||||
}
|
||||
entryIdx := i % perSec
|
||||
//nolint:gosec // anything divided by 4 fits int32
|
||||
if entryIdx >= int32(len(buf)/4) {
|
||||
return -1 // sector truncated short of this entry
|
||||
}
|
||||
//nolint:gosec // intentional two's-complement reinterpretation of a sector id
|
||||
return int32(binary.LittleEndian.Uint32(buf[4*entryIdx:]))
|
||||
}
|
||||
|
||||
// shortStream returns the root storage short-stream pool, loading it on first
|
||||
@@ -435,6 +544,9 @@ func (c *cdf) readShort(sid int32, length uint32) []byte {
|
||||
}
|
||||
off := int(off64)
|
||||
out = append(out, sst[off:off+c.shortSecSize]...)
|
||||
if length > 0 && int64(len(out)) >= int64(length) {
|
||||
break // read enough to satisfy the stream's declared length
|
||||
}
|
||||
if len(out) >= len(sst) {
|
||||
break // chain longer than the pool: cyclic SSAT, stop
|
||||
}
|
||||
@@ -476,18 +588,19 @@ func (c *cdf) dirAt(i int, out *dirEntry) {
|
||||
}
|
||||
out.nameLen = k
|
||||
out.typ = raw[66]
|
||||
out.left = readSecID(raw[68:72])
|
||||
out.right = readSecID(raw[72:76])
|
||||
out.child = readSecID(raw[76:80])
|
||||
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.
|
||||
// userStream finds a root-level 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)
|
||||
for it := c.rootChildren(); it.next(); {
|
||||
if it.d.typ == dirTypeUserStream && string(it.d.nameBytes()) == name {
|
||||
buf := c.readChain(it.d.streamFirst, it.d.size)
|
||||
if buf == nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
+15
-12
@@ -50,7 +50,7 @@ func M3U(raw []byte, _ uint32) bool {
|
||||
|
||||
// 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))
|
||||
return len(raw) > 1 && raw[0] == 0xFF && (raw[1] == 0xF1 || raw[1] == 0xF9)
|
||||
}
|
||||
|
||||
// MP3 matches a .mp3 file.
|
||||
@@ -128,27 +128,30 @@ func id3v2(raw []byte) bool {
|
||||
}
|
||||
|
||||
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
|
||||
// The synchsafe integer is already bounded to 28 bits (~256MB). A 10MB
|
||||
// cap rejected legitimate files with large ID3v2 album art. #839
|
||||
return size > 0
|
||||
}
|
||||
|
||||
// iff checks for an Interchange File Format layout: 4-byte container tag,
|
||||
// 4-byte size, 4-byte format tag.
|
||||
func iff(raw []byte, container, format []byte) bool {
|
||||
return len(raw) > 12 &&
|
||||
bytes.Equal(raw[:4], container) &&
|
||||
bytes.Equal(raw[8:12], format)
|
||||
}
|
||||
|
||||
// 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})
|
||||
return iff(raw, []byte("RIFF"), []byte("WAVE"))
|
||||
}
|
||||
|
||||
// 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})
|
||||
return iff(raw, []byte("FORM"), []byte("AIFF"))
|
||||
}
|
||||
|
||||
// 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"))
|
||||
return iff(raw, []byte("RIFF"), []byte("QLCM"))
|
||||
}
|
||||
+9
-16
@@ -121,29 +121,22 @@ func Dbf(raw []byte, limit uint32) bool {
|
||||
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))
|
||||
func elfType(raw []byte, t byte) bool {
|
||||
return len(raw) > 17 &&
|
||||
((raw[16] == t && raw[17] == 0x00) || (raw[16] == 0x00 && raw[17] == t))
|
||||
}
|
||||
|
||||
// ElfObj matches an object file.
|
||||
func ElfObj(raw []byte, limit uint32) bool { return elfType(raw, 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))
|
||||
}
|
||||
func ElfExe(raw []byte, limit uint32) bool { return elfType(raw, 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))
|
||||
}
|
||||
func ElfLib(raw []byte, limit uint32) bool { return elfType(raw, 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))
|
||||
}
|
||||
func ElfDump(raw []byte, limit uint32) bool { return elfType(raw, 0x04) }
|
||||
|
||||
// Dcm matches a DICOM medical format file.
|
||||
func Dcm(raw []byte, limit uint32) bool {
|
||||
|
||||
+1
-3
@@ -178,9 +178,7 @@ func jpeg2k(raw []byte, sig []byte) bool {
|
||||
|
||||
// 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})
|
||||
return iff(raw, []byte("RIFF"), []byte("WEBP"))
|
||||
}
|
||||
|
||||
// Dwg matches a CAD drawing file.
|
||||
|
||||
+1
-13
@@ -101,25 +101,13 @@ func markup(b scan.Bytes, sigs ...[]byte) bool {
|
||||
return false
|
||||
}
|
||||
func markupCheck(sig, raw []byte) bool {
|
||||
if len(raw) < len(sig)+1 {
|
||||
if !ciCheck(sig, raw) {
|
||||
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
|
||||
}
|
||||
|
||||
|
||||
+31
-59
@@ -46,26 +46,16 @@ 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 {
|
||||
// cdfOrClsid checks if the raw input is detected as the given CDF type, and if
|
||||
// the CDF parser returns a generic result, falls back to matching root storage CLSIDs.
|
||||
func cdfOrClsid(raw []byte, want cdf.CDFType, clsids ...[]byte) bool {
|
||||
fromParsing := cdf.Detect(raw)
|
||||
if fromParsing == cdf.CDFTypeDoc {
|
||||
if fromParsing == want {
|
||||
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
|
||||
@@ -74,25 +64,27 @@ func Doc(raw []byte, _ uint32) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return cdfOrClsid(raw, cdf.CDFTypeDoc,
|
||||
// Microsoft Word 97-2003 Document (Word.Document.8)
|
||||
[]byte{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)
|
||||
[]byte{0x00, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
// Microsoft Word Picture (Word.Picture.8)
|
||||
[]byte{0x07, 0x09, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
)
|
||||
}
|
||||
|
||||
// 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,
|
||||
}) {
|
||||
if cdfOrClsid(raw, cdf.CDFTypePpt,
|
||||
[]byte{0x10, 0x8d, 0x81, 0x64, 0x9b, 0x4f, 0xcf, 0x11,
|
||||
0x86, 0xea, 0x00, 0xaa, 0x00, 0xb9, 0x29, 0xe8},
|
||||
[]byte{0x70, 0xae, 0x7b, 0xea, 0x3b, 0xfb, 0xcd, 0x11,
|
||||
0xa9, 0x03, 0x00, 0xaa, 0x00, 0x51, 0x0e, 0xa3},
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -117,21 +109,10 @@ func Ppt(raw []byte, limit uint32) bool {
|
||||
|
||||
// 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,
|
||||
}) {
|
||||
if cdfOrClsid(raw, cdf.CDFTypeXls,
|
||||
[]byte{0x10, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
|
||||
[]byte{0x20, 0x08, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00},
|
||||
) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -168,19 +149,10 @@ func Pub(raw []byte, limit uint32) bool {
|
||||
|
||||
// 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,
|
||||
})
|
||||
return cdfOrClsid(raw, cdf.CDFTypeMsg,
|
||||
[]byte{0x0B, 0x0D, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46},
|
||||
)
|
||||
}
|
||||
|
||||
// Msi matches a Microsoft Windows Installer file.
|
||||
|
||||
+3
@@ -15,6 +15,9 @@ targets:
|
||||
- name: github
|
||||
tagPrefix: otel/otlp/v
|
||||
tagOnly: true
|
||||
- name: github
|
||||
tagPrefix: cron/v
|
||||
tagOnly: true
|
||||
- name: github
|
||||
tagPrefix: echo/v
|
||||
tagOnly: true
|
||||
|
||||
+35
@@ -1,5 +1,40 @@
|
||||
# Changelog
|
||||
|
||||
## 0.50.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
- adds NoopClient implementation. The SDK now returns a non-nil noop client and handles the previous nil checks with checking for a disabled client. Code paths that were using nil checks now need to check for `client.IsEnabled`. by @giortzisg in [#1365](https://github.com/getsentry/sentry-go/pull/1365)
|
||||
|
||||
### New Features ✨
|
||||
|
||||
#### Crons
|
||||
|
||||
- Add `sentry.WithMonitor` and `Hub.WithMonitor` to wrap a job in cron check-ins and create or update the monitor from code. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
|
||||
- Add `sentrycron.AddFunc` to report robfig/cron jobs to Sentry Crons, using the job's spec as the monitor schedule. by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
|
||||
- Docs: https://github.com/getsentry/sentry-docs/pull/19778 by @wedamija in [#1443](https://github.com/getsentry/sentry-go/pull/1443)
|
||||
|
||||
### Bug Fixes 🐛
|
||||
|
||||
- (dsn) Build envelope URL without re-parsing by @giortzisg in [#1436](https://github.com/getsentry/sentry-go/pull/1436)
|
||||
- (httpclient) Decouple span creation from trace propagation by @giortzisg in [#1421](https://github.com/getsentry/sentry-go/pull/1421)
|
||||
- (slog) Stop replaceAttrs from mutating the handler's grouped attrs by @breken-ai in [#1439](https://github.com/getsentry/sentry-go/pull/1439)
|
||||
- (zerolog) Unescape JSON string values before sending to Sentry by @breken-ai in [#1440](https://github.com/getsentry/sentry-go/pull/1440)
|
||||
- Guard concurrent flushes by @giortzisg in [#1449](https://github.com/getsentry/sentry-go/pull/1449)
|
||||
- Keep http.Hijacker when wrapping a response writer by @knQzx in [#1387](https://github.com/getsentry/sentry-go/pull/1387)
|
||||
|
||||
### Internal Changes 🔧
|
||||
|
||||
#### Deps
|
||||
|
||||
- Bump getsentry/craft from 2.30.1 to 2.31.2 by @dependabot in [#1441](https://github.com/getsentry/sentry-go/pull/1441)
|
||||
- Bump getsentry/github-workflows/validate-pr from 4013fc6e1aeb1be1f9d3b4d232624f0ec1afa613 to 36c729264d2edc29ebae61950c50e1e9f043ad7e by @dependabot in [#1442](https://github.com/getsentry/sentry-go/pull/1442)
|
||||
- Bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.43.0 to 1.45.0 in /otel/otlp by @dependabot in [#1430](https://github.com/getsentry/sentry-go/pull/1430)
|
||||
- Bump go.opentelemetry.io/otel/sdk from 1.44.0 to 1.45.0 by @dependabot in [#1431](https://github.com/getsentry/sentry-go/pull/1431)
|
||||
- Bump google.golang.org/grpc from 1.83.1 to 1.83.2 by @dependabot in [#1422](https://github.com/getsentry/sentry-go/pull/1422)
|
||||
- Bump getsentry/craft from 2.27.2 to 2.30.1 by @dependabot in [#1411](https://github.com/getsentry/sentry-go/pull/1411)
|
||||
- Bump google.golang.org/grpc from 1.82.1 to 1.83.1 by @dependabot in [#1413](https://github.com/getsentry/sentry-go/pull/1413)
|
||||
|
||||
## 0.49.0
|
||||
|
||||
### Breaking Changes 🛠
|
||||
|
||||
+6
-4
@@ -305,6 +305,8 @@ func (t Type) String() string {
|
||||
return "invalid"
|
||||
}
|
||||
|
||||
const arrayType = "array"
|
||||
|
||||
// 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{
|
||||
@@ -313,9 +315,9 @@ var mapTypesToStr = map[Type]string{
|
||||
INT64: "integer",
|
||||
FLOAT64: "double",
|
||||
STRING: "string",
|
||||
BOOLSLICE: "array",
|
||||
INT64SLICE: "array",
|
||||
FLOAT64SLICE: "array",
|
||||
STRINGSLICE: "array",
|
||||
BOOLSLICE: arrayType,
|
||||
INT64SLICE: arrayType,
|
||||
FLOAT64SLICE: arrayType,
|
||||
STRINGSLICE: arrayType,
|
||||
UINT64: "integer", // wire format: same "integer" type
|
||||
}
|
||||
+85
-9
@@ -133,8 +133,8 @@ 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.
|
||||
// In debug mode, diagnostic information is written to DebugWriter, which
|
||||
// defaults to stderr.
|
||||
Debug bool
|
||||
// Configures whether SDK should generate and attach stacktraces to pure
|
||||
// capture message calls.
|
||||
@@ -298,6 +298,7 @@ type ClientOptions struct {
|
||||
// instances. It must be created with NewClient.
|
||||
type Client struct {
|
||||
mu sync.RWMutex
|
||||
disabled bool
|
||||
options ClientOptions
|
||||
dsn *protocol.Dsn
|
||||
eventProcessors []EventProcessor
|
||||
@@ -450,6 +451,45 @@ func NewClient(options ClientOptions) (*Client, error) {
|
||||
return &client, nil
|
||||
}
|
||||
|
||||
var noopClient = &Client{
|
||||
disabled: true,
|
||||
options: ClientOptions{
|
||||
DisableTelemetryBuffer: true,
|
||||
MaxErrorDepth: maxErrorDepth,
|
||||
MaxSpans: defaultMaxSpans,
|
||||
TraceIgnoreStatusCodes: [][]int{{404}},
|
||||
},
|
||||
sdkIdentifier: sdkIdentifier,
|
||||
sdkVersion: SDKVersion,
|
||||
Transport: new(noopTransport),
|
||||
reportRecorder: report.NoopRecorder(),
|
||||
reportProvider: report.NoopProvider(),
|
||||
}
|
||||
|
||||
// NewNoopClient returns the shared client that safely discards telemetry.
|
||||
// Its mutating methods have no effect.
|
||||
func NewNoopClient() *Client {
|
||||
return noopClient
|
||||
}
|
||||
|
||||
// IsEnabled reports whether the client processes captured telemetry.
|
||||
//
|
||||
// It returns false for a nil receiver and for clients returned by
|
||||
// NewNoopClient. A client can be enabled while using a transport that discards
|
||||
// telemetry, such as a client configured with an empty DSN.
|
||||
func (client *Client) IsEnabled() bool {
|
||||
return client != nil && !client.disabled
|
||||
}
|
||||
|
||||
// normalizeClient returns client, or the shared no-op client when client is
|
||||
// nil.
|
||||
func normalizeClient(client *Client) *Client {
|
||||
if client == nil {
|
||||
return noopClient
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func (client *Client) setupTransport() {
|
||||
opts := client.options
|
||||
transport := opts.Transport
|
||||
@@ -555,6 +595,9 @@ func (client *Client) setupIntegrations() {
|
||||
// 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) {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
client.eventProcessors = append(client.eventProcessors, processor)
|
||||
}
|
||||
|
||||
@@ -563,6 +606,9 @@ func (client *Client) AddEventProcessor(processor EventProcessor) {
|
||||
//
|
||||
// This is intended for integrations such as OpenTelemetry.
|
||||
func (client *Client) SetExternalContextTraceResolver(resolver func(ctx context.Context) (TraceID, SpanID, bool)) {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
|
||||
@@ -596,7 +642,7 @@ func (client *Client) Options() ClientOptions {
|
||||
// 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 {
|
||||
if !client.IsEnabled() || client.options.DataCollection == nil {
|
||||
return DataCollection{}
|
||||
}
|
||||
return *cloneDataCollection(client.options.DataCollection)
|
||||
@@ -604,22 +650,32 @@ func (client *Client) GetDataCollection() DataCollection {
|
||||
|
||||
// CaptureMessage captures an arbitrary message.
|
||||
func (client *Client) CaptureMessage(message string, hint *EventHint, scope EventModifier) *EventID {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
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 {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
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 {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
event := client.EventFromCheckIn(checkIn, monitorConfig)
|
||||
if event != nil && event.CheckIn != nil {
|
||||
client.CaptureEvent(event, nil, scope)
|
||||
return &event.CheckIn.ID
|
||||
if client.CaptureEvent(event, nil, scope) != nil {
|
||||
return &event.CheckIn.ID
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -630,6 +686,9 @@ func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorCon
|
||||
// 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 {
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
return client.processEvent(event, hint, scope)
|
||||
}
|
||||
|
||||
@@ -727,6 +786,9 @@ func (client *Client) RecoverWithContext(
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !client.IsEnabled() {
|
||||
return nil
|
||||
}
|
||||
|
||||
if ctx != nil {
|
||||
if hint == nil {
|
||||
@@ -751,7 +813,8 @@ func (client *Client) RecoverWithContext(
|
||||
|
||||
// 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.
|
||||
// the client is disabled or the timeout was reached. In the latter case, some
|
||||
// events may not have been sent.
|
||||
//
|
||||
// Flush should be called before terminating the program to avoid
|
||||
// unintentionally dropping events.
|
||||
@@ -761,6 +824,9 @@ func (client *Client) RecoverWithContext(
|
||||
// the network synchronously, configure it to use the HTTPSyncTransport in the
|
||||
// call to Init.
|
||||
func (client *Client) Flush(timeout time.Duration) bool {
|
||||
if !client.IsEnabled() {
|
||||
return false
|
||||
}
|
||||
if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
@@ -770,9 +836,10 @@ func (client *Client) Flush(timeout time.Duration) bool {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// to the Sentry server, blocking for at most the duration specified by the
|
||||
// context. It returns false if the client is disabled or the context is
|
||||
// canceled before the events are sent. In the latter case, some events may not
|
||||
// be delivered.
|
||||
//
|
||||
// FlushWithContext should be called before terminating the program to ensure no
|
||||
// events are unintentionally dropped.
|
||||
@@ -782,6 +849,9 @@ func (client *Client) Flush(timeout time.Duration) bool {
|
||||
// configure the SDK to use HTTPSyncTransport during initialization with Init.
|
||||
|
||||
func (client *Client) FlushWithContext(ctx context.Context) bool {
|
||||
if !client.IsEnabled() {
|
||||
return false
|
||||
}
|
||||
if client.batchLogger != nil {
|
||||
client.batchLogger.Flush(ctx.Done())
|
||||
}
|
||||
@@ -799,6 +869,9 @@ func (client *Client) FlushWithContext(ctx context.Context) bool {
|
||||
// Close should be called after Flush and before terminating the program
|
||||
// otherwise some events may be lost.
|
||||
func (client *Client) Close() {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
if client.telemetryProcessor != nil {
|
||||
client.telemetryProcessor.Close(5 * time.Second)
|
||||
}
|
||||
@@ -875,6 +948,9 @@ func (client *Client) EventFromCheckIn(checkIn *CheckIn, monitorConfig *MonitorC
|
||||
}
|
||||
|
||||
func (client *Client) SetSDKIdentifier(identifier string) {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
|
||||
|
||||
+4
-4
@@ -43,7 +43,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
|
||||
scope := hub.Scope()
|
||||
client := hub.Client()
|
||||
|
||||
if client == nil || scope == nil {
|
||||
if !client.IsEnabled() || scope == nil {
|
||||
return DynamicSamplingContext{
|
||||
Entries: map[string]string{},
|
||||
Frozen: false,
|
||||
@@ -53,7 +53,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
|
||||
entries := make(map[string]string)
|
||||
|
||||
if traceID := span.TraceID.String(); traceID != "" {
|
||||
entries["trace_id"] = traceID
|
||||
entries[traceIDContextKey] = traceID
|
||||
}
|
||||
if sampleRate := span.sampleRate; sampleRate != 0 {
|
||||
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
|
||||
@@ -122,7 +122,7 @@ func (d DynamicSamplingContext) String() string {
|
||||
func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext {
|
||||
entries := map[string]string{}
|
||||
|
||||
if client == nil || scope == nil {
|
||||
if !client.IsEnabled() || scope == nil {
|
||||
return DynamicSamplingContext{
|
||||
Entries: entries,
|
||||
Frozen: false,
|
||||
@@ -132,7 +132,7 @@ func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSampli
|
||||
propagationContext := scope.propagationContext
|
||||
|
||||
if traceID := propagationContext.TraceID.String(); traceID != "" {
|
||||
entries["trace_id"] = traceID
|
||||
entries[traceIDContextKey] = traceID
|
||||
}
|
||||
if sampleRate := client.options.TracesSampleRate; sampleRate != 0 {
|
||||
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ type visited struct {
|
||||
|
||||
func (v *visited) seenError(err error) bool {
|
||||
t := reflect.ValueOf(err)
|
||||
if t.Kind() == reflect.Ptr && !t.IsNil() {
|
||||
if t.Kind() == reflect.Pointer && !t.IsNil() {
|
||||
ptr := t.Pointer()
|
||||
if _, ok := v.ptrs[ptr]; ok {
|
||||
return true
|
||||
|
||||
+1
@@ -2,6 +2,7 @@ go 1.25.0
|
||||
|
||||
use (
|
||||
.
|
||||
./cron
|
||||
./crosstest
|
||||
./echo
|
||||
./fasthttp
|
||||
|
||||
+18
@@ -1,5 +1,7 @@
|
||||
cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4=
|
||||
cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cloud.google.com/go/auth v0.18.2/go.mod h1:xD+oY7gcahcu7G2SG2DsBerfFxgPAJz17zz2joOFF3M=
|
||||
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=
|
||||
@@ -14,6 +16,7 @@ git.sr.ht/~sbinet/gg v0.6.0/go.mod h1:uucygbfC9wVPQIfrmwM2et0imr8L7KQWywX0xpFMm9
|
||||
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/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM=
|
||||
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=
|
||||
@@ -60,6 +63,7 @@ github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJP
|
||||
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/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
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=
|
||||
@@ -85,6 +89,9 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
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/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.11/go.mod h1:RFV7MUdlb7AgEq2v7FmMCfeSMCllAzWxFgRdusoGks8=
|
||||
github.com/googleapis/gax-go/v2 v2.17.0/go.mod h1:mzaqghpQp4JDh3HvADwrat+6M3MOIDp5YKHhb9PAgDY=
|
||||
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=
|
||||
@@ -138,6 +145,7 @@ 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/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
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=
|
||||
@@ -161,9 +169,13 @@ 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.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
|
||||
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/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
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=
|
||||
@@ -172,10 +184,12 @@ 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/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
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/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
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=
|
||||
@@ -184,6 +198,7 @@ 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/sync v0.22.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=
|
||||
@@ -199,6 +214,7 @@ 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/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||
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=
|
||||
@@ -212,11 +228,13 @@ 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/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk=
|
||||
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 v0.0.0-20260128011058-8636f8732409 h1:VQZ/yAbAtjkHgH80teYd2em3xtIkkHd7ZhqfH2N9CsM=
|
||||
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=
|
||||
|
||||
+52
-36
@@ -20,7 +20,7 @@ const (
|
||||
RequestContextKey = contextKey(2)
|
||||
)
|
||||
|
||||
// currentHub is the initial Hub with no Client bound and an empty Scope.
|
||||
// currentHub is the initial Hub with a no-op Client and an empty Scope.
|
||||
var currentHub = NewHub(nil, NewScope())
|
||||
|
||||
// Hub is the central object that manages scopes and clients.
|
||||
@@ -58,7 +58,7 @@ func (l *layer) Client() *Client {
|
||||
func (l *layer) SetClient(c *Client) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
l.client = c
|
||||
l.client = normalizeClient(c)
|
||||
}
|
||||
|
||||
type stack []*layer
|
||||
@@ -67,7 +67,7 @@ type stack []*layer
|
||||
func NewHub(client *Client, scope *Scope) *Hub {
|
||||
hub := Hub{
|
||||
stack: &stack{{
|
||||
client: client,
|
||||
client: normalizeClient(client),
|
||||
scope: scope,
|
||||
}},
|
||||
}
|
||||
@@ -218,12 +218,12 @@ func (hub *Hub) CaptureEvent(event *Event) *EventID {
|
||||
// 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 {
|
||||
if scope == nil {
|
||||
return nil
|
||||
}
|
||||
eventID := client.CaptureEvent(event, hint, scope)
|
||||
|
||||
if event.Type != transactionType && eventID != nil {
|
||||
if event != nil && event.Type != transactionType && eventID != nil {
|
||||
hub.mu.Lock()
|
||||
hub.lastEventID = *eventID
|
||||
hub.mu.Unlock()
|
||||
@@ -236,7 +236,7 @@ func (hub *Hub) CaptureEventWithHint(event *Event, hint *EventHint) *EventID {
|
||||
// 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 {
|
||||
if scope == nil {
|
||||
return nil
|
||||
}
|
||||
eventID := client.CaptureMessage(message, nil, scope)
|
||||
@@ -254,7 +254,7 @@ func (hub *Hub) CaptureMessage(message string) *EventID {
|
||||
// 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 {
|
||||
if scope == nil {
|
||||
return nil
|
||||
}
|
||||
eventID := client.CaptureException(exception, &EventHint{OriginalException: exception}, scope)
|
||||
@@ -272,13 +272,46 @@ func (hub *Hub) CaptureException(exception error) *EventID {
|
||||
// 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)
|
||||
}
|
||||
|
||||
// WithMonitor runs fn and reports its outcome as check-ins for the cron
|
||||
// monitor identified by monitorSlug.
|
||||
//
|
||||
// An in_progress check-in carrying monitorConfig is sent before fn runs. When
|
||||
// monitorConfig is not nil, Sentry creates the monitor if it does not exist,
|
||||
// or updates its configuration. After fn returns, an ok check-in is sent if
|
||||
// it returned nil, or an error check-in otherwise, along with the measured
|
||||
// duration. If fn panics, an error check-in is sent and the panic continues.
|
||||
//
|
||||
// The error returned by fn is returned unchanged.
|
||||
func (hub *Hub) WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error {
|
||||
checkInID := hub.CaptureCheckIn(&CheckIn{
|
||||
MonitorSlug: monitorSlug,
|
||||
Status: CheckInStatusInProgress,
|
||||
}, monitorConfig)
|
||||
start := time.Now()
|
||||
|
||||
status := CheckInStatusError
|
||||
defer func() {
|
||||
checkIn := &CheckIn{
|
||||
MonitorSlug: monitorSlug,
|
||||
Status: status,
|
||||
Duration: time.Since(start),
|
||||
}
|
||||
if checkInID != nil {
|
||||
checkIn.ID = *checkInID
|
||||
}
|
||||
hub.CaptureCheckIn(checkIn, nil)
|
||||
}()
|
||||
|
||||
err := fn()
|
||||
if err == nil {
|
||||
status = CheckInStatusOK
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// AddBreadcrumb records a new breadcrumb.
|
||||
//
|
||||
// The total number of breadcrumbs that can be recorded are limited by the
|
||||
@@ -286,12 +319,6 @@ func (hub *Hub) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *
|
||||
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:
|
||||
@@ -321,7 +348,7 @@ func (hub *Hub) Recover(err interface{}) *EventID {
|
||||
err = recover()
|
||||
}
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if client == nil || scope == nil {
|
||||
if scope == nil {
|
||||
return nil
|
||||
}
|
||||
return client.Recover(err, &EventHint{RecoveredException: err}, scope)
|
||||
@@ -335,7 +362,7 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
|
||||
err = recover()
|
||||
}
|
||||
client, scope := hub.Client(), hub.Scope()
|
||||
if client == nil || scope == nil {
|
||||
if scope == nil {
|
||||
return nil
|
||||
}
|
||||
return client.RecoverWithContext(ctx, err, &EventHint{RecoveredException: err}, scope)
|
||||
@@ -353,19 +380,14 @@ func (hub *Hub) RecoverWithContext(ctx context.Context, err interface{}) *EventI
|
||||
// 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)
|
||||
return hub.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.
|
||||
// to the Sentry server, blocking for at most the duration specified by the
|
||||
// context. It returns false if capture is disabled or the context is canceled
|
||||
// before the events are sent. In the latter case, some events may not be
|
||||
// delivered.
|
||||
//
|
||||
// FlushWithContext should be called before terminating the program to ensure no
|
||||
// events are unintentionally dropped.
|
||||
@@ -375,13 +397,7 @@ func (hub *Hub) Flush(timeout time.Duration) bool {
|
||||
// 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)
|
||||
return hub.Client().FlushWithContext(ctx)
|
||||
}
|
||||
|
||||
// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value
|
||||
|
||||
+36
@@ -48,6 +48,12 @@ func NewWrapResponseWriter(w http.ResponseWriter, protoMajor int) WrapResponseWr
|
||||
if fl && hj && rf {
|
||||
return &httpFancyWriter{bw}
|
||||
}
|
||||
if fl && hj {
|
||||
return &flushHijackWriter{bw}
|
||||
}
|
||||
if hj {
|
||||
return &hijackWriter{bw}
|
||||
}
|
||||
}
|
||||
if fl {
|
||||
return &flushWriter{bw}
|
||||
@@ -143,6 +149,36 @@ func (f *flushWriter) Flush() {
|
||||
|
||||
var _ http.Flusher = &flushWriter{}
|
||||
|
||||
// flushHijackWriter is a HTTP writer that additionally satisfies http.Flusher
|
||||
// and http.Hijacker, for writers that do not implement io.ReaderFrom.
|
||||
type flushHijackWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *flushHijackWriter) Flush() {
|
||||
f.wroteHeader = true
|
||||
f.ResponseWriter.(http.Flusher).Flush()
|
||||
}
|
||||
|
||||
func (f *flushHijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return f.ResponseWriter.(http.Hijacker).Hijack()
|
||||
}
|
||||
|
||||
var _ http.Flusher = &flushHijackWriter{}
|
||||
var _ http.Hijacker = &flushHijackWriter{}
|
||||
|
||||
// hijackWriter is a HTTP writer that additionally satisfies http.Hijacker, for
|
||||
// writers that implement neither http.Flusher nor io.ReaderFrom.
|
||||
type hijackWriter struct {
|
||||
basicWriter
|
||||
}
|
||||
|
||||
func (f *hijackWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return f.ResponseWriter.(http.Hijacker).Hijack()
|
||||
}
|
||||
|
||||
var _ http.Hijacker = &hijackWriter{}
|
||||
|
||||
// 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
|
||||
|
||||
+12
-8
@@ -3,6 +3,7 @@ package protocol
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -210,17 +211,20 @@ func (dsn *Dsn) SetOrgID(orgID uint64) {
|
||||
// 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)
|
||||
host := dsn.host
|
||||
port := ""
|
||||
if dsn.port != dsn.scheme.defaultPort() {
|
||||
rawURL += fmt.Sprintf(":%d", dsn.port)
|
||||
port = strconv.Itoa(dsn.port)
|
||||
}
|
||||
if dsn.path != "" {
|
||||
rawURL += dsn.path
|
||||
// JoinHostPort correctly adds brackets for IPv6 hosts. However with an
|
||||
// empty port it leaves a trailing ":", which we trim to omit the default port.
|
||||
host = net.JoinHostPort(host, port)
|
||||
host = strings.TrimSuffix(host, ":")
|
||||
return &url.URL{
|
||||
Scheme: string(dsn.scheme),
|
||||
Host: host,
|
||||
Path: dsn.path + "/api/" + dsn.projectID + "/envelope/",
|
||||
}
|
||||
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
|
||||
|
||||
+26
-2
@@ -26,6 +26,9 @@ type Scheduler struct {
|
||||
cancel context.CancelFunc
|
||||
processingWg sync.WaitGroup
|
||||
|
||||
// processing serializes buffer-to-transport handoffs and allows cancelable waits.
|
||||
processing chan struct{}
|
||||
|
||||
mu sync.Mutex
|
||||
cond *sync.Cond
|
||||
startOnce sync.Once
|
||||
@@ -79,6 +82,7 @@ func NewScheduler(
|
||||
currentCycle: currentCycle,
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
processing: make(chan struct{}, 1),
|
||||
}
|
||||
s.cond = sync.NewCond(&s.mu)
|
||||
|
||||
@@ -145,7 +149,9 @@ func (s *Scheduler) Flush(timeout time.Duration) bool {
|
||||
}
|
||||
|
||||
func (s *Scheduler) FlushWithContext(ctx context.Context) bool {
|
||||
s.flushBuffers()
|
||||
if !s.flushBuffers(ctx) {
|
||||
return false
|
||||
}
|
||||
return s.transport.FlushWithContext(ctx)
|
||||
}
|
||||
|
||||
@@ -193,6 +199,13 @@ func (s *Scheduler) hasWork() bool {
|
||||
}
|
||||
|
||||
func (s *Scheduler) processNextBatch() {
|
||||
select {
|
||||
case s.processing <- struct{}{}:
|
||||
defer func() { <-s.processing }()
|
||||
case <-s.ctx.Done():
|
||||
return
|
||||
}
|
||||
|
||||
if len(s.currentCycle) == 0 {
|
||||
return
|
||||
}
|
||||
@@ -290,12 +303,23 @@ func (s *Scheduler) sendItem(item protocol.EnvelopeConvertible) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) flushBuffers() {
|
||||
func (s *Scheduler) flushBuffers(ctx context.Context) bool {
|
||||
select {
|
||||
case s.processing <- struct{}{}:
|
||||
defer func() { <-s.processing }()
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
}
|
||||
|
||||
for category, buffer := range s.buffers {
|
||||
if ctx.Err() != nil {
|
||||
return false
|
||||
}
|
||||
if !buffer.IsEmpty() {
|
||||
s.processItems(buffer, category, true)
|
||||
}
|
||||
}
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
|
||||
func (s *Scheduler) isRateLimited(category ratelimit.Category) bool {
|
||||
|
||||
+2
-2
@@ -60,7 +60,7 @@ func NewLogger(ctx context.Context) Logger { // nolint: dupl
|
||||
}
|
||||
|
||||
client := hub.Client()
|
||||
if client != nil {
|
||||
if client.IsEnabled() {
|
||||
// Build default attrs
|
||||
serverAddr := client.options.ServerName
|
||||
if serverAddr == "" {
|
||||
@@ -111,7 +111,7 @@ func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, me
|
||||
hub = l.hub
|
||||
}
|
||||
client := hub.Client()
|
||||
if client == nil {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -55,7 +55,7 @@ func NewMeter(ctx context.Context) Meter {
|
||||
hub = CurrentHub()
|
||||
}
|
||||
client := hub.Client()
|
||||
if client != nil {
|
||||
if client.IsEnabled() {
|
||||
// build default attrs
|
||||
serverAddr := client.options.ServerName
|
||||
if serverAddr == "" {
|
||||
@@ -110,7 +110,7 @@ func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name stri
|
||||
}
|
||||
|
||||
client := hub.Client()
|
||||
if client == nil {
|
||||
if !client.IsEnabled() {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+7
-2
@@ -4,6 +4,11 @@ import (
|
||||
"crypto/rand"
|
||||
)
|
||||
|
||||
const (
|
||||
traceIDContextKey = "trace_id"
|
||||
spanIDContextKey = "span_id"
|
||||
)
|
||||
|
||||
type PropagationContext struct {
|
||||
TraceID TraceID `json:"trace_id"`
|
||||
SpanID SpanID `json:"span_id"`
|
||||
@@ -13,8 +18,8 @@ type PropagationContext struct {
|
||||
|
||||
func (p PropagationContext) Map() map[string]interface{} {
|
||||
m := map[string]interface{}{
|
||||
"trace_id": p.TraceID,
|
||||
"span_id": p.SpanID,
|
||||
traceIDContextKey: p.TraceID,
|
||||
spanIDContextKey: p.SpanID,
|
||||
}
|
||||
|
||||
if p.ParentSpanID != zeroSpanID {
|
||||
|
||||
+33
-13
@@ -30,7 +30,15 @@ import (
|
||||
// an event for reporting, the current client adds information from the current
|
||||
// scope into the event.
|
||||
type Scope struct {
|
||||
mu sync.RWMutex
|
||||
mu sync.RWMutex
|
||||
// eventProcessors are retained by Clear and inherited by Clone.
|
||||
eventProcessors []EventProcessor
|
||||
|
||||
// scopeData keeps track of all scope specific data
|
||||
scopeData
|
||||
}
|
||||
|
||||
type scopeData struct {
|
||||
attributes map[string]attribute.Value
|
||||
breadcrumbs []*Breadcrumb
|
||||
attachments []*Attachment
|
||||
@@ -49,7 +57,6 @@ type Scope struct {
|
||||
// size.
|
||||
Overflow() bool
|
||||
}
|
||||
eventProcessors []EventProcessor
|
||||
|
||||
propagationContext PropagationContext
|
||||
span *Span
|
||||
@@ -57,14 +64,18 @@ type Scope struct {
|
||||
|
||||
// NewScope creates a new Scope.
|
||||
func NewScope() *Scope {
|
||||
return &Scope{
|
||||
return &Scope{scopeData: newScopeData(NewPropagationContext())}
|
||||
}
|
||||
|
||||
func newScopeData(propagationContext PropagationContext) scopeData {
|
||||
return scopeData{
|
||||
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(),
|
||||
propagationContext: propagationContext,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,6 +293,7 @@ func (scope *Scope) Clone() *Scope {
|
||||
|
||||
clone := NewScope()
|
||||
clone.user = scope.user
|
||||
clone.user.Data = maps.Clone(scope.user.Data)
|
||||
clone.breadcrumbs = make([]*Breadcrumb, len(scope.breadcrumbs))
|
||||
copy(clone.breadcrumbs, scope.breadcrumbs)
|
||||
clone.attachments = make([]*Attachment, len(scope.attachments))
|
||||
@@ -300,9 +312,16 @@ func (scope *Scope) Clone() *Scope {
|
||||
return clone
|
||||
}
|
||||
|
||||
// Clear removes the data from the current scope. Not safe for concurrent use.
|
||||
// Clear removes enrichment data while preserving event processors and trace
|
||||
// correlation. It is safe for concurrent use.
|
||||
func (scope *Scope) Clear() {
|
||||
*scope = *NewScope()
|
||||
scope.mu.Lock()
|
||||
defer scope.mu.Unlock()
|
||||
|
||||
propagationContext := scope.propagationContext
|
||||
span := scope.span
|
||||
scope.scopeData = newScopeData(propagationContext)
|
||||
scope.span = span
|
||||
}
|
||||
|
||||
// AddEventProcessor adds an event processor to the current scope.
|
||||
@@ -375,7 +394,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
event.Contexts["trace"] = scope.propagationContext.Map()
|
||||
|
||||
dsc := scope.propagationContext.DynamicSamplingContext
|
||||
if !dsc.HasEntries() && client != nil {
|
||||
if !dsc.HasEntries() && client.IsEnabled() {
|
||||
dsc = DynamicSamplingContextFromScope(scope, client)
|
||||
}
|
||||
event.sdkMetaData.dsc = dsc
|
||||
@@ -383,7 +402,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
|
||||
// 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 {
|
||||
if client.IsEnabled() {
|
||||
var ctx context.Context
|
||||
if hint != nil {
|
||||
ctx = hint.Context
|
||||
@@ -393,13 +412,14 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
}
|
||||
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()
|
||||
traceCtx[traceIDContextKey] = traceID.String()
|
||||
traceCtx[spanIDContextKey] = spanID.String()
|
||||
}
|
||||
}
|
||||
|
||||
if event.User.IsEmpty() {
|
||||
event.User = scope.user
|
||||
event.User.Data = maps.Clone(scope.user.Data)
|
||||
}
|
||||
|
||||
if len(event.Fingerprint) == 0 {
|
||||
@@ -434,7 +454,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
event = processor(event, hint)
|
||||
if event == nil {
|
||||
debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id)
|
||||
if client != nil {
|
||||
if client.IsEnabled() {
|
||||
client.reportRecorder.RecordOne(report.ReasonEventProcessor, category)
|
||||
if category == ratelimit.CategoryTransaction {
|
||||
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(spanCountBefore))
|
||||
@@ -443,7 +463,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client)
|
||||
return nil
|
||||
}
|
||||
if droppedSpans := spanCountBefore - event.GetSpanCount(); droppedSpans > 0 {
|
||||
if client != nil {
|
||||
if client.IsEnabled() {
|
||||
client.reportRecorder.Record(report.ReasonEventProcessor, ratelimit.CategorySpan, int64(droppedSpans))
|
||||
}
|
||||
}
|
||||
@@ -524,7 +544,7 @@ func resolveTrace(scope *Scope, client *Client, ctxs ...context.Context) (traceI
|
||||
if ctx == nil {
|
||||
continue
|
||||
}
|
||||
if client != nil {
|
||||
if client.IsEnabled() {
|
||||
if traceID, spanID, ok := client.externalTraceContextFromContext(ctx); ok {
|
||||
return traceID, spanID
|
||||
}
|
||||
|
||||
+25
-4
@@ -6,7 +6,7 @@ import (
|
||||
)
|
||||
|
||||
// The version of the SDK.
|
||||
const SDKVersion = "0.49.0"
|
||||
const SDKVersion = "0.50.0"
|
||||
|
||||
// apiVersion is the minimum version of the Sentry API compatible with the
|
||||
// sentry-go SDK.
|
||||
@@ -54,6 +54,26 @@ func CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorConfig) *EventID {
|
||||
return hub.CaptureCheckIn(checkIn, monitorConfig)
|
||||
}
|
||||
|
||||
// WithMonitor runs fn and reports its outcome as check-ins for the cron
|
||||
// monitor identified by monitorSlug, creating or updating the monitor with
|
||||
// monitorConfig when it is not nil. It is a shorthand for
|
||||
// CurrentHub().WithMonitor.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// err := sentry.WithMonitor("nightly-cleanup", &sentry.MonitorConfig{
|
||||
// Schedule: sentry.CrontabSchedule("0 3 * * *"),
|
||||
// CheckInMargin: 5,
|
||||
// MaxRuntime: 30,
|
||||
// Timezone: "UTC",
|
||||
// }, func() error {
|
||||
// return cleanup()
|
||||
// })
|
||||
func WithMonitor(monitorSlug string, monitorConfig *MonitorConfig, fn func() error) error {
|
||||
hub := CurrentHub()
|
||||
return hub.WithMonitor(monitorSlug, monitorConfig, fn)
|
||||
}
|
||||
|
||||
// CaptureEvent captures an event on the currently active client if any.
|
||||
//
|
||||
// The event must already be assembled. Typically code would instead use
|
||||
@@ -129,9 +149,10 @@ func Flush(timeout time.Duration) bool {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// to the Sentry server, blocking for at most the duration specified by the
|
||||
// context. It returns false if capture is disabled or the context is canceled
|
||||
// before the events are sent. In the latter case, some events may not be
|
||||
// delivered.
|
||||
//
|
||||
// FlushWithContext should be called before terminating the program to ensure no
|
||||
// events are unintentionally dropped.
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ type spanRecorder struct {
|
||||
// span tree.
|
||||
func (r *spanRecorder) record(s *Span) {
|
||||
maxSpans := defaultMaxSpans
|
||||
if client := CurrentHub().Client(); client != nil {
|
||||
if client := CurrentHub().Client(); client.IsEnabled() {
|
||||
maxSpans = client.options.MaxSpans
|
||||
}
|
||||
r.mu.Lock()
|
||||
|
||||
+4
-4
@@ -551,7 +551,7 @@ func (s *Span) updateFromBaggage(header []byte) {
|
||||
|
||||
func (s *Span) clientOptions() *ClientOptions {
|
||||
client := hubFromContext(s.ctx).Client()
|
||||
if client != nil {
|
||||
if client.IsEnabled() {
|
||||
return &client.options
|
||||
}
|
||||
return &ClientOptions{}
|
||||
@@ -933,8 +933,8 @@ type TraceContext struct {
|
||||
|
||||
func (tc TraceContext) Map() map[string]interface{} {
|
||||
m := map[string]interface{}{
|
||||
"trace_id": tc.TraceID,
|
||||
"span_id": tc.SpanID,
|
||||
traceIDContextKey: tc.TraceID,
|
||||
spanIDContextKey: tc.SpanID,
|
||||
}
|
||||
|
||||
if tc.ParentSpanID != [8]byte{} {
|
||||
@@ -1202,7 +1202,7 @@ func HTTPtoSpanStatus(code int) SpanStatus {
|
||||
}
|
||||
|
||||
func shouldContinueTrace(client *Client, dsc DynamicSamplingContext) bool {
|
||||
if client == nil {
|
||||
if !client.IsEnabled() {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
+4
-1
@@ -63,6 +63,7 @@ const (
|
||||
ChineseFirstNameTag = "chinese_first_name"
|
||||
ChineseLastNameTag = "chinese_last_name"
|
||||
ChineseNameTag = "chinese_name"
|
||||
ChinesePhoneNumberTag = "chinese_phone_number"
|
||||
GENDER = "gender"
|
||||
UnixTimeTag = "unix_time"
|
||||
DATE = "date"
|
||||
@@ -107,7 +108,7 @@ const (
|
||||
var PriorityTags = []string{ID, HyphenatedID, EmailTag, MacAddressTag, DomainNameTag, UserNameTag, URLTag, IPV4Tag,
|
||||
IPV6Tag, PASSWORD, JWT, CountryInfoTag, LATITUDE, LONGITUDE, CreditCardNumber, CreditCardType, PhoneNumber, TollFreeNumber,
|
||||
E164PhoneNumberTag, TitleMaleTag, TitleFemaleTag, FirstNameTag, FirstNameMaleTag, FirstNameFemaleTag, LastNameTag,
|
||||
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
|
||||
NAME, ChineseFirstNameTag, ChineseLastNameTag, ChineseNameTag, ChinesePhoneNumberTag, GENDER, UnixTimeTag, DATE, TIME, MonthNameTag,
|
||||
YEAR, DayOfWeekTag, DayOfMonthTag, TIMESTAMP, CENTURY, TIMEZONE, TimePeriodTag, WORD, SENTENCE, PARAGRAPH,
|
||||
CurrencyTag, AmountTag, AmountWithCurrencyTag, SKIP, Length, SliceLength, Language, BoundaryStart, BoundaryEnd, ONEOF, BloodTypeTag,
|
||||
UserAgentTag,
|
||||
@@ -169,6 +170,7 @@ func initDefaultTag() {
|
||||
defaultTag.Store(ChineseFirstNameTag, ChineseFirstNameTag)
|
||||
defaultTag.Store(ChineseLastNameTag, ChineseLastNameTag)
|
||||
defaultTag.Store(ChineseNameTag, ChineseNameTag)
|
||||
defaultTag.Store(ChinesePhoneNumberTag, ChinesePhoneNumberTag)
|
||||
defaultTag.Store(GENDER, GENDER)
|
||||
defaultTag.Store(UnixTimeTag, UnixTimeTag)
|
||||
defaultTag.Store(DATE, DATE)
|
||||
@@ -220,6 +222,7 @@ func initMapperTagDefault() {
|
||||
mapperTag.Store(ChineseFirstNameTag, GetPerson().ChineseFirstName)
|
||||
mapperTag.Store(ChineseLastNameTag, GetPerson().ChineseLastName)
|
||||
mapperTag.Store(ChineseNameTag, GetPerson().ChineseName)
|
||||
mapperTag.Store(ChinesePhoneNumberTag, GetPhoner().ChinesePhoneNumber)
|
||||
mapperTag.Store(GENDER, GetPerson().Gender)
|
||||
mapperTag.Store(UnixTimeTag, GetDateTimer().UnixTime)
|
||||
mapperTag.Store(DATE, GetDateTimer().Date)
|
||||
|
||||
+34
@@ -9,6 +9,20 @@ import (
|
||||
"github.com/go-faker/faker/v4/pkg/slice"
|
||||
)
|
||||
|
||||
// chineseMobilePrefixes holds the 3-digit prefixes of Mainland China mobile
|
||||
// numbers, allocated to China Mobile, China Unicom, China Telecom and China
|
||||
// Broadnet (including MVNO & IoT segments). Each prefix is followed by 8
|
||||
// subscriber digits to form an 11-digit number.
|
||||
var chineseMobilePrefixes = []string{
|
||||
"130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
|
||||
"145", "146", "147", "148", "149",
|
||||
"150", "151", "152", "153", "155", "156", "157", "158", "159",
|
||||
"162", "165", "166", "167",
|
||||
"170", "171", "172", "173", "174", "175", "176", "177", "178",
|
||||
"180", "181", "182", "183", "184", "185", "186", "187", "188", "189",
|
||||
"190", "191", "192", "193", "195", "196", "197", "198", "199",
|
||||
}
|
||||
|
||||
// GetPhoner serves as a constructor for Phoner interface
|
||||
func GetPhoner() Phoner {
|
||||
phone := &Phone{}
|
||||
@@ -20,6 +34,7 @@ type Phoner interface {
|
||||
PhoneNumber(v reflect.Value) (any, error)
|
||||
TollFreePhoneNumber(v reflect.Value) (any, error)
|
||||
E164PhoneNumber(v reflect.Value) (any, error)
|
||||
ChinesePhoneNumber(v reflect.Value) (any, error)
|
||||
}
|
||||
|
||||
// Phone struct
|
||||
@@ -95,3 +110,22 @@ func E164PhoneNumber(opts ...options.OptionFunc) string {
|
||||
return p.e164PhoneNumber()
|
||||
}, opts...).(string)
|
||||
}
|
||||
|
||||
func (p Phone) chinesePhoneNumber() string {
|
||||
prefix := chineseMobilePrefixes[rand.Intn(len(chineseMobilePrefixes))]
|
||||
return prefix + randomStringNumber(8)
|
||||
}
|
||||
|
||||
// ChinesePhoneNumber generates a Mainland-China mobile phone number of the
|
||||
// form "13812345678" (11 digits, starting with a valid operator prefix)
|
||||
func (p Phone) ChinesePhoneNumber(v reflect.Value) (any, error) {
|
||||
return p.chinesePhoneNumber(), nil
|
||||
}
|
||||
|
||||
// ChinesePhoneNumber get fake Chinese phone number
|
||||
func ChinesePhoneNumber(opts ...options.OptionFunc) string {
|
||||
return singleFakeData(ChinesePhoneNumberTag, func() any {
|
||||
p := Phone{}
|
||||
return p.chinesePhoneNumber()
|
||||
}, opts...).(string)
|
||||
}
|
||||
+7
-5
@@ -139,11 +139,13 @@ func main() {
|
||||
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
|
||||
// Ordinal Plural Rules. The method returns the locales/plurals.Rule
|
||||
// (e.g. One, Two, Few, Other) for the number; converting that rule into
|
||||
// the actual suffix ("st", "nd", "rd", "th") is left to the caller.
|
||||
fmt.Println(l.OrdinalPluralRule(21, 0)) // One (-> "21st")
|
||||
fmt.Println(l.OrdinalPluralRule(22, 0)) // Two (-> "22nd")
|
||||
fmt.Println(l.OrdinalPluralRule(33, 0)) // Few (-> "33rd")
|
||||
fmt.Println(l.OrdinalPluralRule(34, 0)) // Other (-> "34th")
|
||||
|
||||
// Range Plural Rules
|
||||
fmt.Println(l.RangePluralRule(1, 0, 1, 0)) // 1-1
|
||||
|
||||
+12
-16
@@ -498,10 +498,9 @@ func (en *en) FmtTimeShort(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
@@ -528,10 +527,9 @@ func (en *en) FmtTimeMedium(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
@@ -565,10 +563,9 @@ func (en *en) FmtTimeLong(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
@@ -607,10 +604,9 @@ func (en *en) FmtTimeFull(t time.Time) string {
|
||||
|
||||
b := make([]byte, 0, 32)
|
||||
|
||||
h := t.Hour()
|
||||
|
||||
if h > 12 {
|
||||
h -= 12
|
||||
h := t.Hour() % 12
|
||||
if h == 0 {
|
||||
h = 12
|
||||
}
|
||||
|
||||
b = strconv.AppendInt(b, int64(h), 10)
|
||||
|
||||
+13
-10
@@ -98,7 +98,7 @@ type Translator interface {
|
||||
// returns the locales narrow weekday given the 'weekday' provided
|
||||
WeekdayNarrow(weekday time.Weekday) string
|
||||
|
||||
// WeekdaysNarrowreturns the locales narrow weekdays
|
||||
// WeekdaysNarrow returns the locales narrow weekdays
|
||||
WeekdaysNarrow() []string
|
||||
|
||||
// returns the locales short weekday given the 'weekday' provided
|
||||
@@ -113,7 +113,7 @@ type Translator interface {
|
||||
// returns the locales wide weekdays
|
||||
WeekdaysWide() []string
|
||||
|
||||
// The following Functions are common Formatting functionsfor the Translator's Locale
|
||||
// The following Functions are common Formatting functions for 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
|
||||
@@ -228,14 +228,14 @@ 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
|
||||
// will 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
|
||||
end := 0
|
||||
|
||||
for i := end; i >= 0; i-- {
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
if s[i] != '0' {
|
||||
end = i + 1
|
||||
break
|
||||
@@ -253,7 +253,7 @@ 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
|
||||
// will either be '0' or '0.xxxx', so if 1 then f will be zero
|
||||
// otherwise need to parse
|
||||
if len(s) != 1 {
|
||||
|
||||
@@ -270,14 +270,14 @@ 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
|
||||
// will 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
|
||||
end := 0
|
||||
|
||||
for i := end; i >= 0; i-- {
|
||||
for i := len(s) - 1; i >= 0; i-- {
|
||||
if s[i] != '0' {
|
||||
end = i + 1
|
||||
break
|
||||
@@ -286,8 +286,11 @@ func T(n float64, v uint64) (t int64) {
|
||||
|
||||
// ignoring error, because it can't fail as we generated
|
||||
// the string internally from a real number
|
||||
t, _ = strconv.ParseInt(s[:end], 10, 64)
|
||||
if end > 0 {
|
||||
t, _ = strconv.ParseInt(s[:end], 10, 64)
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project
|
||||
|
||||
`universal-translator` (`ut`) is a Go i18n library that wraps `github.com/go-playground/locales` (CLDR locale data) to provide translation registration, plural rule handling (cardinal, ordinal, range), and `{0}`-style parameter substitution. Translations can be registered programmatically or loaded from JSON files.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Run tests with race detection and coverage
|
||||
make test
|
||||
|
||||
# Run benchmarks
|
||||
make bench
|
||||
|
||||
# Lint
|
||||
make lint # or: golangci-lint run
|
||||
|
||||
# Run a single test
|
||||
go test -run TestTranslatorAdd -race -v ./...
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
Flat package `ut` at the repo root — no sub-packages.
|
||||
|
||||
- **`universal_translator.go`** — `UniversalTranslator` struct: holds a `map[string]Translator` (keyed by lowercased locale) plus a fallback. Constructor: `New(fallback, ...supportedLocales)`. Methods: `FindTranslator`, `GetTranslator`, `AddTranslator`, `VerifyTranslations`.
|
||||
- **`translator.go`** — `Translator` interface (embeds `locales.Translator`) and private `translator` impl. Registration: `Add`, `AddCardinal`, `AddOrdinal`, `AddRange`. Resolution: `T`, `C`, `O`, `R`. Each translation key is `interface{}` (string or int). Parameter substitution indexes are precomputed at registration time via `transText`.
|
||||
- **`import_export.go`** — JSON import/export. `Export` writes per-locale JSON files. `Import` reads them (supports recursive directory traversal). `ImportByReader` for streaming.
|
||||
- **`errors.go`** — Typed error structs: `ErrUnknownTranslation`, `ErrExistingTranslator`, `ErrConflictingTranslation`, `ErrRangeTranslation`, `ErrOrdinalTranslation`, `ErrCardinalTranslation`, `ErrMissingPluralTranslation`, `ErrMissingBracket`, `ErrBadParamSyntax`, `ErrMissingLocale`, `ErrBadPluralDefinition`.
|
||||
|
||||
Note: the private field names `cardinalTanslations`, `ordinalTanslations`, `rangeTanslations` are historical typos — do not "fix" them as it would break serialization/deserialization compatibility.
|
||||
|
||||
## Testing
|
||||
|
||||
Tests live at the repo root alongside source files. Test data JSON files are in `testdata/`. The library is goroutine-safe for reads once translations are registered — benchmarks in `benchmarks_test.go` test both serial and parallel `T()` calls.
|
||||
|
||||
## CI
|
||||
|
||||
GitHub Actions (`.github/workflows/workflow.yml`): Go 1.19.x matrix across ubuntu/macos/windows with race detection, coverage via goveralls, and golangci-lint.
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
## AI Agents
|
||||
|
||||
AI-assisted contributions are welcome but must be clearly attributed. If you are an AI agent or using an AI agent to contribute:
|
||||
|
||||
- **Commits**: Include a `Co-Authored-By:` trailer identifying the AI model used.
|
||||
- **Pull requests and issues**: State that the content was AI-generated or AI-assisted in the description.
|
||||
- **Code review comments**: Prefix with `[AI]` when posting automated review comments.
|
||||
|
||||
Contributions that obscure their AI origin may be closed.
|
||||
+11
@@ -82,6 +82,17 @@ 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.
|
||||
|
||||
Supported Go Versions
|
||||
---------------------
|
||||
This package is aligned with the [Go release policy](https://go.dev/doc/devel/release) in that support is guaranteed for
|
||||
the two most recent major versions.
|
||||
|
||||
This does not mean the package will not work with older versions of Go, only that we reserve the right to increase the
|
||||
MSGV(Minimum Supported Go Version) when the need arises to address Security issues/patches, OS issues & support or newly
|
||||
introduced functionality that would greatly benefit the maintenance and/or usage of this package.
|
||||
|
||||
If and when the MSGV is increased it will be done so in a minimum of a `Minor` release bump.
|
||||
|
||||
License
|
||||
------
|
||||
Distributed under MIT License, please see license file in code for more details.
|
||||
+5
-2
@@ -8,8 +8,11 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUnknowTranslation indicates the translation could not be found
|
||||
ErrUnknowTranslation = errors.New("Unknown Translation")
|
||||
// ErrUnknownTranslation indicates the translation could not be found
|
||||
ErrUnknownTranslation = errors.New("unknown translation")
|
||||
|
||||
// Deprecated: Use ErrUnknownTranslation instead.
|
||||
ErrUnknowTranslation = ErrUnknownTranslation
|
||||
)
|
||||
|
||||
var _ error = new(ErrConflictingTranslation)
|
||||
|
||||
+1
-1
@@ -163,7 +163,7 @@ func (t *UniversalTranslator) Import(format ImportExportFormat, dirnameOrFilenam
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
defer func() { _ = f.Close() }()
|
||||
|
||||
return t.ImportByReader(format, f)
|
||||
}
|
||||
|
||||
+83
-33
@@ -101,35 +101,87 @@ func (t *translator) Add(key interface{}, text string, override bool) error {
|
||||
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}
|
||||
indexes, err := parseParamPlaceholders(text, t.Locale(), key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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
|
||||
t.translations[key] = &transText{text: text, indexes: indexes}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseParamPlaceholders scans text for {N} placeholders where N is a canonical
|
||||
// non-negative integer (no leading zeros). Returns triplets [start, end, paramIdx, ...]
|
||||
// sorted by text position. Requires consecutive param indices starting from 0.
|
||||
func parseParamPlaceholders(text string, locale string, key interface{}) ([]int, error) {
|
||||
var indexes []int
|
||||
seen := make(map[int]struct{})
|
||||
maxParam := -1
|
||||
|
||||
for i := 0; i < len(text); i++ {
|
||||
if text[i] != '{' {
|
||||
continue
|
||||
}
|
||||
|
||||
j := i + 1
|
||||
for j < len(text) && text[j] >= '0' && text[j] <= '9' {
|
||||
j++
|
||||
}
|
||||
|
||||
digitLen := j - i - 1
|
||||
if digitLen == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if j >= len(text) {
|
||||
return nil, &ErrMissingBracket{locale: locale, key: key, text: text}
|
||||
}
|
||||
|
||||
if text[j] != '}' {
|
||||
i = j - 1
|
||||
continue
|
||||
}
|
||||
|
||||
if digitLen > 1 && text[i+1] == '0' {
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
|
||||
if digitLen > 9 {
|
||||
i = j
|
||||
continue
|
||||
}
|
||||
|
||||
n := 0
|
||||
for k := i + 1; k < j; k++ {
|
||||
n = n*10 + int(text[k]-'0')
|
||||
}
|
||||
|
||||
indexes = append(indexes, i, j+1, n)
|
||||
seen[n] = struct{}{}
|
||||
if n > maxParam {
|
||||
maxParam = n
|
||||
}
|
||||
|
||||
i = j
|
||||
}
|
||||
|
||||
if len(seen) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if maxParam != len(seen)-1 {
|
||||
for i := 0; i <= maxParam; i++ {
|
||||
if _, ok := seen[i]; !ok {
|
||||
return nil, &ErrBadParamSyntax{locale: locale, param: "{" + strconv.Itoa(i) + "}", key: key, text: text}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return indexes, 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;
|
||||
@@ -298,20 +350,18 @@ func (t *translator) T(key interface{}, params ...string) (string, error) {
|
||||
|
||||
trans, ok := t.translations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
}
|
||||
|
||||
b := make([]byte, 0, 64)
|
||||
|
||||
var start, end, count int
|
||||
var start, end int
|
||||
|
||||
for i := 0; i < len(trans.indexes); i++ {
|
||||
for i := 0; i < len(trans.indexes); i += 3 {
|
||||
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, params[trans.indexes[i+2]]...)
|
||||
start = trans.indexes[i+1]
|
||||
}
|
||||
|
||||
b = append(b, trans.text[start:]...)
|
||||
@@ -324,7 +374,7 @@ func (t *translator) C(key interface{}, num float64, digits uint64, param string
|
||||
|
||||
tarr, ok := t.cardinalTanslations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
}
|
||||
|
||||
rule := t.CardinalPluralRule(num, digits)
|
||||
@@ -344,7 +394,7 @@ func (t *translator) O(key interface{}, num float64, digits uint64, param string
|
||||
|
||||
tarr, ok := t.ordinalTanslations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
}
|
||||
|
||||
rule := t.OrdinalPluralRule(num, digits)
|
||||
@@ -365,7 +415,7 @@ func (t *translator) R(key interface{}, num1 float64, digits1 uint64, num2 float
|
||||
|
||||
tarr, ok := t.rangeTanslations[key]
|
||||
if !ok {
|
||||
return unknownTranslation, ErrUnknowTranslation
|
||||
return unknownTranslation, ErrUnknownTranslation
|
||||
}
|
||||
|
||||
rule := t.RangePluralRule(num1, digits1, num2, digits2)
|
||||
|
||||
+47
@@ -18,6 +18,50 @@ func (e InvalidTemplateError) Error() string {
|
||||
|
||||
// Parse parses the string representation of path template
|
||||
func Parse(tmpl string) (Compiler, error) {
|
||||
return parse(tmpl)
|
||||
}
|
||||
|
||||
// Segment is a top-level segment of a parsed path template.
|
||||
type Segment struct {
|
||||
// FieldPath is the field path bound by a variable segment, e.g. "name"
|
||||
// for "{name=projects/*}". It is empty for literal and wildcard segments.
|
||||
FieldPath string
|
||||
// Value is the literal or wildcard ("*" or "**") of a non-variable
|
||||
// segment, or the pattern of a variable segment, e.g. "projects/*" for
|
||||
// "{name=projects/*}". A variable without an explicit pattern, such as
|
||||
// "{name}", has the pattern "*".
|
||||
Value string
|
||||
}
|
||||
|
||||
// SplitTemplate parses the string representation of path template and
|
||||
// returns its top-level segments and its verb. The root template "/" has no
|
||||
// segments.
|
||||
func SplitTemplate(tmpl string) (segments []Segment, verb string, err error) {
|
||||
t, err := parse(tmpl)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
for _, s := range t.segments {
|
||||
switch s := s.(type) {
|
||||
case literal:
|
||||
if s == eof {
|
||||
continue
|
||||
}
|
||||
segments = append(segments, Segment{Value: string(s)})
|
||||
case variable:
|
||||
pattern := make([]string, 0, len(s.segments))
|
||||
for _, vs := range s.segments {
|
||||
pattern = append(pattern, vs.String())
|
||||
}
|
||||
segments = append(segments, Segment{FieldPath: s.path, Value: strings.Join(pattern, "/")})
|
||||
default:
|
||||
segments = append(segments, Segment{Value: s.String()})
|
||||
}
|
||||
}
|
||||
return segments, t.verb, nil
|
||||
}
|
||||
|
||||
func parse(tmpl string) (template, error) {
|
||||
if !strings.HasPrefix(tmpl, "/") {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
|
||||
}
|
||||
@@ -28,6 +72,9 @@ func Parse(tmpl string) (Compiler, error) {
|
||||
if err != nil {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()}
|
||||
}
|
||||
if err := expectPChars(verb); err != nil {
|
||||
return template{}, InvalidTemplateError{tmpl: tmpl, msg: fmt.Sprintf("invalid verb: %v", err)}
|
||||
}
|
||||
|
||||
return template{
|
||||
segments: segs,
|
||||
|
||||
+6
@@ -38,6 +38,7 @@ go_library(
|
||||
"@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/emptypb",
|
||||
"@org_golang_google_protobuf//types/known/fieldmaskpb",
|
||||
"@org_golang_google_protobuf//types/known/structpb",
|
||||
"@org_golang_google_protobuf//types/known/timestamppb",
|
||||
@@ -49,13 +50,16 @@ go_test(
|
||||
name = "runtime_test",
|
||||
size = "small",
|
||||
srcs = [
|
||||
"context_internal_test.go",
|
||||
"context_test.go",
|
||||
"convert_test.go",
|
||||
"errors_test.go",
|
||||
"fieldmask_empty_object_test.go",
|
||||
"fieldmask_test.go",
|
||||
"handler_test.go",
|
||||
"marshal_httpbodyproto_test.go",
|
||||
"marshal_json_test.go",
|
||||
"marshal_jsonpb_bench_test.go",
|
||||
"marshal_jsonpb_test.go",
|
||||
"marshal_proto_test.go",
|
||||
"marshaler_registry_test.go",
|
||||
@@ -63,6 +67,7 @@ go_test(
|
||||
"mux_test.go",
|
||||
"pattern_test.go",
|
||||
"query_fuzz_test.go",
|
||||
"query_internal_test.go",
|
||||
"query_test.go",
|
||||
],
|
||||
embed = [":runtime"],
|
||||
@@ -76,6 +81,7 @@ go_test(
|
||||
"@org_golang_google_genproto_googleapis_rpc//status",
|
||||
"@org_golang_google_grpc//:grpc",
|
||||
"@org_golang_google_grpc//codes",
|
||||
"@org_golang_google_grpc//credentials/insecure",
|
||||
"@org_golang_google_grpc//health/grpc_health_v1",
|
||||
"@org_golang_google_grpc//metadata",
|
||||
"@org_golang_google_grpc//status",
|
||||
|
||||
+76
-14
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
@@ -36,6 +37,13 @@ const metadataHeaderBinarySuffix = "-Bin"
|
||||
const xForwardedFor = "X-Forwarded-For"
|
||||
const xForwardedHost = "X-Forwarded-Host"
|
||||
|
||||
// gRPC metadata keys are lower-case, so these two are appended to the pairs under their
|
||||
// lower-case spelling. Writing it out as a constant keeps strings.ToLower off the per-request
|
||||
// path, where it allocated a new string for a compile-time constant on every call, and lets
|
||||
// metadata.Pairs skip its own lower-casing for these keys as well.
|
||||
const xForwardedForKey = "x-forwarded-for"
|
||||
const xForwardedHostKey = "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
|
||||
@@ -107,6 +115,10 @@ func isValidGRPCMetadataKey(key string) bool {
|
||||
// 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.
|
||||
// An empty key is not a valid header name, and gRPC fails the call with one.
|
||||
if key == "" {
|
||||
return false
|
||||
}
|
||||
bytes := []byte(key) // gRPC validates strings on the byte level, not Unicode.
|
||||
for _, ch := range bytes {
|
||||
validLowercaseLetter := ch >= 'a' && ch <= 'z'
|
||||
@@ -146,7 +158,21 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
return nil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", tm)
|
||||
}
|
||||
}
|
||||
var pairs []string
|
||||
// Each forwarded header contributes a key and a value, and the two X-Forwarded-* pairs the
|
||||
// gateway derives below add two more. Sizing for that up front replaces the handful of
|
||||
// reallocations an empty slice goes through while it doubles.
|
||||
pairs := make([]string, 0, 2*(len(req.Header)+2))
|
||||
// For backwards-compatibility, pass through 'authorization' header with no prefix.
|
||||
// It is added before the header loop so that it is always the first
|
||||
// "authorization" value: the loop iterates a map, so a header the matcher
|
||||
// forwards under the same key (Grpc-Metadata-Authorization with the default
|
||||
// matcher) would otherwise land ahead of it in random order, and a backend
|
||||
// reading the first value would get the client-forwarded one.
|
||||
for _, val := range req.Header.Values("Authorization") {
|
||||
if isValidGRPCMetadataTextValue(val) {
|
||||
pairs = append(pairs, "authorization", val)
|
||||
}
|
||||
}
|
||||
for key, vals := range req.Header {
|
||||
key = textproto.CanonicalMIMEHeaderKey(key)
|
||||
switch key {
|
||||
@@ -156,11 +182,17 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
}
|
||||
|
||||
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 {
|
||||
// The gateway derives x-forwarded-host and x-forwarded-for below from
|
||||
// the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends
|
||||
// rely on those metadata keys for client host/IP decisions. Refuse a
|
||||
// forwarded header that the matcher strips into one of them (e.g.
|
||||
// Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value
|
||||
// in ahead of the gateway-set one.
|
||||
if strings.EqualFold(h, xForwardedFor) || strings.EqualFold(h, xForwardedHost) {
|
||||
grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", key, h)
|
||||
continue
|
||||
}
|
||||
if !isValidGRPCMetadataKey(h) {
|
||||
grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", h)
|
||||
continue
|
||||
@@ -182,28 +214,52 @@ func annotateContext(ctx context.Context, mux *ServeMux, req *http.Request, rpcM
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
if host := req.Header.Get(xForwardedHost); host != "" && isValidGRPCMetadataTextValue(host) {
|
||||
pairs = append(pairs, xForwardedHostKey, host)
|
||||
} else if req.Host != "" && isValidGRPCMetadataTextValue(req.Host) {
|
||||
pairs = append(pairs, xForwardedHostKey, req.Host)
|
||||
}
|
||||
|
||||
xff := req.Header.Values(xForwardedFor)
|
||||
// Validate each X-Forwarded-For value on its own, so that an invalid
|
||||
// client-supplied value is dropped without also dropping the remote
|
||||
// address the gateway appends.
|
||||
var xff []string
|
||||
for _, value := range req.Header.Values(xForwardedFor) {
|
||||
if isValidGRPCMetadataTextValue(value) {
|
||||
xff = append(xff, value)
|
||||
}
|
||||
}
|
||||
if addr := req.RemoteAddr; addr != "" {
|
||||
if remoteIP, _, err := net.SplitHostPort(addr); err == nil {
|
||||
if remoteIP, _, err := net.SplitHostPort(addr); err == nil && isValidGRPCMetadataTextValue(remoteIP) {
|
||||
xff = append(xff, remoteIP)
|
||||
}
|
||||
}
|
||||
if len(xff) > 0 {
|
||||
pairs = append(pairs, strings.ToLower(xForwardedFor), strings.Join(xff, ", "))
|
||||
pairs = append(pairs, xForwardedForKey, strings.Join(xff, ", "))
|
||||
}
|
||||
|
||||
if timeout != 0 {
|
||||
ctx, _ = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
md := metadata.Pairs(pairs...)
|
||||
var annotated metadata.MD
|
||||
for _, mda := range mux.metadataAnnotators {
|
||||
md = metadata.Join(md, mda(ctx, req))
|
||||
annotated = metadata.Join(annotated, mda(ctx, req))
|
||||
}
|
||||
// Annotators are the gateway's own code, so their values replace whatever
|
||||
// the request headers put under the same key. Joining them after the
|
||||
// header values would let a client send Grpc-Metadata-<key> and have its
|
||||
// value read first by a backend that trusts the annotator.
|
||||
//
|
||||
// With no annotators registered -- the default -- there is nothing to merge, and
|
||||
// metadata.Join would rebuild the whole map for nothing: it starts from an empty MD and
|
||||
// appends every key's values into a fresh slice, so the result is an identical copy of md
|
||||
// bought with one allocation per key.
|
||||
if len(annotated) > 0 {
|
||||
for k := range annotated {
|
||||
delete(md, strings.ToLower(k))
|
||||
}
|
||||
md = metadata.Join(md, annotated)
|
||||
}
|
||||
if len(md) == 0 {
|
||||
return ctx, nil, nil
|
||||
@@ -302,10 +358,16 @@ func timeoutDecode(s string) (time.Duration, error) {
|
||||
if !ok {
|
||||
return 0, fmt.Errorf("timeout unit is not recognized: %q", s)
|
||||
}
|
||||
t, err := strconv.ParseInt(s[:size-1], 10, 64)
|
||||
t, err := strconv.ParseUint(s[:size-1], 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// Guard against overflowing time.Duration, which is an int64 nanosecond
|
||||
// count: without this a large value wraps to a bogus (often negative)
|
||||
// deadline instead of the long timeout the client asked for.
|
||||
if t > uint64(math.MaxInt64)/uint64(d) {
|
||||
return time.Duration(math.MaxInt64), nil
|
||||
}
|
||||
return d * time.Duration(t), nil
|
||||
}
|
||||
|
||||
|
||||
+50
-17
@@ -3,6 +3,7 @@ package runtime
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -44,9 +45,40 @@ func BoolSlice(val, sep string) ([]bool, error) {
|
||||
return values, nil
|
||||
}
|
||||
|
||||
// parseFloat parses a floating point value the way the proto3 JSON mapping
|
||||
// does: a decimal number, or the exact strings "Infinity", "-Infinity" and
|
||||
// "NaN". strconv.ParseFloat additionally accepts hexadecimal floats ("0x1p4"),
|
||||
// underscore digit separators ("1_000") and alternate infinity/NaN spellings
|
||||
// ("Inf", "nan", "infinity"), none of which protojson (and so the request body
|
||||
// and backend) accept. Reject those so a value bound from a query or path
|
||||
// parameter can't differ from the same value sent in the body.
|
||||
func parseFloat(val string, bitSize int) (float64, error) {
|
||||
switch val {
|
||||
case "Infinity":
|
||||
return math.Inf(1), nil
|
||||
case "-Infinity":
|
||||
return math.Inf(-1), nil
|
||||
case "NaN":
|
||||
return math.NaN(), nil
|
||||
}
|
||||
if strings.ContainsAny(val, "xX_") {
|
||||
return 0, fmt.Errorf("invalid syntax %q", val)
|
||||
}
|
||||
f, err := strconv.ParseFloat(val, bitSize)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
// ParseFloat only yields Inf/NaN without an error for the alternate
|
||||
// spellings handled above; overflow returns a range error instead.
|
||||
if math.IsInf(f, 0) || math.IsNaN(f) {
|
||||
return 0, fmt.Errorf("invalid syntax %q", val)
|
||||
}
|
||||
return f, 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)
|
||||
return parseFloat(val, 64)
|
||||
}
|
||||
|
||||
// Float64Slice converts 'val' where individual floating point numbers are separated by
|
||||
@@ -66,7 +98,7 @@ func Float64Slice(val, sep string) ([]float64, error) {
|
||||
|
||||
// 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)
|
||||
f, err := parseFloat(val, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -90,7 +122,7 @@ func Float32Slice(val, sep string) ([]float32, error) {
|
||||
|
||||
// Int64 converts the given string representation of an integer into int64.
|
||||
func Int64(val string) (int64, error) {
|
||||
return strconv.ParseInt(val, 0, 64)
|
||||
return strconv.ParseInt(val, 10, 64)
|
||||
}
|
||||
|
||||
// Int64Slice converts 'val' where individual integers are separated by
|
||||
@@ -110,7 +142,7 @@ func Int64Slice(val, sep string) ([]int64, error) {
|
||||
|
||||
// Int32 converts the given string representation of an integer into int32.
|
||||
func Int32(val string) (int32, error) {
|
||||
i, err := strconv.ParseInt(val, 0, 32)
|
||||
i, err := strconv.ParseInt(val, 10, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -134,7 +166,7 @@ func Int32Slice(val, sep string) ([]int32, error) {
|
||||
|
||||
// Uint64 converts the given string representation of an integer into uint64.
|
||||
func Uint64(val string) (uint64, error) {
|
||||
return strconv.ParseUint(val, 0, 64)
|
||||
return strconv.ParseUint(val, 10, 64)
|
||||
}
|
||||
|
||||
// Uint64Slice converts 'val' where individual integers are separated by
|
||||
@@ -154,7 +186,7 @@ func Uint64Slice(val, sep string) ([]uint64, error) {
|
||||
|
||||
// Uint32 converts the given string representation of an integer into uint32.
|
||||
func Uint32(val string) (uint32, error) {
|
||||
i, err := strconv.ParseUint(val, 0, 32)
|
||||
i, err := strconv.ParseUint(val, 10, 32)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -176,21 +208,22 @@ func Uint32Slice(val, sep string) ([]uint32, error) {
|
||||
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
|
||||
// Bytes converts the given string representation of a byte sequence into a slice of bytes.
|
||||
// Like the protobuf JSON mapping, it accepts standard or URL-safe base64, with or
|
||||
// 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
|
||||
}
|
||||
enc := base64.StdEncoding
|
||||
if strings.ContainsAny(val, "-_") {
|
||||
enc = base64.URLEncoding
|
||||
}
|
||||
return b, nil
|
||||
if len(val)%4 != 0 {
|
||||
enc = enc.WithPadding(base64.NoPadding)
|
||||
}
|
||||
return enc.DecodeString(val)
|
||||
}
|
||||
|
||||
// BytesSlice converts 'val' where individual bytes sequences, encoded in URL-safe
|
||||
// base64 without padding, are separated by 'sep' into a slice of byte slices.
|
||||
// BytesSlice converts 'val' where individual bytes sequences, encoded in standard or
|
||||
// URL-safe base64, 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))
|
||||
|
||||
+2
-1
@@ -134,7 +134,8 @@ func DefaultHTTPErrorHandler(ctx context.Context, mux *ServeMux, marshaler Marsh
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
if s.Code() == codes.Unauthenticated {
|
||||
w.Header().Set("WWW-Authenticate", s.Message())
|
||||
// Canonical spelling, so Header.Set does not have to build one.
|
||||
w.Header().Set("Www-Authenticate", s.Message())
|
||||
}
|
||||
|
||||
buf, merr := marshaler.Marshal(respRw)
|
||||
|
||||
+52
-24
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
@@ -65,14 +66,16 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
|
||||
}
|
||||
|
||||
if isProtobufAnyMessage(fd.Message()) && !fd.IsList() {
|
||||
_, hasTypeField := v.(map[string]interface{})["@type"]
|
||||
if hasTypeField {
|
||||
queue = append(queue, fieldMaskPathItem{path: k})
|
||||
continue
|
||||
} else {
|
||||
vm, _ := v.(map[string]interface{})
|
||||
if _, hasTypeField := vm["@type"]; !hasTypeField {
|
||||
return nil, fmt.Errorf("could not find field @type in %q in message %q", k, item.msg.Descriptor().FullName())
|
||||
}
|
||||
|
||||
newPath := string(fd.FullName().Name())
|
||||
if item.path != "" {
|
||||
newPath = item.path + "." + newPath
|
||||
}
|
||||
queue = append(queue, fieldMaskPathItem{path: newPath})
|
||||
continue
|
||||
}
|
||||
|
||||
child := fieldMaskPathItem{
|
||||
@@ -96,10 +99,10 @@ func FieldMaskFromRequestBody(r io.Reader, msg proto.Message) (*field_mask.Field
|
||||
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
|
||||
// otherwise, it's a leaf node (an empty object counts as one) so
|
||||
// print its path. The root has no path: an empty body such as {}
|
||||
// sets nothing, and an empty path is not a valid FieldMask path.
|
||||
fm.Paths = append(fm.Paths, item.path)
|
||||
}
|
||||
}
|
||||
@@ -126,30 +129,55 @@ func isDynamicProtoMessage(md protoreflect.MessageDescriptor) bool {
|
||||
// passed in name and json value.
|
||||
func buildPathsBlindly(name string, in interface{}) []string {
|
||||
m, ok := in.(map[string]interface{})
|
||||
if !ok {
|
||||
if !ok || len(m) == 0 {
|
||||
return []string{name}
|
||||
}
|
||||
|
||||
// A google.protobuf.Struct/Value field carries arbitrary client JSON, so
|
||||
// its nesting depth is attacker controlled. Keep each queue entry pointing
|
||||
// at its parent and its own segment rather than carrying the full path
|
||||
// string, so a path is concatenated once at the leaf (O(depth)) instead of
|
||||
// rebuilding the growing prefix at every level (O(depth^2)). A deeply
|
||||
// nested object otherwise makes this allocate quadratically in the depth
|
||||
// while producing only a handful of paths.
|
||||
type pathNode struct {
|
||||
parent *pathNode
|
||||
segment string
|
||||
}
|
||||
type queueItem struct {
|
||||
path *pathNode
|
||||
node map[string]any
|
||||
}
|
||||
|
||||
var paths []string
|
||||
queue := []fieldMaskPathItem{{path: name, node: m}}
|
||||
queue := []queueItem{{path: &pathNode{segment: 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)
|
||||
for k, v := range cur.node {
|
||||
child := &pathNode{parent: cur.path, segment: k}
|
||||
if mi, ok := v.(map[string]any); ok && len(mi) > 0 {
|
||||
queue = append(queue, queueItem{path: child, node: mi})
|
||||
continue
|
||||
}
|
||||
// No populated object remains, so there are no more levels to
|
||||
// descend. Walk back to the root to materialize the path once.
|
||||
var segments []string
|
||||
n := 0
|
||||
for p := child; p != nil; p = p.parent {
|
||||
segments = append(segments, p.segment)
|
||||
n += len(p.segment) + 1
|
||||
}
|
||||
var b strings.Builder
|
||||
b.Grow(n - 1)
|
||||
for i := len(segments) - 1; i >= 0; i-- {
|
||||
b.WriteString(segments[i])
|
||||
if i > 0 {
|
||||
b.WriteByte('.')
|
||||
}
|
||||
}
|
||||
paths = append(paths, b.String())
|
||||
}
|
||||
}
|
||||
return paths
|
||||
|
||||
+4
-1
@@ -210,7 +210,10 @@ func ForwardResponseMessage(ctx context.Context, mux *ServeMux, marshaler Marsha
|
||||
}
|
||||
|
||||
func requestAcceptsTrailers(req *http.Request) bool {
|
||||
te := req.Header.Get("TE")
|
||||
// "Te", not "TE": Header.Get canonicalises the key it is given, and a key that is already
|
||||
// canonical is returned as is, while any other spelling costs an allocated copy on every
|
||||
// call. This one runs once per response.
|
||||
te := req.Header.Get("Te")
|
||||
return strings.Contains(strings.ToLower(te), "trailers")
|
||||
}
|
||||
|
||||
|
||||
+99
-3
@@ -5,11 +5,13 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
|
||||
"google.golang.org/protobuf/encoding/protojson"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
)
|
||||
|
||||
// JSONPb is a Marshaler which marshals/unmarshals into/from JSON
|
||||
@@ -30,6 +32,21 @@ func (*JSONPb) ContentType(_ interface{}) string {
|
||||
|
||||
// Marshal marshals "v" into JSON.
|
||||
func (j *JSONPb) Marshal(v interface{}) ([]byte, error) {
|
||||
if p, ok := v.(proto.Message); ok {
|
||||
// protojson already returns a freshly allocated slice that the caller owns, so
|
||||
// routing it through a bytes.Buffer only added an allocation and a copy of the
|
||||
// whole message per call. Every unary response goes through here.
|
||||
//
|
||||
// The error is returned with a nil slice rather than whatever protojson produced
|
||||
// alongside it, matching what the bytes.Buffer path did: marshalTo returned before
|
||||
// writing anything, so a failed Marshal never handed back partial output.
|
||||
b, err := j.MarshalOptions.Marshal(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := j.marshalTo(&buf, v); err != nil {
|
||||
return nil, err
|
||||
@@ -251,18 +268,36 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
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 {
|
||||
var raw json.RawMessage
|
||||
if err := d.Decode(&raw); err != nil {
|
||||
return err
|
||||
}
|
||||
m := make(map[string]*json.RawMessage)
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return err
|
||||
}
|
||||
// encoding/json keeps the last value of a repeated key, while protojson
|
||||
// rejects a duplicate map key, also when two spellings convert to the
|
||||
// same key (e.g. "1" and "01"). Reject both here too.
|
||||
if k, ok := duplicateObjectKey(raw); ok {
|
||||
return fmt.Errorf("duplicate map key %q", k)
|
||||
}
|
||||
seen := make(map[any]struct{}, len(m))
|
||||
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]
|
||||
if _, ok := seen[bk.Interface()]; ok {
|
||||
return fmt.Errorf("duplicate map key %q", k)
|
||||
}
|
||||
seen[bk.Interface()] = struct{}{}
|
||||
bv := reflect.New(rv.Type().Elem())
|
||||
if v == nil {
|
||||
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
|
||||
return err
|
||||
}
|
||||
null := json.RawMessage("null")
|
||||
v = &null
|
||||
}
|
||||
@@ -293,6 +328,11 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
rv.Set(reflect.MakeSlice(rv.Type(), 0, 0))
|
||||
}
|
||||
for _, item := range sl {
|
||||
if string(item) == "null" {
|
||||
if err := rejectNullEnumItem(rv.Type().Elem()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
bv := reflect.New(rv.Type().Elem())
|
||||
if err := unmarshalJSONPb([]byte(item), unmarshaler, bv.Interface()); err != nil {
|
||||
return err
|
||||
@@ -308,11 +348,30 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
}
|
||||
switch v := repr.(type) {
|
||||
case string:
|
||||
// TODO(yugui) Should use proto.StructProperties?
|
||||
// protojson writes enums by name, so accept the name here too.
|
||||
if e, ok := rv.Interface().(protoreflect.Enum); ok {
|
||||
if ev := e.Descriptor().Values().ByName(protoreflect.Name(v)); ev != nil {
|
||||
rv.SetInt(int64(ev.Number()))
|
||||
return nil
|
||||
}
|
||||
if unmarshaler.DiscardUnknown {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid value %q for enum %s", v, e.Descriptor().FullName())
|
||||
}
|
||||
return fmt.Errorf("unmarshaling of symbolic enum %q not supported: %T", repr, rv.Interface())
|
||||
case float64:
|
||||
// Enum values are int32 on the wire. A fractional or out-of-range
|
||||
// number would otherwise be silently truncated/wrapped into a bogus
|
||||
// enum here, unlike protojson which rejects it, so reject it too.
|
||||
if v != math.Trunc(v) || v < math.MinInt32 || v > math.MaxInt32 {
|
||||
return fmt.Errorf("%v is not a valid value for enum %T", repr, rv.Interface())
|
||||
}
|
||||
rv.Set(reflect.ValueOf(int32(v)).Convert(rv.Type()))
|
||||
return nil
|
||||
case nil:
|
||||
// protojson leaves a null enum field unset.
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("cannot assign %#v into Go type %T", repr, rv.Interface())
|
||||
}
|
||||
@@ -320,6 +379,43 @@ func decodeNonProtoField(d *json.Decoder, unmarshaler protojson.UnmarshalOptions
|
||||
return d.Decode(v)
|
||||
}
|
||||
|
||||
// rejectNullEnumItem returns an error when t is an enum other than
|
||||
// google.protobuf.NullValue. protojson leaves a null enum field unset, but
|
||||
// rejects null as a list item or map value of such an enum.
|
||||
func rejectNullEnumItem(t reflect.Type) error {
|
||||
e, ok := reflect.Zero(t).Interface().(protoreflect.Enum)
|
||||
if !ok || e.Descriptor().FullName() == "google.protobuf.NullValue" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid value null for enum %s", e.Descriptor().FullName())
|
||||
}
|
||||
|
||||
// duplicateObjectKey returns the first key that appears more than once in the
|
||||
// JSON object in data.
|
||||
func duplicateObjectKey(data []byte) (string, bool) {
|
||||
d := json.NewDecoder(bytes.NewReader(data))
|
||||
if t, err := d.Token(); err != nil || t != json.Delim('{') {
|
||||
return "", false
|
||||
}
|
||||
seen := make(map[string]struct{})
|
||||
for d.More() {
|
||||
t, err := d.Token()
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
k, _ := t.(string)
|
||||
if _, ok := seen[k]; ok {
|
||||
return k, true
|
||||
}
|
||||
seen[k] = struct{}{}
|
||||
var v json.RawMessage
|
||||
if err := d.Decode(&v); err != nil {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
type protoEnum interface {
|
||||
fmt.Stringer
|
||||
EnumDescriptor() ([]byte, []int)
|
||||
|
||||
+7
@@ -40,6 +40,13 @@ func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// ReadAll drains the reader, so a call with nothing left to read has
|
||||
// to report io.EOF like the other decoders. Otherwise it decodes an
|
||||
// empty message every time, and a loop decoding until io.EOF, such as
|
||||
// the generated client streaming handlers, never terminates.
|
||||
if len(buffer) == 0 {
|
||||
return io.EOF
|
||||
}
|
||||
return marshaller.Unmarshal(buffer, value)
|
||||
})
|
||||
}
|
||||
|
||||
+12
@@ -44,6 +44,18 @@ func MarshalerForRequest(mux *ServeMux, r *http.Request) (inbound Marshaler, out
|
||||
}
|
||||
|
||||
for _, contentTypeVal := range r.Header[contentTypeHeader] {
|
||||
// A header that is already exactly a registered media type -- "application/json",
|
||||
// which is what clients send -- needs no parsing. mime.ParseMediaType allocates a
|
||||
// parameter map even when the value carries no parameters, and it would return this
|
||||
// value unchanged, so the lookup below would be the same one.
|
||||
//
|
||||
// This is also what the Accept loop above already does: the registry is keyed by the
|
||||
// strings passed to WithMarshalerOption, and that loop matches the header value
|
||||
// against them directly.
|
||||
if m, ok := mux.marshalers.mimeMap[contentTypeVal]; ok {
|
||||
inbound = m
|
||||
break
|
||||
}
|
||||
contentType, _, err := mime.ParseMediaType(contentTypeVal)
|
||||
if err != nil {
|
||||
grpclog.Errorf("Failed to parse Content-Type %s: %v", contentTypeVal, err)
|
||||
|
||||
+132
-27
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"regexp"
|
||||
@@ -44,7 +45,9 @@ const (
|
||||
UnescapingModeDefault = UnescapingModeLegacy
|
||||
)
|
||||
|
||||
var encodedPathSplitter = regexp.MustCompile("(/|%2F)")
|
||||
// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an
|
||||
// escaped path separator has to be recognized in either spelling.
|
||||
var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])")
|
||||
|
||||
// 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)
|
||||
@@ -75,6 +78,7 @@ type ServeMux struct {
|
||||
unescapingMode UnescapingMode
|
||||
writeContentLength bool
|
||||
disableChunkedEncoding bool
|
||||
strictDeepWildcard bool
|
||||
}
|
||||
|
||||
// ServeMuxOption is an option that can be given to a ServeMux on construction.
|
||||
@@ -137,6 +141,19 @@ func WithDisableChunkedEncoding() ServeMuxOption {
|
||||
}
|
||||
}
|
||||
|
||||
// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least
|
||||
// one path segment when preceded by another segment. For example,
|
||||
// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still
|
||||
// provides an empty segment, so "/v3/files/" continues to match.
|
||||
//
|
||||
// This option applies to all patterns registered with the ServeMux, including
|
||||
// generated routes and routes registered with HandlePath.
|
||||
func WithStrictDeepWildcardMatching() ServeMuxOption {
|
||||
return func(mux *ServeMux) {
|
||||
mux.strictDeepWildcard = 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.
|
||||
@@ -151,24 +168,55 @@ 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.
|
||||
//
|
||||
// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the
|
||||
// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an
|
||||
// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the
|
||||
// WithLegacyHeaderMatching option, to keep forwarding those headers.
|
||||
func DefaultHeaderMatcher(key string) (string, bool) {
|
||||
switch key = textproto.CanonicalMIMEHeaderKey(key); {
|
||||
case isPermanentHTTPHeader(key):
|
||||
if key = textproto.CanonicalMIMEHeaderKey(key); isPermanentHTTPHeader(key) {
|
||||
return MetadataPrefix + key, true
|
||||
case strings.HasPrefix(key, MetadataHeaderPrefix):
|
||||
return key[len(MetadataHeaderPrefix):], true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the
|
||||
// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped
|
||||
// to gRPC metadata after removing the prefix 'Grpc-Metadata-'.
|
||||
//
|
||||
// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for
|
||||
// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway.
|
||||
func LegacyHeaderMatcher(key string) (string, bool) {
|
||||
switch key = textproto.CanonicalMIMEHeaderKey(key); {
|
||||
case isPermanentHTTPHeader(key):
|
||||
return MetadataPrefix + key, true
|
||||
case strings.HasPrefix(key, MetadataHeaderPrefix):
|
||||
mdKey := key[len(MetadataHeaderPrefix):]
|
||||
// The grpcgateway- namespace is reserved for permanent HTTP headers the
|
||||
// gateway maps itself, so refuse to forward a Grpc-Metadata- header that
|
||||
// strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client
|
||||
// inject a value indistinguishable from the gateway-set grpcgateway-host.
|
||||
if strings.HasPrefix(strings.ToLower(mdKey), MetadataPrefix) {
|
||||
return "", false
|
||||
}
|
||||
return mdKey, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header
|
||||
// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again.
|
||||
func WithLegacyHeaderMatching() ServeMuxOption {
|
||||
return WithIncomingHeaderMatcher(LegacyHeaderMatcher)
|
||||
}
|
||||
|
||||
func defaultOutgoingHeaderMatcher(key string) (string, bool) {
|
||||
return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true
|
||||
return MetadataHeaderPrefix + key, true
|
||||
}
|
||||
|
||||
func defaultOutgoingTrailerMatcher(key string) (string, bool) {
|
||||
return fmt.Sprintf("%s%s", MetadataTrailerPrefix, key), true
|
||||
return MetadataTrailerPrefix + key, true
|
||||
}
|
||||
|
||||
// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.
|
||||
@@ -376,15 +424,28 @@ func NewServeMux(opts ...ServeMuxOption) *ServeMux {
|
||||
serveMux.outgoingTrailerMatcher = defaultOutgoingTrailerMatcher
|
||||
}
|
||||
|
||||
// Options such as WithHealthEndpointAt register handlers while the options
|
||||
// are still being applied, so they were wrapped with only the middlewares
|
||||
// configured before them. Rewrap them now that all middlewares are known.
|
||||
if len(serveMux.middlewares) > 0 {
|
||||
chain := chainMiddlewares(serveMux.middlewares)
|
||||
for _, handlers := range serveMux.handlers {
|
||||
for i := range handlers {
|
||||
handlers[i].h = chain(handlers[i].raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return serveMux
|
||||
}
|
||||
|
||||
// Handle associates "h" to the pair of HTTP method and path pattern.
|
||||
func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {
|
||||
raw := h
|
||||
if len(s.middlewares) > 0 {
|
||||
h = chainMiddlewares(s.middlewares)(h)
|
||||
}
|
||||
s.handlers[meth] = append([]handler{{pat: pat, h: h}}, s.handlers[meth]...)
|
||||
s.handlers[meth] = append([]handler{{pat: pat, h: h, raw: raw}}, s.handlers[meth]...)
|
||||
}
|
||||
|
||||
// HandlePath allows users to configure custom path handlers.
|
||||
@@ -415,11 +476,22 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// TODO(v3): remove UnescapingModeLegacy
|
||||
if s.unescapingMode != UnescapingModeLegacy && r.URL.RawPath != "" {
|
||||
path = r.URL.RawPath
|
||||
unescapingMode := s.unescapingMode
|
||||
if unescapingMode != UnescapingModeLegacy {
|
||||
if r.URL.RawPath != "" {
|
||||
path = r.URL.RawPath
|
||||
} else {
|
||||
// net/url only sets RawPath when the request path is not in its
|
||||
// default encoding. Without it, Path is all there is and it has
|
||||
// already been unescaped once, so unescaping it again while matching
|
||||
// would decode a sequence like %252F twice.
|
||||
unescapingMode = UnescapingModeLegacy
|
||||
}
|
||||
}
|
||||
|
||||
if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && !s.disableHTTPMethodOverride && s.isPathLengthFallback(r) {
|
||||
// "X-Http-Method-Override" is the canonical spelling; Header.Get allocates a
|
||||
// canonicalised copy of any other, and this lookup happens on every request.
|
||||
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())
|
||||
@@ -434,7 +506,7 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// 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 {
|
||||
if unescapingMode == UnescapingModeAllCharacters {
|
||||
pathComponents = encodedPathSplitter.Split(path[1:], -1)
|
||||
} else {
|
||||
pathComponents = strings.Split(path[1:], "/")
|
||||
@@ -460,20 +532,33 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
idx = len(lastPathComponent) - len(patVerb) - 1
|
||||
}
|
||||
if idx == 0 {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
s.routingErrorHandler(ctx, s, outboundMarshaler, w, r, http.StatusNotFound)
|
||||
return
|
||||
// The last component is the bare verb with nothing before it,
|
||||
// which this pattern cannot match. Other patterns still might, so
|
||||
// move on rather than ending the search with a 404.
|
||||
continue
|
||||
}
|
||||
|
||||
comps := make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
|
||||
// Only copy the components when the verb has to be split off the last
|
||||
// one. MatchAndEscape never mutates its input, so sharing the slice
|
||||
// across handlers is safe, and copying it per handler otherwise costs
|
||||
// len(pathComponents) allocations for every registered pattern.
|
||||
comps := pathComponents
|
||||
if idx > 0 {
|
||||
comps = make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
|
||||
}
|
||||
|
||||
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
|
||||
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
|
||||
if err != nil {
|
||||
// ErrNotMatch is returned once for every registered pattern the request does not
|
||||
// match, so it is by far the most common error reaching this branch. Checking it
|
||||
// first keeps errors.As off that path: its target parameter is an any, so &mse is
|
||||
// boxed onto the heap on every call -- one allocation per route a request did not
|
||||
// match, which grows with the number of registered routes.
|
||||
if errors.Is(err, ErrNotMatch) {
|
||||
continue
|
||||
}
|
||||
var mse MalformedSequenceError
|
||||
if ok := errors.As(err, &mse); ok {
|
||||
_, outboundMarshaler := MarshalerForRequest(s, r)
|
||||
@@ -495,11 +580,24 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// 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 {
|
||||
// GET is tried first when the request is subject to path length fallback:
|
||||
// map iteration order is random, and a match for another method would
|
||||
// otherwise return 405 before the GET handler is reached.
|
||||
methods := make([]string, 0, len(s.handlers))
|
||||
if s.isPathLengthFallback(r) {
|
||||
methods = append(methods, http.MethodGet)
|
||||
}
|
||||
for m := range s.handlers {
|
||||
if m == http.MethodGet && s.isPathLengthFallback(r) {
|
||||
continue
|
||||
}
|
||||
methods = append(methods, m)
|
||||
}
|
||||
for _, m := range methods {
|
||||
if m == r.Method {
|
||||
continue
|
||||
}
|
||||
for _, h := range handlers {
|
||||
for _, h := range s.handlers[m] {
|
||||
var verb string
|
||||
patVerb := h.pat.Verb()
|
||||
|
||||
@@ -508,14 +606,14 @@ func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
idx = len(lastPathComponent) - len(patVerb) - 1
|
||||
}
|
||||
|
||||
comps := make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
|
||||
comps := pathComponents
|
||||
if idx > 0 {
|
||||
comps = make([]string, len(pathComponents))
|
||||
copy(comps, pathComponents)
|
||||
comps[len(comps)-1], verb = lastPathComponent[:idx], lastPathComponent[idx+1:]
|
||||
}
|
||||
|
||||
pathParams, err := h.pat.MatchAndEscape(comps, verb, s.unescapingMode)
|
||||
pathParams, err := h.pat.matchAndEscape(comps, verb, unescapingMode, s.strictDeepWildcard)
|
||||
if err != nil {
|
||||
var mse MalformedSequenceError
|
||||
if ok := errors.As(err, &mse); ok {
|
||||
@@ -558,12 +656,19 @@ func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.Resp
|
||||
}
|
||||
|
||||
func (s *ServeMux) isPathLengthFallback(r *http.Request) bool {
|
||||
return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded"
|
||||
if s.disablePathLengthFallback || r.Method != http.MethodPost {
|
||||
return false
|
||||
}
|
||||
// Like net/http's ParseForm, ignore parameters such as charset.
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
return err == nil && mediaType == "application/x-www-form-urlencoded"
|
||||
}
|
||||
|
||||
type handler struct {
|
||||
pat Pattern
|
||||
h HandlerFunc
|
||||
// raw is h before middlewares were applied.
|
||||
raw HandlerFunc
|
||||
}
|
||||
|
||||
func (s *ServeMux) handleHandler(h handler, w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
|
||||
|
||||
+83
-5
@@ -26,6 +26,9 @@ func (e MalformedSequenceError) Error() string {
|
||||
type op struct {
|
||||
code utilities.OpCode
|
||||
operand int
|
||||
// multisegment is set on an OpPush that is one segment of a variable
|
||||
// spanning several segments, such as the "*" in {name=shelves/*}.
|
||||
multisegment bool
|
||||
}
|
||||
|
||||
// Pattern is a template pattern of http request paths defined in
|
||||
@@ -43,6 +46,20 @@ type Pattern struct {
|
||||
tailLen int
|
||||
// verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part.
|
||||
verb string
|
||||
// strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one
|
||||
// remaining path component.
|
||||
strictDeepWildcard bool
|
||||
}
|
||||
|
||||
// PatternOpt configures optional behavior of a Pattern.
|
||||
type PatternOpt func(*Pattern)
|
||||
|
||||
// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another
|
||||
// segment refuse to match zero path segments. For example, "/v3/files/{path=**}"
|
||||
// will not match "/v3/files". A bare "**" with nothing preceding it still matches
|
||||
// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
|
||||
func WithStrictDeepWildcard() PatternOpt {
|
||||
return func(p *Pattern) { p.strictDeepWildcard = true }
|
||||
}
|
||||
|
||||
// NewPattern returns a new Pattern from the given definition values.
|
||||
@@ -51,6 +68,12 @@ type Pattern struct {
|
||||
// "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) {
|
||||
return NewPatternWithOptions(version, ops, pool, verb)
|
||||
}
|
||||
|
||||
// NewPatternWithOptions is like NewPattern but additionally accepts options that modify
|
||||
// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard.
|
||||
func NewPatternWithOptions(version int, ops []int, pool []string, verb string, opts ...PatternOpt) (Pattern, error) {
|
||||
if version != 1 {
|
||||
grpclog.Errorf("unsupported version: %d", version)
|
||||
return Pattern{}, ErrInvalidPattern
|
||||
@@ -106,6 +129,15 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er
|
||||
return Pattern{}, ErrInvalidPattern
|
||||
}
|
||||
stack++
|
||||
// The segments of a variable are the ops pushed right before its
|
||||
// OpConcatN, so these are the ones of a multi-segment variable.
|
||||
if op.operand > 1 {
|
||||
for j := len(typedOps) - op.operand; j < len(typedOps); j++ {
|
||||
if typedOps[j].code == utilities.OpPush {
|
||||
typedOps[j].multisegment = true
|
||||
}
|
||||
}
|
||||
}
|
||||
case utilities.OpCapture:
|
||||
if op.operand < 0 || len(pool) <= op.operand {
|
||||
grpclog.Errorf("variable name index out of bound: %d", op.operand)
|
||||
@@ -129,14 +161,18 @@ func NewPattern(version int, ops []int, pool []string, verb string) (Pattern, er
|
||||
}
|
||||
typedOps = append(typedOps, op)
|
||||
}
|
||||
return Pattern{
|
||||
pat := Pattern{
|
||||
ops: typedOps,
|
||||
pool: pool,
|
||||
vars: vars,
|
||||
stacksize: maxstack,
|
||||
tailLen: tailLen,
|
||||
verb: verb,
|
||||
}, nil
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(&pat)
|
||||
}
|
||||
return pat, nil
|
||||
}
|
||||
|
||||
// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization.
|
||||
@@ -152,6 +188,10 @@ func MustPattern(p Pattern, err error) 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) {
|
||||
return p.matchAndEscape(components, verb, unescapingMode, false)
|
||||
}
|
||||
|
||||
func (p Pattern) matchAndEscape(components []string, verb string, unescapingMode UnescapingMode, strictDeepWildcard bool) (map[string]string, error) {
|
||||
if p.verb != verb {
|
||||
if p.verb != "" {
|
||||
return nil, ErrNotMatch
|
||||
@@ -165,8 +205,29 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
|
||||
}
|
||||
|
||||
var pos int
|
||||
stack := make([]string, 0, p.stacksize)
|
||||
captured := make([]string, len(p.vars))
|
||||
|
||||
// Scratch space for the match. Neither backing array escapes -- only the individual
|
||||
// strings they hold are copied into the returned bindings -- so fixed-size arrays keep
|
||||
// both off the heap for the patterns generated code registers, where the stack size and
|
||||
// the variable count are single digits.
|
||||
//
|
||||
// This matters beyond one allocation each: ServeHTTP calls matchAndEscape once per
|
||||
// registered pattern until one matches, and both allocations happened before the
|
||||
// non-match return below, so a request paid for them once for every route it did not
|
||||
// match. With a few dozen routes registered that was the largest single source of
|
||||
// allocations in routing.
|
||||
var stackArr, capturedArr [8]string
|
||||
stack := stackArr[:0]
|
||||
if p.stacksize > len(stackArr) {
|
||||
stack = make([]string, 0, p.stacksize)
|
||||
}
|
||||
var captured []string
|
||||
if n := len(p.vars); n <= len(capturedArr) {
|
||||
captured = capturedArr[:n]
|
||||
} else {
|
||||
captured = make([]string, n)
|
||||
}
|
||||
|
||||
l := len(components)
|
||||
for _, op := range p.ops {
|
||||
var err error
|
||||
@@ -184,7 +245,14 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
} else if op.code == utilities.OpPush {
|
||||
if c, err = unescape(c, unescapingMode, false); err != nil {
|
||||
// google.api.http decodes a variable spanning several segments
|
||||
// "except %2F and %2f", so a "*" in it can't add a path separator
|
||||
// to the bound value. Other escapes are decoded as for {var}.
|
||||
mode := unescapingMode
|
||||
if op.multisegment && mode == UnescapingModeAllExceptReserved {
|
||||
mode = UnescapingModeAllExceptSlash
|
||||
}
|
||||
if c, err = unescape(c, mode, op.multisegment); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -196,6 +264,16 @@ func (p Pattern) MatchAndEscape(components []string, verb string, unescapingMode
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
end -= p.tailLen
|
||||
if (p.strictDeepWildcard || strictDeepWildcard) && pos > 0 && pos == end {
|
||||
// A deep wildcard ("**") is allowed to match zero path segments when it is
|
||||
// the first thing being matched in the pattern (pos == 0). But once a literal
|
||||
// or variable segment has already consumed a component, "**" needs the request
|
||||
// path to continue past that segment — it cannot succeed with nothing left to
|
||||
// consume at all (though an empty trailing segment, e.g. from a trailing slash,
|
||||
// still counts as a real component and is fine).
|
||||
// See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.
|
||||
return nil, ErrNotMatch
|
||||
}
|
||||
c := strings.Join(components[pos:end], "/")
|
||||
if c, err = unescape(c, unescapingMode, true); err != nil {
|
||||
return nil, err
|
||||
|
||||
+145
-17
@@ -4,7 +4,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -16,13 +15,41 @@ import (
|
||||
"google.golang.org/protobuf/reflect/protoreflect"
|
||||
"google.golang.org/protobuf/reflect/protoregistry"
|
||||
"google.golang.org/protobuf/types/known/durationpb"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
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(`^(.*)\[(.*)\]$`)
|
||||
// splitMapKey splits a query parameter name of the form "field[key]" into the part before the
|
||||
// bracket and the key inside it, reporting whether the name has that shape at all.
|
||||
//
|
||||
// This replaces a FindStringSubmatch against `^(.*)\[(.*)\]$`, which ran for every query
|
||||
// parameter and cost two allocations each -- the submatch slice and the backtracker's state --
|
||||
// to answer a question that is two index operations. The returned strings are slices of the
|
||||
// caller's key, so nothing is copied; the caller rebuilds "[key]" as key[len(prefix):] rather
|
||||
// than concatenating it back together.
|
||||
//
|
||||
// The regexp is matched exactly, including two details worth spelling out:
|
||||
//
|
||||
// - The first group is greedy, so the bracket that counts is the last one before the final
|
||||
// "]". "a[b]c]" splits into "a" and "b]c", which is what LastIndexByte over everything but
|
||||
// the final byte finds.
|
||||
// - Go's regexp does not let "." match a newline and anchors ^ and $ at the ends of the text,
|
||||
// so a key containing a newline could never match the pattern no matter where the brackets
|
||||
// sat. The explicit newline check keeps that, rather than quietly starting to treat
|
||||
// "a\n[b]" as a map key.
|
||||
func splitMapKey(key string) (prefix, inner string, ok bool) {
|
||||
if len(key) < 2 || key[len(key)-1] != ']' || strings.IndexByte(key, '\n') >= 0 {
|
||||
return "", "", false
|
||||
}
|
||||
open := strings.LastIndexByte(key[:len(key)-1], '[')
|
||||
if open < 0 {
|
||||
return "", "", false
|
||||
}
|
||||
return key[:open], key[open+1 : len(key)-1], true
|
||||
}
|
||||
|
||||
var currentQueryParser QueryParameterParser = &DefaultQueryParser{}
|
||||
|
||||
@@ -44,30 +71,67 @@ func PopulateQueryParameters(msg proto.Message, values url.Values, filter *utili
|
||||
type DefaultQueryParser struct{}
|
||||
|
||||
// Parse populates "values" into "msg".
|
||||
// A value is ignored if its key starts with one of the elements in "filter".
|
||||
// A value is ignored if its key starts with one of the elements in "filter",
|
||||
// or names a field that contains one of them.
|
||||
func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *utilities.DoubleArray) error {
|
||||
// A field is addressable by both its proto name and its JSON name, so two
|
||||
// keys can set the same one. Record which fields have been set and refuse a
|
||||
// second key for a field, the way protojson refuses a duplicate field in a
|
||||
// body, instead of letting map iteration order pick the value that survives.
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for key, values := range values {
|
||||
if match := valuesKeyRegexp.FindStringSubmatch(key); len(match) == 3 {
|
||||
key = match[1]
|
||||
values = append([]string{match[2]}, values...)
|
||||
fieldKey, mapKey := key, ""
|
||||
if prefix, inner, ok := splitMapKey(key); ok {
|
||||
fieldKey, mapKey = prefix, key[len(prefix):]
|
||||
values = append([]string{inner}, values...)
|
||||
}
|
||||
|
||||
msgValue := msg.ProtoReflect()
|
||||
fieldPath := normalizeFieldPath(msgValue, strings.Split(key, "."))
|
||||
if filter.HasCommonPrefix(fieldPath) {
|
||||
fieldPath := normalizeFieldPath(msgValue, strings.Split(fieldKey, "."))
|
||||
if filter.HasCommonPrefix(fieldPath) || containsFilteredField(filter, fieldPath) {
|
||||
continue
|
||||
}
|
||||
if err := populateFieldValueFromPath(msgValue, fieldPath, values); err != nil {
|
||||
field := strings.Join(fieldPath, ".") + mapKey
|
||||
if _, ok := seen[field]; ok {
|
||||
return fmt.Errorf("duplicate field %q", field)
|
||||
}
|
||||
seen[field] = struct{}{}
|
||||
if err := populateFieldValueFromPath(msgValue, fieldPath, values, mapKey != ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// containsFilteredField reports whether fieldPath names a field that contains
|
||||
// one of the sequences in filter, such as "id" for a path parameter bound to
|
||||
// "id.value". Setting such a field from the query, which the parser can do for
|
||||
// well-known types like wrappers and timestamps, would replace the whole
|
||||
// message and with it the value already bound from the path or body.
|
||||
func containsFilteredField(filter *utilities.DoubleArray, fieldPath []string) bool {
|
||||
if len(filter.Base) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
var i int
|
||||
for _, t := range fieldPath {
|
||||
code, ok := filter.Encoding[t]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
j := filter.Base[i] + code
|
||||
if len(filter.Check) <= j || filter.Check[j] != i+1 {
|
||||
return false
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// 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})
|
||||
return populateFieldValueFromPath(msg.ProtoReflect(), fieldPath, []string{value}, false)
|
||||
}
|
||||
|
||||
func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []string {
|
||||
@@ -102,7 +166,7 @@ func normalizeFieldPath(msgValue protoreflect.Message, fieldPath []string) []str
|
||||
return newFieldPath
|
||||
}
|
||||
|
||||
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string) error {
|
||||
func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []string, values []string, hasMapKey bool) error {
|
||||
if len(fieldPath) < 1 {
|
||||
return errors.New("no field path")
|
||||
}
|
||||
@@ -149,6 +213,18 @@ func populateFieldValueFromPath(msgValue protoreflect.Message, fieldPath []strin
|
||||
msgValue = msgValue.Mutable(fieldDescriptor).Message()
|
||||
}
|
||||
|
||||
// A key using the map syntax (field[key]=value) must name a map field,
|
||||
// or a repeated field of key/value messages laid out like map entries.
|
||||
// Otherwise the bracket content would be bound as if it were a regular
|
||||
// value: appended as a phantom element of a repeated field, or counted
|
||||
// as a second value for a singular one.
|
||||
if hasMapKey && !fieldDescriptor.IsMap() {
|
||||
if isKeyValueList(fieldDescriptor) {
|
||||
return populateKeyValueListField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
|
||||
}
|
||||
return fmt.Errorf("field %q is not a map", fieldDescriptor.FullName().Name())
|
||||
}
|
||||
|
||||
switch {
|
||||
case fieldDescriptor.IsList():
|
||||
return populateRepeatedField(fieldDescriptor, msgValue.Mutable(fieldDescriptor).List(), values)
|
||||
@@ -205,6 +281,48 @@ func populateMapField(fieldDescriptor protoreflect.FieldDescriptor, mp protorefl
|
||||
return nil
|
||||
}
|
||||
|
||||
// isKeyValueList reports whether fieldDescriptor is a repeated message field
|
||||
// whose message has exactly a singular "key" and a singular "value" field.
|
||||
// Such a field is shaped like a map entry list, but can hold more than one
|
||||
// value for a key.
|
||||
func isKeyValueList(fieldDescriptor protoreflect.FieldDescriptor) bool {
|
||||
if !fieldDescriptor.IsList() || fieldDescriptor.Message() == nil {
|
||||
return false
|
||||
}
|
||||
fields := fieldDescriptor.Message().Fields()
|
||||
if fields.Len() != 2 {
|
||||
return false
|
||||
}
|
||||
key, value := fields.ByName("key"), fields.ByName("value")
|
||||
return key != nil && key.Cardinality() != protoreflect.Repeated &&
|
||||
value != nil && value.Cardinality() != protoreflect.Repeated
|
||||
}
|
||||
|
||||
// populateKeyValueListField appends one key/value message to list for each of
|
||||
// values[1:], all with the key values[0].
|
||||
func populateKeyValueListField(fieldDescriptor protoreflect.FieldDescriptor, list protoreflect.List, values []string) error {
|
||||
fields := fieldDescriptor.Message().Fields()
|
||||
keyField, valueField := fields.ByName("key"), fields.ByName("value")
|
||||
|
||||
key, err := parseField(keyField, values[0])
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing map key %q: %w", fieldDescriptor.FullName().Name(), err)
|
||||
}
|
||||
|
||||
for _, value := range values[1:] {
|
||||
v, err := parseField(valueField, value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parsing map value %q: %w", fieldDescriptor.FullName().Name(), err)
|
||||
}
|
||||
entry := list.NewElement()
|
||||
entry.Message().Set(keyField, key)
|
||||
entry.Message().Set(valueField, v)
|
||||
list.Append(entry)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (protoreflect.Value, error) {
|
||||
switch fieldDescriptor.Kind() {
|
||||
case protoreflect.BoolKind:
|
||||
@@ -224,7 +342,7 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
|
||||
// Look for enum by name
|
||||
v := enum.Descriptor().Values().ByName(protoreflect.Name(value))
|
||||
if v == nil {
|
||||
i, err := strconv.Atoi(value)
|
||||
i, err := strconv.ParseInt(value, 10, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, fmt.Errorf("%q is not a valid value", value)
|
||||
}
|
||||
@@ -259,13 +377,13 @@ func parseField(fieldDescriptor protoreflect.FieldDescriptor, value string) (pro
|
||||
}
|
||||
return protoreflect.ValueOfUint64(v), nil
|
||||
case protoreflect.FloatKind:
|
||||
v, err := strconv.ParseFloat(value, 32)
|
||||
v, err := 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)
|
||||
v, err := parseFloat(value, 64)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
@@ -305,13 +423,13 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
}
|
||||
msg = durationpb.New(d)
|
||||
case "google.protobuf.DoubleValue":
|
||||
v, err := strconv.ParseFloat(value, 64)
|
||||
v, err := parseFloat(value, 64)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
msg = wrapperspb.Double(v)
|
||||
case "google.protobuf.FloatValue":
|
||||
v, err := strconv.ParseFloat(value, 32)
|
||||
v, err := parseFloat(value, 32)
|
||||
if err != nil {
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
@@ -356,7 +474,9 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
msg = wrapperspb.Bytes(v)
|
||||
case "google.protobuf.FieldMask":
|
||||
fm := &field_mask.FieldMask{}
|
||||
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
|
||||
if value != "" {
|
||||
fm.Paths = append(fm.Paths, strings.Split(value, ",")...)
|
||||
}
|
||||
msg = fm
|
||||
case "google.protobuf.Value":
|
||||
var v structpb.Value
|
||||
@@ -370,6 +490,14 @@ func parseMessage(msgDescriptor protoreflect.MessageDescriptor, value string) (p
|
||||
return protoreflect.Value{}, err
|
||||
}
|
||||
msg = &v
|
||||
case "google.protobuf.Empty":
|
||||
// An Empty carries nothing, so the only thing the value can say is that the
|
||||
// field is present. Accept the two spellings of "no content" and reject
|
||||
// anything else, rather than silently ignoring it.
|
||||
if value != "" && value != "{}" {
|
||||
return protoreflect.Value{}, fmt.Errorf("expected an empty value or %q, got %q", "{}", value)
|
||||
}
|
||||
msg = &emptypb.Empty{}
|
||||
default:
|
||||
return protoreflect.Value{}, fmt.Errorf("unsupported message type: %q", string(msgDescriptor.FullName()))
|
||||
}
|
||||
|
||||
+12
-4
@@ -72,6 +72,7 @@ func (n node) children(seqs [][]int) []*node {
|
||||
if lastVal == seqs[i][n.col+1] {
|
||||
continue
|
||||
}
|
||||
lastVal = seqs[i][n.col+1]
|
||||
last.right = i
|
||||
last = &node{
|
||||
row: i,
|
||||
@@ -156,6 +157,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
|
||||
|
||||
var i int
|
||||
for _, t := range seq {
|
||||
// A sequence ending at this node is already a prefix of seq, even if
|
||||
// a longer sequence shares the path and the walk could carry on.
|
||||
if da.hasTerminator(i) {
|
||||
return true
|
||||
}
|
||||
code, ok := da.Encoding[t]
|
||||
if !ok {
|
||||
break
|
||||
@@ -166,9 +172,11 @@ func (da *DoubleArray) HasCommonPrefix(seq []string) bool {
|
||||
}
|
||||
i = j
|
||||
}
|
||||
return da.hasTerminator(i)
|
||||
}
|
||||
|
||||
// hasTerminator reports whether a sequence in the DoubleArray ends at node i.
|
||||
func (da *DoubleArray) hasTerminator(i int) bool {
|
||||
j := da.Base[i] + len(da.Encoding)
|
||||
if len(da.Check) <= j || da.Check[j] != i+1 {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
return j < len(da.Check) && da.Check[j] == i+1
|
||||
}
|
||||
+21
-1
@@ -22,6 +22,26 @@ _testmain.go
|
||||
*.exe
|
||||
|
||||
.envrc
|
||||
/.testdb
|
||||
|
||||
# Per-checkout development state: this checkout's allocated TCP ports, the values derived from
|
||||
# them, its decoded client certificates, and its own PostgreSQL/CockroachDB clusters. A git
|
||||
# worktree is the native equivalent of a second devcontainer instance, so this is instance-local
|
||||
# by definition -- never shared, never committed. See DEVELOPMENT.md.
|
||||
/.dev/
|
||||
|
||||
# port-tamer writes this checkout's allocation to .dev/ports.env (the --state-file every task
|
||||
# passes). These are where a bare `port-tamer` run at the repo root would put a stray second
|
||||
# allocation instead; ignored so it cannot be committed by accident.
|
||||
/.port-tamer.env
|
||||
/.port-tamer.env.lock
|
||||
|
||||
# Personal, machine-local mise overrides (mise.toml IS committed/shared). Git has no knowledge of
|
||||
# mise's conventions, so this must be ignored explicitly.
|
||||
/mise.local.toml
|
||||
|
||||
# Provisioned on demand with `rake references:setup`; never committed.
|
||||
/references/
|
||||
|
||||
.DS_Store
|
||||
|
||||
/.vscode
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Host dependencies only. Project tools and language runtimes belong in
|
||||
# mise.toml; scripts/setup-host installs mise itself when necessary.
|
||||
|
||||
# Server and client binaries for the checkout-local test matrix.
|
||||
brew "postgresql@14"
|
||||
brew "postgresql@15"
|
||||
brew "postgresql@16"
|
||||
brew "postgresql@17"
|
||||
brew "postgresql@18"
|
||||
|
||||
# mise compiles Ruby from source and links against these.
|
||||
brew "openssl@3"
|
||||
brew "readline"
|
||||
brew "libyaml"
|
||||
brew "gmp"
|
||||
+328
@@ -1,3 +1,331 @@
|
||||
# 5.13.0 (November 11, 2026)
|
||||
|
||||
This release adds automatic client certificate reloading and temporal precision metadata for `database/sql`.
|
||||
It also fixes a panic on malformed server responses, unsafe retries after connection failures, and range encoding.
|
||||
See Changes for client certificate configuration behavior that may affect existing applications.
|
||||
|
||||
## Security Fixes
|
||||
|
||||
* **Panic in `Rows.Values` on malformed server responses**
|
||||
([GHSA-w9rp-vfrh-q8vv](https://github.com/jackc/pgx/security/advisories/GHSA-w9rp-vfrh-q8vv)).
|
||||
A server response containing fewer row values than declared fields could cause an index-out-of-range panic in
|
||||
`Rows.Values`. It now returns an error and closes the rows when the counts differ, including when there are extra
|
||||
values, matching `Rows.Scan` validation.
|
||||
|
||||
## Features
|
||||
|
||||
* pgconn: reload client certificates and keys configured through `sslcert` and `sslkey` for each TLS certificate
|
||||
request, allowing new connections to pick up rotated credentials without recreating the configuration or
|
||||
restarting the application. Files are still validated during configuration parsing. Relative paths retain their
|
||||
parse-time directory, and reloads follow symlinks (Erin Shepherd)
|
||||
* stdlib: expose fractional seconds precision for `timestamp`, `timestamptz`, `time`, `timetz`, and `interval` through
|
||||
`ColumnTypePrecisionScale` and `database/sql.ColumnType.DecimalSize`. These return precision 0, the fractional
|
||||
seconds precision as scale, and `ok=true`. The scale defaults to 6 when no fractional seconds precision is declared;
|
||||
precision 0 means numeric precision is not applicable (Danny Xu)
|
||||
|
||||
## Changes
|
||||
|
||||
* pgconn: file-backed client certificates are no longer stored in the parsed `TLSConfig.Certificates` slice.
|
||||
Setting `TLSConfig.Certificates` (including a non-nil empty slice) or `TLSConfig.GetClientCertificate` overrides
|
||||
automatic reloading. Replacing `TLSConfig`, including with a direct `TLSConfig.Clone`, discards the file-backed
|
||||
certificate settings; use `pgconn.Config.Copy` to preserve them when copying a configuration. Certificate and key
|
||||
files must remain readable for subsequent TLS certificate requests. Encrypted keys reuse the password resolved
|
||||
during configuration parsing; `GetSSLPassword` is not called again on reload.
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
* pgconn: do not mark a connection-closed error encountered while receiving a response as safe to retry, since the
|
||||
request may already have reached the server. This prevents `database/sql` from automatically repeating a statement
|
||||
that may already have executed. The error still supports `errors.Is(err, pgconn.ErrConnClosed)` (Aayush Shah)
|
||||
* pgconn: skip sending a cancel request when a connection fails during startup, avoiding an unnecessary second
|
||||
connection attempt (felipe stival)
|
||||
* pgconn: accept unencrypted combined certificate/key PEM files with the certificate before the key, as well as
|
||||
key-first files (Erin Shepherd)
|
||||
* pgtype: encode `Range[any]` values returned by `RangeCodec.DecodeValue` and `Rows.Values` in both binary and text
|
||||
formats, allowing decoded ranges and multiranges to be reused as query arguments or in `CopyFrom` (waw666waw666)
|
||||
* stdlib: report `ok=false` for the precision and scale of unconstrained `numeric` columns instead of bogus values
|
||||
(Danny Xu)
|
||||
* stdlib: report `math.MaxInt64` for the lengths of unconstrained `varchar`, `bpchar`, and `varbit` columns instead of
|
||||
negative lengths (PerryLink)
|
||||
|
||||
## Documentation and Tests
|
||||
|
||||
* pgxpool: clarify that a zero `PingTimeout` lets a stalled health-check ping consume the acquiring caller's full
|
||||
deadline, and explain the tradeoffs of a positive timeout (dajiaohuang)
|
||||
* Correct the `AppendRows` / `RowToStructByName` benchmark to measure name-based rather than positional mapping
|
||||
(Samir)
|
||||
|
||||
# 5.12.0 (October 30, 2026)
|
||||
|
||||
This release fixes two security vulnerabilities with narrow triggering conditions but serious impact. Affected
|
||||
applications should upgrade to v5.12.0; see Security Fixes below.
|
||||
|
||||
It also adds batched transaction startup, client certificate policy controls, and per-query batch timing,
|
||||
and improves connection pool cancellation and type handling. Custom implementations
|
||||
of `BatchResults`, including mocks, must add the new `Tx` method.
|
||||
|
||||
## Security Fixes
|
||||
|
||||
* **SQL injection in simple-protocol batches**
|
||||
([GHSA-j38q-h3ph-jjpq](https://github.com/jackc/pgx/security/advisories/GHSA-j38q-h3ph-jjpq), high severity).
|
||||
In pgx v5 before v5.12.0, `SendBatch` using the non-default simple protocol could allow arbitrary SQL execution
|
||||
with the application's database privileges when a queued query ends in a `--` comment without a newline and the
|
||||
next query has an attacker-controlled string argument on its first line. Batched queries are now separated by
|
||||
a newline to end such comments. Extended-protocol modes are unaffected.
|
||||
Reported by [Igor Kupczyński (@igor-kupczynski)](https://github.com/igor-kupczynski).
|
||||
* **Bypass of `require_auth` and `channel_binding=require`**
|
||||
([GHSA-95fj-3fxw-g62g](https://github.com/jackc/pgx/security/advisories/GHSA-95fj-3fxw-g62g), high severity).
|
||||
In pgx v5.9.0 through v5.11.0, applications relying on these settings without verifying the server's identity
|
||||
with `sslmode=verify-full` (or equivalent TLS verification) could accept an impersonating server that skips
|
||||
authentication. The attacker could read queries and parameters and return fabricated results. pgx now enforces
|
||||
authentication completion and required channel binding before accepting the connection. This vulnerability does
|
||||
not bypass TLS server certificate verification.
|
||||
Reported by [@president-xd](https://github.com/president-xd).
|
||||
|
||||
## Features
|
||||
|
||||
* Add `Batch.BeginTx` and `BatchResults.Tx` to begin a transaction as the first query of a batch, saving the round
|
||||
trip for `BeginTx`. Call `Batch.BeginTx` before queuing any queries, consume the begin query's result first, and
|
||||
close the batch before using the transaction. With `pgxpool.Pool.SendBatch`, the connection remains acquired until
|
||||
the transaction is committed or rolled back. Add `FailedBatchResults` for wrappers that fail before sending a
|
||||
batch (Timo Furrer)
|
||||
* Add `TraceBatchQueryData.ReadStartTime` and per-query durations to `tracelog` batch query entries. These measure
|
||||
result consumption, including application time spent reading rows, rather than server execution alone
|
||||
(Yasser-Ameur)
|
||||
* pgconn: support the `sslcertmode` connection parameter, `PGSSLCERTMODE` environment variable, and
|
||||
`Config.SSLCertMode`. The default, `allow`, sends an available client certificate when requested; `disable`
|
||||
prevents sending one and skips loading certificate/key files; `require` fails unless the server requests and
|
||||
receives a certificate. `require` does not guarantee server-side certificate validation, disables TLS session
|
||||
resumption, and stops further host or TLS fallbacks when the certificate requirement fails (k-zshiba)
|
||||
* pgtype: add support for PostgreSQL 19's `oid8` and `oid8[]` (k-zshiba)
|
||||
|
||||
## Changes
|
||||
|
||||
* pgxpool: background attempts to satisfy `MinConns` and `MinIdleConns` now have a 60-second timeout, including
|
||||
connection hooks. Initial background connections preserve the constructor context's values but ignore its
|
||||
cancellation and deadline.
|
||||
* pgxpool: canceling `Acquire` during a health-check ping now returns promptly and lets a successful ping return
|
||||
the connection to the pool. The ping retains the caller's deadline and `PingTimeout`, with at most one additional
|
||||
minute to finish after cancellation (lazerg)
|
||||
* pgconn: on Windows, look for the default service file at `%APPDATA%\postgresql\.pg_service.conf`, matching libpq.
|
||||
Fall back to the previous home-directory location only when the APPDATA file is missing, or APPDATA is unset;
|
||||
other file errors no longer cause fallback (b84330808)
|
||||
|
||||
## Performance Improvements
|
||||
|
||||
* pgtype: add fast-path slice scan and encode plans for common primitive types (Andrew Suffield)
|
||||
* pgtype: reduce allocations when encoding numbers and times as text (Guillaume Malette)
|
||||
* stdlib: cache scan destination type classification on Go 1.27 (DublikuntMux)
|
||||
* Reuse the begin statement for standard transaction option combinations (Timo Furrer)
|
||||
|
||||
## Bug Fixes
|
||||
|
||||
* Fix `NamedArgs` and `StrictNamedArgs` rewriting parameters inside dollar-quoted strings, truncating queries
|
||||
containing U+FFFD (youdie006), and treating a trailing backslash as extending a SQL line comment. Fix the same
|
||||
line-comment handling in simple-protocol argument sanitization.
|
||||
* Preserve multidimensional array dimensions in `CopyFrom` (arminazimi)
|
||||
* Deduplicate shared type dependencies returned by `LoadTypes` (Grivn)
|
||||
* pgconn: preserve SCRAM passwords containing characters unassigned in Unicode 3.2, matching PostgreSQL's SASLprep
|
||||
behavior
|
||||
* pgconn: do not retain timeout errors in the background reader after a deadline has been cleared
|
||||
(Vitalii Cherepanov)
|
||||
* pgconn: normalize timeout errors after failed writes so context cancellation and deadline errors are reported
|
||||
consistently (lazerg)
|
||||
* pgconn: avoid a double-close panic when `OnPgError` closes the connection
|
||||
* pgtype: fix interval fractional-second parsing beyond microsecond precision, validate all fractional digits
|
||||
before rounding (Sasha Mitchell), and correctly encode `math.MinInt64` microseconds as text (spicysharkco)
|
||||
* pgtype: preserve delimiters inside quoted multirange bounds (Sueun Cho)
|
||||
* pgtype: handle SQL NULL in binary `ltree` scan plans without panicking (Januth Nimnal)
|
||||
* pgtype: preserve `xid8` values above `math.MaxInt64` when decoding for `sql.Scanner`, returning their decimal
|
||||
string representation instead of overflowing to a negative integer (k-zshiba)
|
||||
|
||||
# 5.11.0 (September 7, 2026)
|
||||
|
||||
This release adds direct PostgreSQL type scanning through `database/sql` on Go 1.27, improves compatibility with
|
||||
libpq connection strings and PostgreSQL date/time values, and includes further decoder hardening. See Changes for
|
||||
connection-string and date/time behavior changes that may affect existing applications.
|
||||
|
||||
## Features
|
||||
|
||||
* stdlib: support Go 1.27's `driver.RowsColumnScanner`, allowing PostgreSQL types such as arrays and ranges to be
|
||||
scanned directly into Go values without `pgtype.Map.SQLScanner`. Existing `database/sql` scalar conversions and
|
||||
`sql.Scanner` behavior are preserved. The minimum supported Go version remains 1.25.
|
||||
* Add `Rows.TypeMap` to expose the type map used to decode rows, including rows created by `RowsFromResultReader`
|
||||
that have no underlying `Conn`. Custom implementations of `Rows`, including mocks, must add this method.
|
||||
* pgconn: add `Config.MaxProtocolMessageBodyLen` to configure the maximum incoming protocol message body size
|
||||
(carter-ya)
|
||||
* pgconn: add `ErrReadOnlyConnection`, `ErrReadWriteConnection`, `ErrPrimaryConnection`, and `ErrStandbyConnection`
|
||||
sentinel errors for `target_session_attrs` validation, allowing callers to use `errors.Is` (Adrian-Stefan Mares)
|
||||
* pgxpool: accept `pool_ping_timeout` in connection strings to configure `Config.PingTimeout`. The default is zero;
|
||||
zero and negative durations mean no timeout (1991santhu)
|
||||
|
||||
## Changes
|
||||
|
||||
* Name-based row-to-struct mapping now matches explicit `db` tags case-insensitively, with exact matches taking
|
||||
precedence so tags can still distinguish quoted column names that differ only by case (AlisinaDevelo)
|
||||
* pgconn: resolve the OS user account only when no user is supplied by the connection string, environment, or service
|
||||
file, avoiding unnecessary account lookups and crashes in some restricted container environments. Home-directory
|
||||
defaults for password, service, and TLS files remain available independently of the account lookup. On Unix these
|
||||
now use `$HOME` rather than the OS account's home directory (Mohamed MAACHE)
|
||||
|
||||
* pgtype: `date`, `timestamp` and `timestamptz` text values are now parsed and written by a hand-written parser and
|
||||
encoder for PostgreSQL's ISO date/time format instead of `time.Parse` and `time.Format`. Go's layout language cannot
|
||||
express a variable-width year or the BC era, which is the root of the bugs below. The text scan path is roughly 2.5x
|
||||
faster for `timestamp` and `timestamptz`. Bug fixes:
|
||||
* `timestamp` and `timestamptz` no longer silently move February 29 of a BC leap year to March 1 when encoding.
|
||||
`time.Date(-4712, 2, 29, ...)` was written as `4713-03-01 BC` and is now written as `4713-02-29 BC`. This
|
||||
affected ordinary four-digit BC years, not only extended-range ones. `date` was never affected.
|
||||
* `timestamp` and `timestamptz` can now scan BC leap days. `4713-02-29 BC` previously failed with
|
||||
`day out of range`. `date` could already scan them.
|
||||
* Years past 9999 can now be scanned. `10000-01-02 03:04:05` previously failed to parse, so `timestamp` and
|
||||
`timestamptz` values at the high end of PostgreSQL's range were unreadable over the simple protocol and in any
|
||||
other text-format result.
|
||||
* `time.Time` arguments in the simple protocol now encode BC dates correctly, using the same timestamp encoder.
|
||||
* Fractional seconds beyond microsecond precision are rounded the way the server rounds them (round half to even,
|
||||
carrying into the rest of the value) instead of being kept at full precision. PostgreSQL never sends more than six
|
||||
fractional digits, so this only affects values from other sources.
|
||||
|
||||
Behavior changes:
|
||||
* `date` now rejects impossible dates instead of normalizing them. `2024-02-30` returned `2024-03-01` and
|
||||
`2024-13-01` returned `2025-01-01`; both are now errors. `timestamp` and `timestamptz` already rejected them.
|
||||
* All three types now reject values outside PostgreSQL's range for that type, in the binary format as well as the
|
||||
text format. PostgreSQL never sends out-of-range dates, so this only affects corrupt or hand-built input; the range
|
||||
is checked in both formats so that whether a value is accepted does not depend on `QueryExecMode`.
|
||||
`timestamptz` also rejects time zone displacements outside PostgreSQL's signed 32-bit seconds range, while accepting
|
||||
the wider offsets emitted for POSIX time zones, such as `+16`.
|
||||
* `timestamptz` values scanned from the text format are now returned in `time.Local`, or in `ScanLocation` when it is
|
||||
set, matching what the binary format has always returned. Previously the text path kept whatever location
|
||||
`time.Parse` derived from the offset the server sent, so the same value scanned in the two formats could report a
|
||||
different `Location()` and `Zone()`. The instant is unchanged, but everything that renders the location changes
|
||||
with it: `Timestamptz.MarshalJSON` now writes the client's offset rather than the server's, so a value the server
|
||||
sent as `+05:30` marshals as `2024-01-01T13:34:05-08:00` on a UTC-8 client instead of `2024-01-02T03:04:05+05:30`,
|
||||
and `DecodeDatabaseSQLValue` hands `database/sql` a `time.Time` in that same location. Set the codec's
|
||||
`ScanLocation` to `time.UTC` to pin the location regardless of the client's zone.
|
||||
* Error messages from these paths have changed.
|
||||
|
||||
* pgconn: connection URIs (`postgres://...`) are now parsed by a new parser designed to exactly match libpq's URI
|
||||
parser behavior instead of `net/url`,
|
||||
making pgx accept and reject exactly the same URIs as libpq (verified by differential fuzzing against libpq itself).
|
||||
Most connection strings are unaffected. Edge-case behavior changes, all matching libpq:
|
||||
* `+` in query values is literal, no longer decoded as a space.
|
||||
* Malformed percent-encoding is a parse error instead of the parameter being silently dropped. `%00` is rejected.
|
||||
* Leading/trailing spaces in URI components are trimmed; interior spaces are a parse error (encode them as `%20`).
|
||||
* `#` is ordinary data, not a fragment delimiter.
|
||||
* The userinfo terminator is the first `@` before any `/` (previously the last `@`).
|
||||
* When a query parameter is repeated, the last occurrence wins (previously the first).
|
||||
* `ssl=true` is accepted as an alias for `sslmode=require` in URIs (JDBC compatibility). A repeated `ssl` key
|
||||
follows the same last-occurrence-wins rule as other repeated parameters, even across the rewrite to `sslmode`. If
|
||||
the final `ssl` value is not `true`, an independent explicit `sslmode` remains in effect.
|
||||
* Multiple hosts with mixed port specs are positionally aligned: `postgres://h1,h2:5433/db` now means h1:5432 and
|
||||
h2:5433 (previously both hosts got port 5433). A port list that is neither a single port nor exactly one port per
|
||||
host is an error (`could not match N port numbers to M hosts`), also for keyword/value connection strings.
|
||||
* An IPv6 address in a URI must be enclosed in brackets. A bare `postgres://::1/db` was previously accepted as host
|
||||
`::1`; it is now read as an empty host followed by port `:1` and fails with an invalid port error. Write it as
|
||||
`postgres://[::1]/db`.
|
||||
* Empty host list elements (e.g. `h1,,h2`) get the default host instead of being dropped. Likewise, an empty host in
|
||||
a keyword/value string (`host=`) now means the default host -- typically the Unix socket directory -- where it
|
||||
previously meant a TCP connection to an empty hostname.
|
||||
* An empty port (`?port=` in a URI or `port=` in a keyword/value string) now means the default port 5432 for the
|
||||
affected hosts; previously it was an invalid port error. Like any connection-string port, a present-but-empty port
|
||||
takes precedence over `PGPORT`.
|
||||
* ASCII control characters (tab, newline, ...) in a URI are ordinary data bytes, as they are to libpq; `net/url`
|
||||
rejected any URI containing one. The exception is a literal NUL byte, which is still rejected, as `net/url` did.
|
||||
(libpq never sees one -- C strings end at the first NUL -- but in Go a raw NUL could otherwise pass through into
|
||||
the NUL-delimited startup message and inject extra parameters.)
|
||||
|
||||
Unlike libpq, unrecognized URI query parameters are still accepted (they become runtime parameters or pgx-specific
|
||||
options). Parse error messages avoid quoting the unredacted connection string and redact recognizable password
|
||||
fields on a best-effort basis. Invalid connection strings can be structurally ambiguous, so password redaction
|
||||
cannot be guaranteed for every malformed input.
|
||||
|
||||
* pgconn: keyword/value connection strings (`host=... user=...`) now match libpq's parser exactly, the same treatment
|
||||
the URI parser received above and verified the same way, by differential fuzzing against libpq itself. Most
|
||||
connection strings are unaffected. Behavior changes, all matching libpq:
|
||||
* A backslash escapes whatever character follows it and is dropped, where previously only `\\` and `\'` were
|
||||
unescaped and every other backslash was kept. A value containing a backslash must now escape it, as libpq
|
||||
requires: `sslcert=C:\path\to\cert` reads as `C:pathtocert` and has to be written `sslcert=C:\\path\\to\\cert`.
|
||||
This mainly affects Windows certificate and key paths, which previously came through intact without doubling.
|
||||
* A trailing backslash in an unquoted value escapes the end of the string, so it is dropped and the value ends
|
||||
there; it was previously rejected with `invalid backslash`. Inside a quoted value the escaped terminator leaves
|
||||
the string unterminated, which is still an error.
|
||||
* Whitespace inside a keyword is an error (`missing "=" after "us" in connection info string`) instead of becoming
|
||||
part of the key. Whitespace around the `=` is unaffected. This most often shows up with an unquoted value
|
||||
containing a space: `application_name=my app host=x` previously set neither parameter and sent `app host` to the
|
||||
server as a runtime parameter, and now fails to parse.
|
||||
|
||||
As with URIs, unrecognized keywords are still accepted where libpq rejects them, and an empty `user=` is still
|
||||
dropped so that `PGUSER` and the OS user still apply.
|
||||
|
||||
## Fixes
|
||||
|
||||
* Keep the connection open after a recoverable PostgreSQL error from `Begin` or `BeginTx`
|
||||
(Victor Alejandro Sanz Ararat)
|
||||
* Call `TraceQueryEnd` when `Exec` fails while deallocating invalidated cached statements (Chris Bandy)
|
||||
* Deallocate a failed prepare using the statement name actually sent to the server, and skip cleanup if Parse never
|
||||
completed, avoiding leaked prepared statements and unnecessary cleanup errors (Eliran Ben-Zikri)
|
||||
* Fix `LoadTypes` overwriting scalar codecs such as `box` and `point` with an incorrect `ArrayCodec` (Arsen Ozhetov)
|
||||
* pgconn: retrieve field descriptions when cached descriptions are empty, such as for cursor `FETCH` statements,
|
||||
including batch and pipeline execution (water)
|
||||
* pgconn: keep batch statement descriptions and result formats aligned when commands return no rows or when
|
||||
`Batch.ExecStatement` is mixed with other batch commands; preserve field descriptions for empty results
|
||||
* pgconn: handle empty and comment-only queries in pipeline mode, discard stale statement data after bind errors,
|
||||
and return a nil result from `Pipeline.GetResults` on error
|
||||
* pgconn: skip reading the password file when a password is already set (Jared Fowkes)
|
||||
* pgxpool: treat non-positive `MaxConnLifetime` values as unlimited instead of immediately expiring connections
|
||||
(Aurelien Pillevesse)
|
||||
* pgtype: support non-comma text array delimiters through `ArrayCodec.Delimiter`, including the semicolon delimiter
|
||||
used by `box[]`. `LoadType` and `LoadTypes` now load the delimiter from PostgreSQL (Sueun Cho)
|
||||
* pgtype: quote text array elements containing internal whitespace (Louisa Huang)
|
||||
* pgtype: quote and escape text range bounds containing delimiters, quotes, or backslashes, and distinguish empty
|
||||
string bounds from unbounded ranges (Sueun Cho)
|
||||
* pgtype: preserve decimal precision in `Numeric.ScanScientific` and accept scientific notation in
|
||||
`Numeric.UnmarshalJSON`; reject out-of-range scientific exponents and preserve the original input in parse errors
|
||||
(Sueun Cho)
|
||||
* pgtype: encode and decode numeric infinity in JSON as `"Infinity"` and `"-Infinity"` instead of encoding it as zero
|
||||
(Vladimir Saraikin)
|
||||
* pgtype: treat a valid `Numeric` with a nil `Int` as zero in `Int64Value`, and return errors when converting NaN or
|
||||
infinity to an integer instead of panicking (Vladimir Saraikin)
|
||||
* pgtype: fix an infinite loop when decoding binary numeric zero with a nonzero digit count (Vladimir Saraikin)
|
||||
* pgtype: fix binary numeric digit-count overflow and trailing-byte handling. Binary encoding now rejects values
|
||||
whose digit count, weight, or scale cannot fit the wire format, while accepting the full unsigned digit-count range.
|
||||
* pgtype: fix scanning through multiple pointer levels, including SQL NULL and XML values, and return an error
|
||||
instead of panicking when a pointer-to-pointer scan destination is nil (Rangel Reale)
|
||||
* pgtype: use bounds-checked binary reads throughout the codecs and reject malformed lengths, counts, and trailing
|
||||
data. This includes fixes for panics on malformed records and truncated multiranges (Vladimir Saraikin), and
|
||||
validation of `bit` / `varbit` bit lengths against the actual data (g3m0sis).
|
||||
* pgtype: return errors instead of panicking on malformed interval text (greymoth-jp), unterminated composite text
|
||||
fields, and text arrays whose dimensions and element counts disagree
|
||||
* pgtype: cap the initial allocation estimate when parsing hstore text to avoid excessive allocation from unvalidated
|
||||
separator counts; valid hstores may still contain any number of pairs (AshSgDe29071999)
|
||||
* pgtype: correct reversed bounds in integer scan error messages
|
||||
* pgconn: a backslash as the last byte of a quoted value in a keyword/value connection string no longer panics with
|
||||
`slice bounds out of range`. `host='a\` -- and the shorter `='\`, reachable through `pgx.ParseConfig` and
|
||||
`pgxpool.ParseConfig` -- now return `unterminated quoted string in connection info string`, libpq's own message for
|
||||
the same input. The unquoted branch has been guarded since be69c1c1; the quoted branch carried the same unguarded
|
||||
increment since the parser was ported from pgx v3. Found by fuzzing (Maxim Korotkov)
|
||||
* pgconn: error messages that embed the connection string now also redact `password` and `sslpassword` values supplied
|
||||
as URI query parameters; previously only the userinfo password was redacted. Redaction matches keys the way the
|
||||
parser does -- percent-encoded spellings such as `pass%77ord=` are recognized -- and masks the entire raw value, so
|
||||
a password containing a space cannot leak its tail into the error message. Credentials stranded outside the
|
||||
userinfo by a malformed URI are masked whole, and invalid-port errors no longer embed the offending text (which in
|
||||
a malformed URI can be a mislaid password). Redaction of invalid connection strings is necessarily best effort:
|
||||
their structure may be ambiguous, so some malformed inputs can still expose password text in an error.
|
||||
* pgconn: `ParseConfigOptions.ConnStringAllowedKeys` no longer exempts an explicitly supplied empty port (`?port=` in
|
||||
a URI or `port=` in a keyword/value string) from the allow-list. Only the implied all-empty port list of a
|
||||
multi-host URI without ports (`postgres://h1,h2/db`) is exempt. An explicit empty port shadows `PGPORT` even though
|
||||
it is empty, so it must be allowed like any other user-supplied key. The URI-only `ssl=true` alias is accepted when
|
||||
either `ssl` or `sslmode` is allowed, and every `ssl`/`sslmode` spelling written in the URI is validated --
|
||||
including occurrences superseded by later repeated parameters.
|
||||
* pgconn: drain socket before close in `asyncClose` so context cancellation produces a TCP FIN instead of RST, avoiding "connection reset by peer" on the server / proxy (Sean Chittenden at CrowdStrike, Inc.)
|
||||
* pgproto3: `StartupMessage.Encode` rejects a NUL byte in any parameter name or value instead of writing it. The
|
||||
startup message body is a run of NUL-delimited strings whose length is data-driven, so a NUL in a value ends that
|
||||
parameter and everything after it is read by the server as further parameters -- an `application_name` of
|
||||
`x\x00user\x00admin` changed the role the connection logged in as. libpq cannot reach this state because its
|
||||
parameters are NUL-terminated C strings. `Connect` now fails with nothing written to the wire, which covers
|
||||
settings that bypass connection string parsing: service files and direct assignment to `Config.RuntimeParams`,
|
||||
`Config.User`, or `Config.Database`.
|
||||
* pgconn: keyword/value connection strings containing a NUL byte are rejected by `ParseConfig`, as URIs already were.
|
||||
|
||||
# 5.10.0 (June 3, 2026)
|
||||
|
||||
This release includes a significant amount of hardening against malicious or compromised PostgreSQL servers,
|
||||
|
||||
+42
-24
@@ -8,41 +8,59 @@ pgx is a PostgreSQL driver and toolkit for Go (`github.com/jackc/pgx/v5`). It pr
|
||||
|
||||
## Build & Test Commands
|
||||
|
||||
Every checkout has its own PostgreSQL 14-18 and CockroachDB instances, supervised by
|
||||
process-compose. `mise run dev` starts PostgreSQL 18; tests start other targets on demand and stop
|
||||
them afterwards unless they were explicitly prewarmed. See DEVELOPMENT.md.
|
||||
|
||||
```bash
|
||||
# Run all tests (requires PGX_TEST_DATABASE to be set)
|
||||
go test ./...
|
||||
mise run dev # start PostgreSQL 18 and the database supervisor
|
||||
mise run dev:all # eagerly start every available database
|
||||
mise run dev -- -D # ... detached; then `mise run dev:wait`, and
|
||||
# `mise run dev:down` when finished. Agents must do this.
|
||||
|
||||
# Run a specific test
|
||||
go test -run TestFunctionName ./...
|
||||
./test.sh # Full suite against PostgreSQL 18 (the default target)
|
||||
./test.sh pg16 # Against PostgreSQL 16
|
||||
./test.sh crdb # Against CockroachDB
|
||||
./test.sh all # Every target (pg14-18 + crdb)
|
||||
./test.sh pg16 -run TestConnect # Trailing arguments are passed to `go test`
|
||||
|
||||
# Run tests for a specific package
|
||||
go test ./pgconn/...
|
||||
go test ./... # Also works: mise loads the default target's PGX_TEST_*
|
||||
go test -race ./... # With the race detector
|
||||
|
||||
# Run tests with race detector
|
||||
go test -race ./...
|
||||
goimports -w . # Format (always run after making changes)
|
||||
golangci-lint run ./... # Lint
|
||||
|
||||
# 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 ./...
|
||||
mise run dev:ports # This checkout's ports and where each server's data lives
|
||||
mise run db:start pg16 crdb # Prewarm targets; tests then leave them running
|
||||
mise run db:stop pg16 crdb # Stop prewarmed targets
|
||||
mise run db:psql # psql against PostgreSQL 18; `mise run db:psql 16` for another
|
||||
process-compose process logs pg16 # One server's output
|
||||
```
|
||||
|
||||
Do not hardcode database ports. They are allocated per checkout by port-tamer and read from the
|
||||
environment (`PGPORT`, `PGPORT_16`, `CRDB_PORT`) or `.dev/ports.env`; 5432 and 26257 mean nothing
|
||||
here.
|
||||
|
||||
The `PGX_TEST_*` connection strings have one definition, `scripts/lib/test_targets.rb`. Add or
|
||||
change a target there, never in a second copy.
|
||||
|
||||
## Test Database Setup
|
||||
|
||||
Tests require `PGX_TEST_DATABASE` environment variable. In the devcontainer, `test.sh` handles this. For local development:
|
||||
The lifecycle scripts handle setup: a PostgreSQL server initializes its cluster on first start and
|
||||
creates `pgx_test` with the extensions and auth roles from `testsetup/postgresql_setup.sql`.
|
||||
CockroachDB recreates `pgx_test` after each in-memory restart. Nothing needs to be set up by hand.
|
||||
|
||||
```bash
|
||||
export PGX_TEST_DATABASE="host=localhost user=postgres password=postgres dbname=pgx_test"
|
||||
```
|
||||
Contributors who would rather point pgx at a PostgreSQL server they already have can set
|
||||
`PGX_TEST_DATABASE` themselves; see CONTRIBUTING.md. Many tests are skipped unless additional
|
||||
`PGX_TEST_*` variables are set (for TLS, SCRAM, MD5, unix socket, PgBouncer testing).
|
||||
|
||||
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).
|
||||
## Reference Material
|
||||
|
||||
`references/` holds read-only reference checkouts used when building pgx — currently the PostgreSQL source tree pinned to `REL_18_STABLE`. It is gitignored and provisioned on demand: bare mirrors are cached at a machine-level path (`/persist/shared/references` in a devcontainer, `~/.local/share/pgx/references` natively; `REFERENCES_MIRROR_DIR` overrides) and lightweight local checkouts are created in `references/` with `rake references:setup`. Each checkout has per-instance Git metadata while borrowing the shared mirror's object store. Related tasks: `rake references:update`, `rake references:status`, `rake references:clean`.
|
||||
|
||||
- Do not automatically provision or update `references/`.
|
||||
- Never run `rake references:setup`, `rake references:update`, or any large download on your own initiative.
|
||||
- If reference sources are missing, work without them or ask the user.
|
||||
|
||||
## Architecture
|
||||
|
||||
|
||||
+29
-76
@@ -24,21 +24,30 @@ Using AI is acceptable (not that it can really be stopped) under one the followi
|
||||
|
||||
## 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.
|
||||
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.
|
||||
|
||||
### Devcontainer
|
||||
### The full environment
|
||||
|
||||
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.
|
||||
[DEVELOPMENT.md](DEVELOPMENT.md) describes the maintained setup: [mise](https://mise.jdx.dev)
|
||||
installs the toolchain, and each checkout has its own PostgreSQL 14-18 clusters and CockroachDB
|
||||
node, so the whole test matrix is available locally. PostgreSQL 18 stays running; other servers
|
||||
start and stop around their tests. It works natively on macOS and Linux, and in the included
|
||||
devcontainer.
|
||||
|
||||
### Using an Existing PostgreSQL Cluster Outside of a Devcontainer
|
||||
```
|
||||
mise install
|
||||
mise run dev:init
|
||||
mise run dev
|
||||
./test.sh all
|
||||
```
|
||||
|
||||
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).
|
||||
### Using an existing PostgreSQL cluster
|
||||
|
||||
If you already have a PostgreSQL development server this is the quickest way to run the majority of
|
||||
the pgx test suite, and it needs nothing from the section above. Some tests will be skipped that
|
||||
require server configuration changes (e.g. those testing different authentication methods).
|
||||
|
||||
Create and setup a test database:
|
||||
|
||||
@@ -50,86 +59,30 @@ 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.
|
||||
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.
|
||||
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
|
||||
```
|
||||
This will run the vast majority of the tests, but some tests will be skipped (e.g. those testing
|
||||
different connection methods).
|
||||
|
||||
### PgBouncer
|
||||
|
||||
There are tests specific for PgBouncer that will be executed if `PGX_TEST_PGBOUNCER_CONN_STRING` is set.
|
||||
The test PgBouncer must be version 1.21.0 or newer, use transaction pooling, and have `max_prepared_statements` set to a
|
||||
non-zero value. This ensures the tests cover PgBouncer's protocol-level named prepared statement support in addition to
|
||||
the pgx query modes that do not use named prepared statements.
|
||||
|
||||
### Optional Tests
|
||||
|
||||
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
# Developing pgx
|
||||
|
||||
Two supported environments, one command set. Native macOS or Linux is the fast inner loop; the
|
||||
devcontainer is a Linux compatibility and isolation option. Both run the same mise tasks against
|
||||
the same `process-compose.yaml`, so nothing here is specific to one of them except the
|
||||
prerequisites in §1.
|
||||
|
||||
```sh
|
||||
scripts/setup-host # native macOS or Ubuntu host prerequisites (once per machine)
|
||||
export PATH="$HOME/.local/bin:$PATH" # if mise was just installed
|
||||
mise trust # trust this checkout's configuration
|
||||
mise install # tool versions from mise.toml
|
||||
mise run dev:init # this checkout's ports and certificates
|
||||
mise run dev # start PostgreSQL 18 and the on-demand database supervisor
|
||||
./test.sh # the suite against PostgreSQL 18
|
||||
./test.sh all # every target; non-default servers start and stop around their tests
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. Prerequisites
|
||||
|
||||
### Native
|
||||
|
||||
[mise](https://mise.jdx.dev) provides Go, Ruby, CockroachDB, process-compose, and port-tamer.
|
||||
PostgreSQL itself is the one thing it does not: pgx tests against five major versions, and they
|
||||
come from the system package manager.
|
||||
|
||||
```sh
|
||||
scripts/setup-host
|
||||
```
|
||||
|
||||
On macOS, install [Homebrew](https://brew.sh) first. The script uses `Brewfile` to install
|
||||
PostgreSQL 14-18 and Ruby build dependencies. On Ubuntu, it uses sudo when needed, configures
|
||||
the official PostgreSQL apt repository, and installs the same server versions and build
|
||||
dependencies. Other Linux distributions require manual prerequisite installation.
|
||||
|
||||
The Ubuntu installer temporarily disables automatic `main` cluster creation during server
|
||||
installation and removes that override on exit, leaving the package-owned cluster configuration
|
||||
unchanged. The macOS installer does not start Homebrew services.
|
||||
|
||||
The dispatcher installs mise if it is missing and prints its executable path. It does not run
|
||||
`mise trust`, install project tools, allocate ports, initialize databases, or start servers. Run
|
||||
the remaining commands above explicitly as your regular development user.
|
||||
|
||||
- **Do not** `brew services start` any of them, and on Debian do not let the packages create a
|
||||
machine-wide cluster. pgx runs its own clusters per checkout.
|
||||
- The Homebrew formulas are *keg-only*, so `psql` and `pg_isready` are not on your `PATH` after
|
||||
install. `mise.toml` adds PostgreSQL 18's `bin` to `PATH` for this project — one client serves
|
||||
every server, since libpq is backward compatible.
|
||||
- Only the majors you actually test against need to be installed. `mise run dev` looks for each
|
||||
one's server binaries and names any that are missing; `./test.sh pg15` reports a direct install
|
||||
hint rather than trying to launch a missing server. `PGBIN_16` and friends override the search
|
||||
for a major built or installed somewhere unusual.
|
||||
- Clusters are created with the `en_US.UTF-8` locale where the system has it (matching CI and the
|
||||
container images this replaced), falling back to `C.UTF-8` and then `C`. A stock Debian or Ubuntu
|
||||
has only `C.UTF-8` unless you have run `locale-gen en_US.UTF-8`.
|
||||
|
||||
### Devcontainer
|
||||
|
||||
Reopen in the container; `.devcontainer/` handles the rest. It installs the same five PostgreSQL
|
||||
servers and runs the same per-checkout clusters — it is a Linux shell around this same setup, not a
|
||||
second architecture.
|
||||
|
||||
---
|
||||
|
||||
## 2. Checkouts are the unit of isolation
|
||||
|
||||
A git worktree is the native equivalent of a second devcontainer instance. Each one gets:
|
||||
|
||||
```
|
||||
.dev/ # gitignored, per-checkout runtime state
|
||||
ports.env # this checkout's TCP ports (port-tamer's state file)
|
||||
derived.env # PG* defaults and the default target's PGX_TEST_* set
|
||||
certs/ # the client certificates the TLS tests use
|
||||
logs/ # one log per service
|
||||
<os>-<arch>/postgres/run # one socket directory, shared by all five servers (mode 0700)
|
||||
<os>-<arch>/postgres/<major>/data
|
||||
<os>-<arch>/crdb/
|
||||
```
|
||||
|
||||
The last three — the clusters, the CockroachDB store and the socket directory — move when
|
||||
`PGX_DEV_RUNTIME_DIR` is set. The devcontainer sets it to `/persist/local/dev`, on its own named
|
||||
volume: `.dev/` is inside the `/workspaces/pgx` bind mount, and `initdb` and Unix sockets do not
|
||||
work reliably on Docker Desktop's macOS/Windows file sharing. (The per-version PostgreSQL
|
||||
containers this setup replaced used named volumes for their data and socket directories for the
|
||||
same reason.) Everything else stays in the checkout.
|
||||
|
||||
```sh
|
||||
git worktree add ../pgx-feature-x feature-x
|
||||
cd ../pgx-feature-x
|
||||
mise run dev:init && mise run dev
|
||||
```
|
||||
|
||||
Both checkouts run simultaneously: different ports, independent database state, independent
|
||||
process-compose instances. `mise run dev:ports` prints the allocation.
|
||||
|
||||
Ports are allocated once per checkout by [port-tamer](https://github.com/jackc/port-tamer) and then
|
||||
persisted. `port-tamer.toml` declares which ports a checkout needs — **append new entries at the
|
||||
end**, since inserting or reordering renumbers the existing ones. A listening port never moves an
|
||||
existing allocation, because it may well belong to this checkout's own running services; when two
|
||||
checkouts genuinely collide, stop one and run `mise run dev:ports:overwrite`.
|
||||
|
||||
The data directories are keyed by platform because a cluster `initdb`'d by the Linux devcontainer
|
||||
cannot be read by a native macOS server, and one checkout may be opened both ways. After switching
|
||||
a checkout between the two, re-run `mise run dev:ports:ensure` so the derived paths follow.
|
||||
|
||||
**Reference sources** (`references/`) are provisioned per checkout with `rake references:setup`,
|
||||
sharing one machine-level mirror (`/persist/shared` in a container, `~/.local/share/pgx` natively;
|
||||
`REFERENCES_MIRROR_DIR` overrides). They are a multi-GB download; nothing provisions them
|
||||
automatically.
|
||||
|
||||
---
|
||||
|
||||
## 3. The databases
|
||||
|
||||
`mise run dev` starts PostgreSQL 18 under
|
||||
[process-compose](https://github.com/F1bonacc1/process-compose). PostgreSQL 14-17 and a single-node
|
||||
in-memory CockroachDB are registered with the same supervisor but disabled initially, ready to be
|
||||
started by a test or an explicit `db:start`. `mise run dev:all` eagerly starts every available
|
||||
server. These are the same services the devcontainer used to run as containers; they are now
|
||||
ordinary processes against this checkout's own clusters.
|
||||
|
||||
Each PostgreSQL server initializes its cluster on first start — `initdb`, this project's
|
||||
`pg_hba.conf`, and the TLS certificates — then creates `pgx_test` with its extensions and its
|
||||
`pgx_md5` / `pgx_scram` / `pgx_pw` / `pgx_ssl` / `pgx_sslcert` roles. The default server uses its
|
||||
follow-on `pg18-setup` process; the lazy lifecycle performs the same idempotent setup directly for
|
||||
an on-demand target. Restarts are free once the cluster exists. If setup fails partway it drops the
|
||||
half-built database so the next start retries rather than reporting it as present.
|
||||
|
||||
CockroachDB has no separate setup process: its store is in memory, so every restart is an empty
|
||||
cluster and its readiness probe creates `pgx_test` itself.
|
||||
|
||||
```sh
|
||||
process-compose process list # status, scriptable
|
||||
process-compose process logs pg16 # one server's output
|
||||
mise run db:start pg16 crdb # prewarm one or more targets
|
||||
mise run db:stop pg16 crdb # stop them again
|
||||
mise run db:start all # prewarm every target
|
||||
process-compose down # stop this checkout's stack only
|
||||
mise run db:psql # psql against the already-running PostgreSQL 18
|
||||
mise run db:start pg16 # prewarm PostgreSQL 16 before interactive use
|
||||
mise run db:psql 16 # psql against PostgreSQL 16
|
||||
mise run db:psql 16 -c 'select 1' # arguments after the major go to psql
|
||||
```
|
||||
|
||||
The `process-compose` commands need no flags: `PC_PORT_NUM` is part of this checkout's
|
||||
environment, so they never reach another checkout's stack.
|
||||
|
||||
`rake db:psql[16]` is the same as `mise run db:psql 16`. Note the brackets — a bare
|
||||
`rake db:psql 16` is rake asking for a *task* named `16`, not an argument, so the `db:*` tasks
|
||||
reject it rather than quietly acting on every cluster.
|
||||
|
||||
`mise run db:reset` destroys and re-creates clusters and refuses to run while the selected servers
|
||||
are up: removing a data directory under a live postmaster corrupts it. Stop selected targets with
|
||||
`mise run db:stop`, or stop the whole supervisor with `mise run dev:down`.
|
||||
|
||||
All five PostgreSQL servers share **one** Unix socket directory. Sockets are named
|
||||
`.s.PGSQL.<port>`, so the port picks the server — which is what lets a single
|
||||
`PGX_TEST_UNIX_SOCKET_CONN_STRING` work for every major, exactly as the container's shared
|
||||
`/var/run/postgresql` volume did.
|
||||
|
||||
Tests preserve explicit choices: if `db:start` prewarmed a target, tests leave it running. If a
|
||||
test had to start the target, it stops it in an `ensure` block whether the suite passes, fails, or
|
||||
is interrupted. A per-target lock prevents concurrent test commands from stopping a server the
|
||||
other is using.
|
||||
|
||||
---
|
||||
|
||||
## 4. Running tests
|
||||
|
||||
```sh
|
||||
./test.sh # PostgreSQL 18, the default target
|
||||
./test.sh pg14 # PostgreSQL 14
|
||||
./test.sh crdb # CockroachDB
|
||||
./test.sh all # every target, sequentially
|
||||
./test.sh pg16 -run TestConnect # trailing arguments go to `go test`
|
||||
```
|
||||
|
||||
`mise run test` and `mise run test:all` are equivalent. All of them require the stack to be
|
||||
running, but only their selected database target needs to be up. A stopped target is started,
|
||||
bootstrapped, and stopped automatically. `./test.sh all` does this sequentially, so at most the
|
||||
default PostgreSQL 18 plus one additional database is normally resident.
|
||||
|
||||
A bare `go test ./...` also works: mise loads `.dev/derived.env`, which carries the default
|
||||
target's full `PGX_TEST_*` set, so an activated shell is already pointed at PostgreSQL 18.
|
||||
|
||||
Those connection strings have exactly one definition, `scripts/lib/test_targets.rb`. Both consumers
|
||||
— the generated `.dev/derived.env` and `./test.sh <target>` — read it, so there is no second copy
|
||||
to drift.
|
||||
|
||||
Some tests only run when their environment variable is set. `go test ./... -v | grep SKIP` shows
|
||||
what is being skipped; on a healthy stack that is the PgBouncer, OAuth, CrateDB, and libpq-oracle
|
||||
tests, which are CI-only or manual.
|
||||
|
||||
---
|
||||
|
||||
## 5. Everyday commands
|
||||
|
||||
| Command | What it does |
|
||||
|---|---|
|
||||
| `mise run dev` | start PostgreSQL 18 and the on-demand database supervisor |
|
||||
| `mise run dev:all` | eagerly start every available database |
|
||||
| `mise run dev -- -D` | start the default stack detached, for CI and agents |
|
||||
| `mise run dev:wait` / `dev:down` | wait for a detached stack / stop it |
|
||||
| `mise run dev:init` | allocate this checkout's ports, decode its certificates |
|
||||
| `mise run dev:ports` | the allocation, and where each server's data lives |
|
||||
| `mise run test [target]` | the suite against one target |
|
||||
| `mise run test:all` | every target |
|
||||
| `mise run db:start [targets...]` / `db:stop` | prewarm or stop targets (`pg16`, `crdb`, or `all`) |
|
||||
| `mise run db:init [major]` / `db:psql [major]` / `db:reset [major]` | create / open / rebuild the clusters |
|
||||
| `mise run fmt` | `goimports -w .` |
|
||||
| `mise run generate` | regenerate the ERB-templated sources |
|
||||
|
||||
`rake <task>` remains equally valid and is where some of the logic lives; `rake -T` lists
|
||||
everything, including tasks with no mise wrapper (`references:*`, `db:setup`).
|
||||
|
||||
---
|
||||
|
||||
## 6. Notes
|
||||
|
||||
- **`PGHOST` and `PGPORT` are a pair.** They come from `.dev/` via mise — `PGPORT` from the
|
||||
allocation, `PGHOST` derived from it. Setting one without the other names a real port on the
|
||||
wrong server, and the error will point at a socket nothing ever created. `mise run dev` asserts
|
||||
the two agree with the cluster before starting anything.
|
||||
- **`.dev/derived.env` is generated.** If it is ever hand-edited into something mise's dotenv
|
||||
parser rejects, every `mise` command in the directory fails — including the one that would
|
||||
rewrite it. Recover with `rm .dev/derived.env && mise run dev:ports:ensure`.
|
||||
- **A `~/.psqlrc` that changes session defaults** can break the database bootstrap while leaving
|
||||
interactive use fine. The scripts pass `--no-psqlrc` for that reason.
|
||||
- **`./test.sh` needs Ruby 3.0+**, which `mise install` provides. If mise is installed but not yet
|
||||
activated in your shell, `./test.sh` re-runs itself through `mise exec` rather than failing on
|
||||
the system interpreter.
|
||||
- **CI does not use any of this.** `.github/workflows/ci.yml` installs system PostgreSQL through
|
||||
`ci/setup_test.bash` and carries its own copy of the connection strings. Local runs and CI
|
||||
exercise the same auth paths — `PGX_TEST_DATABASE` connects as `pgx_md5`, and one
|
||||
`testsetup/pg_hba.conf` serves both — but the two setups are still independent.
|
||||
- **PgBouncer and the PG18 OAuth validator module** are exercised only in CI. Neither is part of
|
||||
the local stack, and both were absent from the devcontainer too.
|
||||
+45
-4
@@ -12,7 +12,15 @@ The toolkit component is a related set of packages that implement PostgreSQL fun
|
||||
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
|
||||
## Quick Start
|
||||
|
||||
### Installation
|
||||
|
||||
```bash
|
||||
go get github.com/jackc/pgx/v5
|
||||
```
|
||||
|
||||
### Example Usage
|
||||
|
||||
```go
|
||||
package main
|
||||
@@ -46,7 +54,18 @@ func main() {
|
||||
}
|
||||
```
|
||||
|
||||
See the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx) for more information.
|
||||
### Connection Configuration
|
||||
|
||||
`pgx.Connect` and `pgxpool.New` accept PostgreSQL connection URLs (such as `postgres://user:pass@host:5432/db?sslmode=verify-full`) as well as `key=value` strings. See [`pgconn.ParseConfig`](https://pkg.go.dev/github.com/jackc/pgx/v5/pgconn#ParseConfig) and the [PostgreSQL connection string documentation](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING) for supported options and environment variables.
|
||||
|
||||
For a step-by-step walkthrough, see the [getting started guide](https://github.com/jackc/pgx/wiki/Getting-started-with-pgx).
|
||||
|
||||
## Documentation
|
||||
|
||||
Package documentation and API reference are available on [pkg.go.dev](https://pkg.go.dev/github.com/jackc/pgx/v5):
|
||||
* [`pgx`](https://pkg.go.dev/github.com/jackc/pgx/v5) — base PostgreSQL driver
|
||||
* [`pgxpool`](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool) — concurrency-safe connection pool
|
||||
* [`stdlib`](https://pkg.go.dev/github.com/jackc/pgx/v5/stdlib) — `database/sql` compatibility adapter
|
||||
|
||||
## Features
|
||||
|
||||
@@ -82,9 +101,30 @@ The pgx interface is recommended when:
|
||||
|
||||
It is also possible to use the `database/sql` interface and convert a connection to the lower-level pgx interface as needed.
|
||||
|
||||
## Testing
|
||||
## Development and Testing
|
||||
|
||||
See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup instructions.
|
||||
Each checkout has its own PostgreSQL 14-18 clusters and CockroachDB node, so the whole test matrix
|
||||
is available locally on macOS, on Linux, or in the included devcontainer. Only PostgreSQL 18 stays
|
||||
running by default; other targets start and stop around their tests:
|
||||
|
||||
```sh
|
||||
scripts/setup-host # native macOS (Homebrew required) or Ubuntu: host packages and mise
|
||||
export PATH="$HOME/.local/bin:$PATH" # if mise was just installed
|
||||
mise trust
|
||||
mise install # project tools
|
||||
mise run dev:init # checkout ports and certificates
|
||||
mise run dev # start PostgreSQL 18 and the on-demand database supervisor
|
||||
./test.sh # the suite against PostgreSQL 18
|
||||
./test.sh all # every target, starting and stopping each server as needed
|
||||
```
|
||||
|
||||
Host setup installs PostgreSQL 14-18 and Ruby build dependencies. It does not install project
|
||||
tools or initialize the checkout; those remain separate steps above. The devcontainer already
|
||||
provides the host prerequisites.
|
||||
|
||||
See [DEVELOPMENT.md](./DEVELOPMENT.md) for the full setup, and
|
||||
[CONTRIBUTING.md](./CONTRIBUTING.md) for how to contribute — including how to run the tests against
|
||||
a PostgreSQL server you already have, without any of the above.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -129,6 +169,7 @@ pgerrcode contains constants for the PostgreSQL error codes.
|
||||
|
||||
* [github.com/jackhopner/pgx-xray-tracer](https://github.com/jackhopner/pgx-xray-tracer)
|
||||
* [github.com/exaring/otelpgx](https://github.com/exaring/otelpgx)
|
||||
* [github.com/b0r1ssh/pgxotel](https://github.com/b0r1ssh/pgxotel)
|
||||
|
||||
## Adapters for 3rd Party Loggers
|
||||
|
||||
|
||||
+291
@@ -1,4 +1,5 @@
|
||||
require "erb"
|
||||
require "fileutils"
|
||||
|
||||
rule '.go' => '.go.erb' do |task|
|
||||
erb = ERB.new(File.read(task.source))
|
||||
@@ -16,3 +17,293 @@ generated_code_files = [
|
||||
|
||||
desc "Generate code"
|
||||
task generate: generated_code_files
|
||||
|
||||
# dev -- per-checkout development state. A git worktree is the native equivalent of a second
|
||||
# devcontainer instance: same machine, same network stack, so the five PostgreSQL servers and
|
||||
# CockroachDB that each owned a well-known port in their own container namespace now need distinct
|
||||
# ones. `dev:ports:*` drives port-tamer (port-tamer.toml declares the names; the allocation lands
|
||||
# in the gitignored .dev/ports.env) and writes the values derived from it -- scripts/devenv.rb.
|
||||
namespace :dev do
|
||||
namespace :ports do
|
||||
desc "Allocate this checkout's TCP ports if it has none (idempotent)"
|
||||
task :ensure do
|
||||
sh RbConfig.ruby, "scripts/devenv.rb", "ensure"
|
||||
end
|
||||
|
||||
desc "Move this checkout to a different port group (stop its services first)"
|
||||
task :overwrite do
|
||||
sh RbConfig.ruby, "scripts/devenv.rb", "overwrite"
|
||||
end
|
||||
|
||||
desc "Print this checkout's port allocation and where each server's data lives"
|
||||
task :show do
|
||||
sh RbConfig.ruby, "scripts/devenv.rb", "show"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# db -- this checkout's own PostgreSQL clusters, one per major (scripts/devdb.rb). Clusters per
|
||||
# checkout rather than databases inside shared servers: destructive resets stay local, two
|
||||
# checkouts run at once, and the layout matches the per-instance devcontainer model it replaces.
|
||||
# The SERVERS run in the foreground under process-compose (process-compose.yaml); these are the
|
||||
# one-shot half. Each task takes an optional major, defaulting to all of them.
|
||||
#
|
||||
# rake db:init initialize every cluster
|
||||
# rake db:init[16] just PostgreSQL 16
|
||||
# rake db:psql[16] psql against PostgreSQL 16 (default: the newest major)
|
||||
#
|
||||
# The mise wrappers (`mise run db:init 16`) call scripts/devdb.rb directly rather than routing
|
||||
# through these tasks — mise APPENDS its arguments, and `rake db:init 16` means "run task db:init,
|
||||
# then run task 16", not "run db:init with the argument 16".
|
||||
namespace :db do
|
||||
# A bare major on the command line is the natural thing to type and the one rake cannot mean:
|
||||
# it becomes a second TASK name, so `rake db:reset 16` runs db:reset with no major — every
|
||||
# cluster — and only then fails on the unknown task, after the data is gone. Catch it first.
|
||||
def db_major(task, args)
|
||||
stray = Rake.application.top_level_tasks.find { |t| t =~ /\A\d+\z/ }
|
||||
if stray
|
||||
abort "rake: `#{stray}` is being read as a task name, not an argument. " \
|
||||
"Write `rake #{task.name}[#{stray}]` (or `mise run #{task.name} #{stray}`)."
|
||||
end
|
||||
|
||||
Array(args[:major])
|
||||
end
|
||||
|
||||
desc "Create this checkout's PostgreSQL clusters under .dev (idempotent). Optional: rake db:init[16]"
|
||||
task :init, [:major] do |task, args|
|
||||
sh RbConfig.ruby, "scripts/devdb.rb", "init", *db_major(task, args)
|
||||
end
|
||||
|
||||
desc "psql against one of this checkout's clusters. Optional: rake db:psql[16]"
|
||||
task :psql, [:major] do |task, args|
|
||||
sh RbConfig.ruby, "scripts/devdb.rb", "psql", *db_major(task, args)
|
||||
end
|
||||
|
||||
desc "Create the pgx_test database and roles in a running cluster (idempotent)"
|
||||
task :setup, [:major] do |task, args|
|
||||
sh RbConfig.ruby, "scripts/devdb.rb", "setup", *db_major(task, args)
|
||||
end
|
||||
|
||||
desc "Destroy this checkout's clusters and re-initialize (destructive; CONFIRM=yes)"
|
||||
task :reset, [:major] do |task, args|
|
||||
sh RbConfig.ruby, "scripts/devdb.rb", "reset", *db_major(task, args)
|
||||
end
|
||||
end
|
||||
|
||||
# references:* — provision local, read-only checkouts of reference material used
|
||||
# when building pgx (currently the PostgreSQL source tree).
|
||||
#
|
||||
# Storage model:
|
||||
# * A bare `--mirror` clone of each repo lives on the devcontainer's shared
|
||||
# persist volume under MIRROR_ROOT. It holds the full history + all
|
||||
# branches/tags, is downloaded once, and survives container rebuilds. It is
|
||||
# the canonical copy, shared across every container for this project.
|
||||
# * Each container creates a lightweight shared clone in ./references/<name>.
|
||||
# Its Git metadata is local to that checkout while its object store borrows
|
||||
# from the mirror. Containers can therefore use the same in-container path
|
||||
# without sharing Git worktree registrations or downloading history again.
|
||||
#
|
||||
# Provisioning a new container is therefore cheap: a local clone from the
|
||||
# already-present mirror, with no network fetch or duplicate object store.
|
||||
|
||||
# Each entry is one reference repo. `ref` is the branch/tag checked out into the
|
||||
# local checkout. PostgreSQL is pinned to REL_18_STABLE to match the devcontainer's
|
||||
# default PG18 test target.
|
||||
REFERENCE_REPOS = [
|
||||
{ name: "postgres", url: "https://github.com/postgres/postgres.git", ref: "REL_18_STABLE", license: "PostgreSQL License" },
|
||||
].freeze
|
||||
|
||||
# Where the canonical bare mirrors live. They are machine-level state, not checkout-level:
|
||||
# multiple GB, read-only, and identical for every checkout -- so they belong outside the tree, and
|
||||
# every checkout on the machine shares one copy.
|
||||
#
|
||||
# * devcontainer -- the shared persist volume, so every container for this project reuses one
|
||||
# download and a rebuild costs nothing.
|
||||
# * native -- an XDG data directory under $HOME, where git worktrees of this repo share it the
|
||||
# same way containers share the volume.
|
||||
#
|
||||
# REFERENCES_MIRROR_DIR overrides both (a second disk, a scratch location, a test).
|
||||
def default_mirror_root
|
||||
return "/persist/shared/references" if File.directory?("/persist/shared")
|
||||
|
||||
xdg = ENV["XDG_DATA_HOME"]
|
||||
base = xdg.nil? || xdg.empty? ? File.join(Dir.home, ".local", "share") : xdg
|
||||
File.join(base, "pgx", "references")
|
||||
end
|
||||
|
||||
MIRROR_ROOT = ENV.fetch("REFERENCES_MIRROR_DIR") { default_mirror_root }
|
||||
CHECKOUT_ROOT = File.join(__dir__, "references")
|
||||
|
||||
def mirror_path(repo) = File.expand_path(File.join(MIRROR_ROOT, "#{repo[:name]}.git"))
|
||||
def checkout_path(repo) = File.join(CHECKOUT_ROOT, repo[:name])
|
||||
|
||||
# File.exist? is false for dangling symlinks, which are still leftovers setup
|
||||
# must replace (and clean must remove).
|
||||
def path_present?(path) = File.exist?(path) || File.symlink?(path)
|
||||
|
||||
# Run a git command against a bare mirror. Names the gitdir explicitly and lifts
|
||||
# any safe.bareRepository=explicit guard. Raises on failure.
|
||||
def git_bare(repo, *args)
|
||||
sh "git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), *args
|
||||
end
|
||||
|
||||
# Capture stdout of a command given as an argv array (no shell parsing, no
|
||||
# quoting pitfalls). Returns [stdout_string, success_boolean].
|
||||
def capture(*args)
|
||||
out = IO.popen(args, err: File::NULL, &:read)
|
||||
[out.to_s, $?.success?]
|
||||
end
|
||||
|
||||
# A managed checkout has its own repository metadata, uses this exact mirror as
|
||||
# its origin, and borrows that mirror's object database. This rejects ordinary
|
||||
# clones, linked worktrees left by the old implementation, and dangling gitfiles.
|
||||
def checkout_valid?(repo)
|
||||
wp = checkout_path(repo)
|
||||
git_dir = File.join(wp, ".git")
|
||||
objects_dir = File.join(git_dir, "objects")
|
||||
alternates_path = File.join(objects_dir, "info", "alternates")
|
||||
|
||||
return false unless File.directory?(git_dir) && File.file?(alternates_path)
|
||||
|
||||
inside, inside_ok = capture("git", "-C", wp, "rev-parse", "--is-inside-work-tree")
|
||||
origin, origin_ok = capture("git", "-C", wp, "remote", "get-url", "origin")
|
||||
return false unless inside_ok && inside.strip == "true" && origin_ok
|
||||
return false unless File.identical?(File.expand_path(origin.strip, wp), mirror_path(repo))
|
||||
|
||||
File.foreach(alternates_path).any? do |alternate|
|
||||
alternate = alternate.strip
|
||||
next false if alternate.empty?
|
||||
|
||||
File.identical?(File.expand_path(alternate, objects_dir), File.join(mirror_path(repo), "objects"))
|
||||
end
|
||||
rescue SystemCallError
|
||||
false
|
||||
end
|
||||
|
||||
# A mirror is valid only if it exists AND has at least one ref — this rejects a
|
||||
# directory left behind by an interrupted clone (which exists but is incomplete).
|
||||
def mirror_valid?(repo)
|
||||
return false unless File.directory?(mirror_path(repo))
|
||||
out, ok = capture("git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo), "for-each-ref", "--count=1")
|
||||
ok && !out.strip.empty?
|
||||
end
|
||||
|
||||
# Clone the bare mirror onto the persist volume if it is missing or broken.
|
||||
def ensure_mirror(repo)
|
||||
if mirror_valid?(repo)
|
||||
puts " mirror cached: #{mirror_path(repo)}"
|
||||
else
|
||||
FileUtils.rm_rf(mirror_path(repo)) # clear any partial/broken clone
|
||||
puts " cloning mirror (full history): #{repo[:url]}"
|
||||
sh "git", "clone", "--mirror", repo[:url], mirror_path(repo)
|
||||
end
|
||||
end
|
||||
|
||||
# Serialize mirror creation and updates across devcontainer instances. Local
|
||||
# checkouts do not share metadata, but they all read from the same object store.
|
||||
def with_mirror_lock(repo)
|
||||
FileUtils.mkdir_p(MIRROR_ROOT)
|
||||
File.open(File.join(MIRROR_ROOT, ".#{repo[:name]}.lock"), File::RDWR | File::CREAT, 0o644) do |lock|
|
||||
lock.flock(File::LOCK_EX)
|
||||
yield
|
||||
end
|
||||
end
|
||||
|
||||
# Check out (or re-point) the local clone at the configured ref. Resolve the
|
||||
# commit in the freshly updated mirror so an existing checkout cannot remain
|
||||
# stale merely because only the mirror was fetched.
|
||||
def ensure_checkout(repo)
|
||||
wp = checkout_path(repo)
|
||||
ref = repo[:ref]
|
||||
|
||||
commit, ok = capture("git", "-c", "safe.bareRepository=all", "--git-dir", mirror_path(repo),
|
||||
"rev-parse", "--verify", "#{ref}^{commit}")
|
||||
raise "ref #{ref.inspect} not found in #{mirror_path(repo)}" unless ok && !commit.strip.empty?
|
||||
|
||||
if checkout_valid?(repo)
|
||||
puts " checkout present: #{wp} -> #{ref}"
|
||||
else
|
||||
puts " replacing invalid checkout: #{wp}" if path_present?(wp)
|
||||
FileUtils.rm_rf(wp) if path_present?(wp)
|
||||
puts " cloning checkout: #{wp} -> #{ref}"
|
||||
sh "git", "clone", "--shared", "--no-checkout", mirror_path(repo), wp
|
||||
raise "checkout at #{wp} is not linked to #{mirror_path(repo)}" unless checkout_valid?(repo)
|
||||
end
|
||||
|
||||
sh "git", "-C", wp, "checkout", "--detach", commit.strip
|
||||
end
|
||||
|
||||
# Run a block per repo, collecting failures so one bad repo does not abort the rest.
|
||||
def for_each_repo
|
||||
failures = []
|
||||
REFERENCE_REPOS.each do |repo|
|
||||
puts "#{repo[:name]}:"
|
||||
begin
|
||||
yield repo
|
||||
rescue => e
|
||||
warn " FAILED: #{e.message}"
|
||||
failures << repo[:name]
|
||||
end
|
||||
end
|
||||
abort "references: failed for #{failures.join(', ')}" unless failures.empty?
|
||||
end
|
||||
|
||||
namespace :references do
|
||||
desc "Clone/refresh reference mirrors on persist and create checkouts in references/"
|
||||
task :setup do
|
||||
FileUtils.mkdir_p(MIRROR_ROOT)
|
||||
FileUtils.mkdir_p(CHECKOUT_ROOT)
|
||||
for_each_repo do |repo|
|
||||
with_mirror_lock(repo) do
|
||||
ensure_mirror(repo)
|
||||
ensure_checkout(repo)
|
||||
end
|
||||
end
|
||||
puts
|
||||
puts "Done. Reference sources are in #{CHECKOUT_ROOT}"
|
||||
Rake::Task["references:status"].invoke
|
||||
end
|
||||
|
||||
desc "Fetch latest upstream for all mirrors and re-point checkouts"
|
||||
task :update do
|
||||
for_each_repo do |repo|
|
||||
with_mirror_lock(repo) do
|
||||
abort "mirror missing for #{repo[:name]}; run `rake references:setup`" unless mirror_valid?(repo)
|
||||
git_bare(repo, "remote", "update", "--prune")
|
||||
ensure_checkout(repo)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
desc "Show provisioned reference repos, their pinned ref, and current HEAD"
|
||||
task :status do
|
||||
puts
|
||||
puts format(" %-16s %-14s %-14s %s", "REPO", "REF", "HEAD", "LICENSE")
|
||||
REFERENCE_REPOS.each do |repo|
|
||||
wp = checkout_path(repo)
|
||||
state =
|
||||
if checkout_valid?(repo)
|
||||
head, ok = capture("git", "-C", wp, "rev-parse", "--short", "HEAD")
|
||||
ok && !head.strip.empty? ? head.strip : "(invalid)"
|
||||
elsif path_present?(wp)
|
||||
"(invalid)"
|
||||
else
|
||||
"(not set up)"
|
||||
end
|
||||
puts format(" %-16s %-14s %-14s %s", repo[:name], repo[:ref], state, repo[:license])
|
||||
end
|
||||
puts
|
||||
puts " mirrors: #{MIRROR_ROOT}"
|
||||
puts " checkouts: #{CHECKOUT_ROOT}"
|
||||
end
|
||||
|
||||
desc "Remove checkouts from references/ (keeps the cached mirrors on persist)"
|
||||
task :clean do
|
||||
REFERENCE_REPOS.each do |repo|
|
||||
wp = checkout_path(repo)
|
||||
next unless path_present?(wp)
|
||||
puts "removing checkout: #{wp}"
|
||||
FileUtils.rm_rf(wp)
|
||||
end
|
||||
end
|
||||
end
|
||||
+127
-18
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
@@ -62,6 +63,21 @@ func (qq *QueuedQuery) Exec(fn func(ct pgconn.CommandTag) error) {
|
||||
// unnecessary network round trips. A Batch must only be sent once.
|
||||
type Batch struct {
|
||||
QueuedQueries []*QueuedQuery
|
||||
|
||||
txOptions *TxOptions
|
||||
}
|
||||
|
||||
// BeginTx queues the query that begins a transaction with txOptions as the first query of b, saving the round trip that
|
||||
// [Conn.BeginTx] spends on it. It must be called before any query is queued and panics otherwise. Like any queued query,
|
||||
// the begin query has a result: it is the first result of the batch. The transaction is available from
|
||||
// [BatchResults.Tx] once b has been sent.
|
||||
func (b *Batch) BeginTx(txOptions TxOptions) {
|
||||
if len(b.QueuedQueries) != 0 {
|
||||
panic("Batch.BeginTx must be called before any query is queued")
|
||||
}
|
||||
|
||||
b.Queue(txOptions.beginSQL())
|
||||
b.txOptions = &txOptions
|
||||
}
|
||||
|
||||
// Queue queues a query to batch b. query can be an SQL query or the name of a prepared statement. The only pgx option
|
||||
@@ -113,6 +129,12 @@ type BatchResults interface {
|
||||
// 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
|
||||
|
||||
// Tx returns the transaction begun by [Batch.BeginTx], or nil if the batch did not begin one. It is available before
|
||||
// Close is called so that a Rollback can be deferred as usual, but the transaction must not otherwise be used until
|
||||
// Close has been called. If the batch fails before the transaction is begun, the transaction is closed by the time
|
||||
// Close returns, and its methods return an error where errors.Is(ErrTxClosed) is true.
|
||||
Tx() Tx
|
||||
}
|
||||
|
||||
type batchResults struct {
|
||||
@@ -137,6 +159,8 @@ func (br *batchResults) Exec() (pgconn.CommandTag, error) {
|
||||
|
||||
query, arguments, _ := br.nextQueryAndArgs()
|
||||
|
||||
readStartTime := time.Now()
|
||||
|
||||
if !br.mrr.NextResult() {
|
||||
err := br.mrr.Close()
|
||||
if err == nil {
|
||||
@@ -144,9 +168,10 @@ func (br *batchResults) Exec() (pgconn.CommandTag, error) {
|
||||
}
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: err,
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: err,
|
||||
ReadStartTime: readStartTime,
|
||||
})
|
||||
}
|
||||
return pgconn.CommandTag{}, err
|
||||
@@ -160,10 +185,11 @@ func (br *batchResults) Exec() (pgconn.CommandTag, error) {
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
CommandTag: commandTag,
|
||||
Err: br.err,
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
CommandTag: commandTag,
|
||||
Err: br.err,
|
||||
ReadStartTime: readStartTime,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -198,9 +224,10 @@ func (br *batchResults) Query() (Rows, error) {
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: rows.err,
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: rows.err,
|
||||
ReadStartTime: rows.startTime,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -261,6 +288,10 @@ func (br *batchResults) Close() error {
|
||||
return br.err
|
||||
}
|
||||
|
||||
func (br *batchResults) Tx() Tx {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (br *batchResults) earlyError() error {
|
||||
return br.err
|
||||
}
|
||||
@@ -306,9 +337,19 @@ func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) {
|
||||
return pgconn.CommandTag{}, err
|
||||
}
|
||||
|
||||
readStartTime := time.Now()
|
||||
|
||||
results, err := br.pipeline.GetResults()
|
||||
if err != nil {
|
||||
br.err = err
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: br.err,
|
||||
ReadStartTime: readStartTime,
|
||||
})
|
||||
}
|
||||
return pgconn.CommandTag{}, br.err
|
||||
}
|
||||
var commandTag pgconn.CommandTag
|
||||
@@ -316,15 +357,25 @@ func (br *pipelineBatchResults) Exec() (pgconn.CommandTag, error) {
|
||||
case *pgconn.ResultReader:
|
||||
commandTag, br.err = results.Close()
|
||||
default:
|
||||
return pgconn.CommandTag{}, fmt.Errorf("unexpected pipeline result: %T", results)
|
||||
err = 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,
|
||||
Err: err,
|
||||
ReadStartTime: readStartTime,
|
||||
})
|
||||
}
|
||||
return pgconn.CommandTag{}, err
|
||||
}
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
CommandTag: commandTag,
|
||||
Err: br.err,
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
CommandTag: commandTag,
|
||||
Err: br.err,
|
||||
ReadStartTime: readStartTime,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -364,9 +415,10 @@ func (br *pipelineBatchResults) Query() (Rows, error) {
|
||||
|
||||
if br.conn.batchTracer != nil {
|
||||
br.conn.batchTracer.TraceBatchQuery(br.ctx, br.conn, TraceBatchQueryData{
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: err,
|
||||
SQL: query,
|
||||
Args: arguments,
|
||||
Err: err,
|
||||
ReadStartTime: rows.startTime,
|
||||
})
|
||||
}
|
||||
} else {
|
||||
@@ -378,6 +430,15 @@ func (br *pipelineBatchResults) Query() (Rows, error) {
|
||||
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,
|
||||
ReadStartTime: rows.startTime,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -434,6 +495,10 @@ func (br *pipelineBatchResults) Close() error {
|
||||
return br.err
|
||||
}
|
||||
|
||||
func (br *pipelineBatchResults) Tx() Tx {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (br *pipelineBatchResults) earlyError() error {
|
||||
return br.err
|
||||
}
|
||||
@@ -491,6 +556,50 @@ func (br *emptyBatchResults) Close() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (br *emptyBatchResults) Tx() Tx {
|
||||
return nil
|
||||
}
|
||||
|
||||
// txBatchResults are the results of a batch that begins a transaction with [Batch.BeginTx].
|
||||
type txBatchResults struct {
|
||||
BatchResults
|
||||
tx *dbTx
|
||||
closed bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (br *txBatchResults) Tx() Tx {
|
||||
return br.tx
|
||||
}
|
||||
|
||||
// Close closes the batch and, when that leaves the connection outside a transaction because the begin query failed or
|
||||
// the batch was never sent, the transaction as well. Only the first call does this: once the transaction has been
|
||||
// committed or rolled back the connection may already be in use elsewhere and must not be touched.
|
||||
func (br *txBatchResults) Close() error {
|
||||
if br.closed {
|
||||
return br.err
|
||||
}
|
||||
br.closed = true
|
||||
|
||||
br.err = br.BatchResults.Close()
|
||||
if br.tx.conn.PgConn().TxStatus() == 'I' {
|
||||
br.tx.closed = true
|
||||
}
|
||||
return br.err
|
||||
}
|
||||
|
||||
// FailedBatchResults returns [BatchResults] for b that report err from every method, as if sending b had failed before
|
||||
// anything reached the server. It is for code that wraps [Conn.SendBatch] and can fail before it has a connection to
|
||||
// send b on, such as a connection pool. If b began a transaction with [Batch.BeginTx], Tx returns a closed transaction.
|
||||
func FailedBatchResults(b *Batch, err error) BatchResults {
|
||||
br := &batchResults{err: err}
|
||||
if b.txOptions == nil {
|
||||
return br
|
||||
}
|
||||
|
||||
return &txBatchResults{BatchResults: br, tx: &dbTx{closed: true}, closed: true, err: err}
|
||||
}
|
||||
|
||||
// invalidates statement and description caches on batch results error
|
||||
func invalidateCachesOnBatchResultsError(conn *Conn, b *Batch, err error) {
|
||||
if err != nil && conn != nil && b != nil {
|
||||
|
||||
+40
-16
@@ -36,9 +36,10 @@ type ConnConfig struct {
|
||||
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.
|
||||
// and automatically prepares and caches prepared statements. This may be incompatible with proxies such as PgBouncer
|
||||
// unless they are configured to support protocol-level prepared statements. In an incompatible configuration 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.
|
||||
@@ -358,8 +359,13 @@ func (c *Conn) Prepare(ctx context.Context, name, sql string) (sd *pgconn.Statem
|
||||
sd, err = c.pgConn.Prepare(ctx, psName, sql, nil)
|
||||
if err != nil {
|
||||
var pErr *pgconn.PrepareError
|
||||
if errors.As(err, &pErr) {
|
||||
c.failedDescribeStatement = psKey
|
||||
if errors.As(err, &pErr) && pErr.ParseComplete {
|
||||
// The server-side statement was created under psName — the name sent in
|
||||
// Parse. In the name == sql case psKey is the SQL text, and deallocating
|
||||
// by it would close a nonexistent statement while leaking the real one.
|
||||
// When Parse never completed no statement was created at all, so there
|
||||
// is nothing to clean up.
|
||||
c.failedDescribeStatement = psName
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
@@ -475,6 +481,9 @@ func (c *Conn) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.C
|
||||
}
|
||||
|
||||
if err := c.deallocateInvalidatedCachedStatements(ctx); err != nil {
|
||||
if c.queryTracer != nil {
|
||||
c.queryTracer.TraceQueryEnd(ctx, c, TraceQueryEndData{Err: err})
|
||||
}
|
||||
return pgconn.CommandTag{}, err
|
||||
}
|
||||
|
||||
@@ -742,7 +751,7 @@ type QueryRewriter interface {
|
||||
// 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
|
||||
// An implementer 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
|
||||
@@ -934,12 +943,24 @@ func (c *Conn) QueryRow(ctx context.Context, sql string, args ...any) Row {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// explicit transaction control statements are executed or the batch begins a transaction with [Batch.BeginTx]. 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) {
|
||||
func (c *Conn) SendBatch(ctx context.Context, b *Batch) BatchResults {
|
||||
br := c.sendBatch(ctx, b)
|
||||
if b.txOptions == nil {
|
||||
return br
|
||||
}
|
||||
|
||||
return &txBatchResults{
|
||||
BatchResults: br,
|
||||
tx: &dbTx{conn: c, commitQuery: b.txOptions.CommitQuery},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) sendBatch(ctx context.Context, b *Batch) (br BatchResults) {
|
||||
if len(b.QueuedQueries) == 0 {
|
||||
return &emptyBatchResults{conn: c}
|
||||
}
|
||||
@@ -1018,7 +1039,9 @@ func (c *Conn) sendBatchQueryExecModeSimpleProtocol(ctx context.Context, b *Batc
|
||||
var sb strings.Builder
|
||||
for i, bi := range b.QueuedQueries {
|
||||
if i > 0 {
|
||||
sb.WriteByte(';')
|
||||
// The newline ends any trailing line comment in the previous query, which would otherwise swallow the ';' and
|
||||
// this query.
|
||||
sb.WriteString("\n;")
|
||||
}
|
||||
sql, err := c.sanitizeForSimpleQuery(bi.SQL, bi.Arguments...)
|
||||
if err != nil {
|
||||
@@ -1305,7 +1328,7 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err
|
||||
|
||||
switch typtype {
|
||||
case "b": // array
|
||||
elementOID, err := c.getArrayElementOID(ctx, oid)
|
||||
elementOID, delimiter, err := c.getArrayElementOIDAndDelimiter(ctx, oid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -1315,7 +1338,7 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err
|
||||
return nil, errors.New("array element OID not registered")
|
||||
}
|
||||
|
||||
return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt}}, nil
|
||||
return &pgtype.Type{Name: typeName, OID: oid, Codec: &pgtype.ArrayCodec{ElementType: dt, Delimiter: delimiter}}, nil
|
||||
case "c": // composite
|
||||
fields, err := c.getCompositeFields(ctx, oid)
|
||||
if err != nil {
|
||||
@@ -1361,15 +1384,16 @@ func (c *Conn) LoadType(ctx context.Context, typeName string) (*pgtype.Type, err
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Conn) getArrayElementOID(ctx context.Context, oid uint32) (uint32, error) {
|
||||
func (c *Conn) getArrayElementOIDAndDelimiter(ctx context.Context, oid uint32) (uint32, byte, error) {
|
||||
var typelem uint32
|
||||
var typdelim string
|
||||
|
||||
err := c.QueryRow(ctx, "select typelem from pg_type where oid=$1", oid).Scan(&typelem)
|
||||
err := c.QueryRow(ctx, "select typelem, typdelim::text from pg_type where oid=$1", oid).Scan(&typelem, &typdelim)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
return 0, 0, err
|
||||
}
|
||||
|
||||
return typelem, nil
|
||||
return typelem, parseTypeDelimiter(typdelim), nil
|
||||
}
|
||||
|
||||
func (c *Conn) getRangeElementOID(ctx context.Context, oid uint32) (uint32, error) {
|
||||
|
||||
+24
-7
@@ -64,9 +64,12 @@ UNION ALL
|
||||
-- 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 (
|
||||
-- typtype = 'b' AND typelem != 0 is not sufficient to identify an array type: some
|
||||
-- scalar types (box, point, line, lseg, name, ...) also set typelem to describe their
|
||||
-- internal C representation. typcategory = 'A' is the reliable "is an array" signal.
|
||||
SELECT parent.oid, parent.typelem
|
||||
FROM pg_type parent
|
||||
WHERE parent.typtype = 'b' AND parent.typelem != 0
|
||||
WHERE parent.typtype = 'b' AND parent.typelem != 0 AND parent.typcategory = 'A'
|
||||
UNION ALL
|
||||
SELECT parent.oid, parent.typbasetype
|
||||
FROM pg_type parent
|
||||
@@ -82,6 +85,8 @@ UNION ALL
|
||||
-- Now construct a recursive query which includes a 'depth' element.
|
||||
-- This is used to ensure that the "youngest" children are registered before
|
||||
-- their parents.
|
||||
-- Deduplicate relationships at each depth so shared dependencies do not
|
||||
-- multiply the work at every level of a nested composite type.
|
||||
relationships(parent, child, depth) AS (
|
||||
SELECT DISTINCT 0::OID, selected_types.oid, 0
|
||||
FROM selected_types
|
||||
@@ -90,7 +95,7 @@ UNION ALL
|
||||
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
|
||||
UNION
|
||||
SELECT pc.parent, pc.child, relationships.depth + 1
|
||||
FROM pc
|
||||
INNER JOIN relationships ON (pc.parent = relationships.child)
|
||||
@@ -113,6 +118,7 @@ SELECT typname,
|
||||
typtype,
|
||||
typbasetype,
|
||||
typelem,
|
||||
typdelim,
|
||||
pg_type.oid,`)
|
||||
if supportsMultirange {
|
||||
parts = append(parts, `
|
||||
@@ -135,9 +141,13 @@ SELECT typname,
|
||||
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)`)
|
||||
-- Only emit typtype = 'b' rows that are true arrays (typcategory = 'A'). Other base
|
||||
-- types, including ones with a non-zero typelem for non-array reasons (box, point,
|
||||
-- line, lseg, name, ...), already have a codec registered and must not be re-emitted,
|
||||
-- or LoadTypes will overwrite their correct codec with a bogus ArrayCodec.
|
||||
WHERE NOT (typtype = 'b' AND NOT (typelem != 0 AND typcategory = 'A'))`)
|
||||
parts = append(parts, `
|
||||
GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, pg_type.oid, pg_range.rngsubtype,`)
|
||||
GROUP BY typname, pg_namespace.nspname, typtype, typbasetype, typelem, typdelim, pg_type.oid, pg_range.rngsubtype,`)
|
||||
if supportsMultirange {
|
||||
parts = append(parts, `
|
||||
multirange.rngtypid,`)
|
||||
@@ -150,11 +160,18 @@ SELECT typname,
|
||||
|
||||
type derivedTypeInfo struct {
|
||||
Oid, Typbasetype, Typelem, Rngsubtype, Rngtypid uint32
|
||||
TypeName, Typtype, NspName string
|
||||
TypeName, Typtype, NspName, Typdelim string
|
||||
Attnames []string
|
||||
Atttypids []uint32
|
||||
}
|
||||
|
||||
func parseTypeDelimiter(typdelim string) byte {
|
||||
if typdelim == "" {
|
||||
return 0
|
||||
}
|
||||
return typdelim[0]
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -177,7 +194,7 @@ func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Typ
|
||||
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)
|
||||
err = rows.Scan(&ti.TypeName, &ti.NspName, &ti.Typtype, &ti.Typbasetype, &ti.Typelem, &ti.Typdelim, &ti.Oid, &ti.Rngtypid, &ti.Rngsubtype, &ti.Attnames, &ti.Atttypids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("While scanning type information: %w", err)
|
||||
}
|
||||
@@ -188,7 +205,7 @@ func (c *Conn) LoadTypes(ctx context.Context, typeNames []string) ([]*pgtype.Typ
|
||||
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}}
|
||||
type_ = &pgtype.Type{Name: ti.TypeName, OID: ti.Oid, Codec: &pgtype.ArrayCodec{ElementType: dt, Delimiter: parseTypeDelimiter(ti.Typdelim)}}
|
||||
case "c": // composite
|
||||
var fields []pgtype.CompositeCodecField
|
||||
for i, fieldName := range ti.Attnames {
|
||||
|
||||
+21
-2
@@ -68,6 +68,15 @@ Use [Conn.Exec] to execute a query that does not return a result set.
|
||||
return errors.New("No row found to delete")
|
||||
}
|
||||
|
||||
To match a column against a Go slice, pass the slice as one argument and use
|
||||
PostgreSQL's ANY. Bare IN $1 is invalid SQL, and IN ($1) compares against the
|
||||
array as a whole rather than its elements.
|
||||
|
||||
ids := []int64{1, 2, 3}
|
||||
rows, _ := conn.Query(ctx, "select * from widgets where id = any($1)", ids)
|
||||
|
||||
See https://www.postgresql.org/docs/current/functions-comparisons.html#FUNCTIONS-COMPARISONS-ANY-SOME.
|
||||
|
||||
PostgreSQL Data Types
|
||||
|
||||
pgx uses the [pgtype] package to converting Go values to and from PostgreSQL values. It supports many PostgreSQL types
|
||||
@@ -210,8 +219,18 @@ implemented on top of [pgconn.PgConn]. The [Conn.PgConn] method can be used to a
|
||||
|
||||
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].
|
||||
By default pgx automatically uses protocol-level named prepared statements. PgBouncer 1.21.0 and newer can use these
|
||||
prepared statements in transaction and statement pooling modes when its max_prepared_statements setting is greater than
|
||||
zero. In this configuration the default [QueryExecModeCacheStatement] mode may be used. See the PgBouncer documentation
|
||||
for limitations and configuration details: https://www.pgbouncer.org/config.html#max_prepared_statements.
|
||||
|
||||
When using an older PgBouncer version or when prepared statement support is disabled, set
|
||||
[ConnConfig.DefaultQueryExecMode] to [QueryExecModeExec]. [QueryExecModeCacheDescribe] and
|
||||
[QueryExecModeSimpleProtocol] are also compatible with PgBouncer. Prefer [QueryExecModeExec] over
|
||||
[QueryExecModeSimpleProtocol] whenever possible. Do not use [QueryExecModeDescribeExec] with transaction pooling because
|
||||
PgBouncer may assign a different server connection between the describe and execute steps.
|
||||
|
||||
SQL-level prepared statements created with PREPARE are not supported by PgBouncer in transaction pooling mode.
|
||||
*/
|
||||
package pgx
|
||||
|
||||
|
||||
+1
-1
@@ -33,7 +33,7 @@ func Get(size int) *[]byte {
|
||||
return &buf
|
||||
}
|
||||
|
||||
ptrBuf := (pools[i].Get().(*[]byte))
|
||||
ptrBuf := pools[i].Get().(*[]byte)
|
||||
*ptrBuf = (*ptrBuf)[:size]
|
||||
|
||||
return ptrBuf
|
||||
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
// Package pgdatetime writes PostgreSQL's ISO date/time text format.
|
||||
//
|
||||
// The format is the one EncodeDateTime and AppendSeconds produce in
|
||||
// src/backend/utils/adt/datetime.c under the default ISO DateStyle:
|
||||
//
|
||||
// stamp = date [ SP time [ zone ] ] [ " BC" ]
|
||||
// date = year "-" 2DIGIT "-" 2DIGIT
|
||||
// time = 2DIGIT ":" 2DIGIT ":" 2DIGIT [ "." 1*6DIGIT ]
|
||||
//
|
||||
// The year is zero-padded to four digits and then grows as wide as it needs, the
|
||||
// fractional part is omitted when it is zero and never carries trailing zeros, and " BC"
|
||||
// comes last, after any time zone. Go's layout language can express none of those, which
|
||||
// is why the format is written out here rather than left to time.Format.
|
||||
//
|
||||
// This is the only implementation of the format in pgx. pgtype's date, timestamp and
|
||||
// timestamptz text encoders and the simple protocol's query sanitizer all go through it,
|
||||
// so they cannot drift apart.
|
||||
package pgdatetime
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// AppendDate appends t's date. The fields are read from t in its own location.
|
||||
func AppendDate(buf []byte, t time.Time) []byte {
|
||||
year, bc := splitBCYear(t.Year())
|
||||
buf = appendDate(buf, year, int(t.Month()), t.Day())
|
||||
return appendEra(buf, bc)
|
||||
}
|
||||
|
||||
// AppendTimestamp appends t's date and time of day followed by zone, which goes before
|
||||
// the era suffix because PostgreSQL writes " BC" last. zone is "Z" for a value already
|
||||
// converted to UTC and "" for a type that carries no time zone at all.
|
||||
//
|
||||
// The fields are read from t in its own location, so a caller that wants the UTC instant
|
||||
// must convert first. Sub-microsecond precision is discarded, matching the resolution of
|
||||
// the wire format.
|
||||
func AppendTimestamp(buf []byte, t time.Time, zone string) []byte {
|
||||
year, bc := splitBCYear(t.Year())
|
||||
buf = appendDate(buf, year, int(t.Month()), t.Day())
|
||||
buf = append(buf, ' ')
|
||||
buf = appendTime(buf, t.Hour(), t.Minute(), t.Second(), t.Nanosecond())
|
||||
buf = append(buf, zone...)
|
||||
return appendEra(buf, bc)
|
||||
}
|
||||
|
||||
// splitBCYear converts an astronomical year, in which 1 BC is 0 and 2 BC is -1, to the
|
||||
// year and era PostgreSQL writes.
|
||||
func splitBCYear(year int) (displayYear int, bc bool) {
|
||||
if year <= 0 {
|
||||
return 1 - year, true
|
||||
}
|
||||
return year, false
|
||||
}
|
||||
|
||||
func appendEra(buf []byte, bc bool) []byte {
|
||||
if bc {
|
||||
buf = append(buf, " BC"...)
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
// appendDate appends year-month-day. year is a displayed year from splitBCYear rather
|
||||
// than an astronomical one.
|
||||
func appendDate(buf []byte, year, month, day int) []byte {
|
||||
buf = appendYear(buf, year)
|
||||
buf = append(buf, '-')
|
||||
buf = append2Digits(buf, month)
|
||||
buf = append(buf, '-')
|
||||
return append2Digits(buf, day)
|
||||
}
|
||||
|
||||
func appendTime(buf []byte, hour, min, sec, nsec int) []byte {
|
||||
buf = append2Digits(buf, hour)
|
||||
buf = append(buf, ':')
|
||||
buf = append2Digits(buf, min)
|
||||
buf = append(buf, ':')
|
||||
buf = append2Digits(buf, sec)
|
||||
|
||||
usec := nsec / 1000
|
||||
if usec == 0 {
|
||||
return buf
|
||||
}
|
||||
|
||||
var frac [6]byte
|
||||
for i := 5; i >= 0; i-- {
|
||||
frac[i] = byte('0' + usec%10)
|
||||
usec /= 10
|
||||
}
|
||||
|
||||
// The server trims trailing zeros, so ".5" rather than ".500000".
|
||||
end := len(frac)
|
||||
for end > 1 && frac[end-1] == '0' {
|
||||
end--
|
||||
}
|
||||
|
||||
buf = append(buf, '.')
|
||||
return append(buf, frac[:end]...)
|
||||
}
|
||||
|
||||
// append2Digits appends v as exactly two digits. Every field but the year is fixed width
|
||||
// and comes from a time.Time accessor, so v is always in [0, 99] and the general routine
|
||||
// below is not needed.
|
||||
func append2Digits(buf []byte, v int) []byte {
|
||||
return append(buf, byte('0'+v/10), byte('0'+v%10))
|
||||
}
|
||||
|
||||
// appendYear appends v zero-padded to four digits, or wider when the year needs it. v is
|
||||
// a displayed year from splitBCYear and so is always positive.
|
||||
func appendYear(buf []byte, v int) []byte {
|
||||
var tmp [20]byte
|
||||
s := strconv.AppendInt(tmp[:0], int64(v), 10)
|
||||
for i := len(s); i < 4; i++ {
|
||||
buf = append(buf, '0')
|
||||
}
|
||||
return append(buf, s...)
|
||||
}
|
||||
+4
-2
@@ -1,6 +1,8 @@
|
||||
// Package pgio is a low-level toolkit building messages in the PostgreSQL wire protocol.
|
||||
// Package pgio is a low-level toolkit for building and parsing messages in the
|
||||
// PostgreSQL wire protocol.
|
||||
/*
|
||||
pgio provides functions for appending integers to a []byte while doing byte
|
||||
order conversion.
|
||||
order conversion, and a bounds-checked Reader for parsing binary values from
|
||||
untrusted input.
|
||||
*/
|
||||
package pgio
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
package pgio
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ErrInsufficientBytes is wrapped by all Reader errors caused by a read past
|
||||
// the end of the source.
|
||||
var ErrInsufficientBytes = errors.New("insufficient bytes")
|
||||
|
||||
// Reader is a bounds-checked reader for the PostgreSQL binary format. It is
|
||||
// designed so that decoders of untrusted input cannot forget a length check:
|
||||
// every read validates against the remaining bytes, and the first failure
|
||||
// sticks. After a failure all subsequent reads return zero values, so a
|
||||
// decoder can read an entire structure without intermediate error checks and
|
||||
// inspect Err or Finish once at the end.
|
||||
//
|
||||
// Reads never panic. A decoder that branches on a value it just read (e.g. an
|
||||
// element count used to size an allocation) should check Err before acting on
|
||||
// the value.
|
||||
type Reader struct {
|
||||
s []byte
|
||||
rp int
|
||||
err error
|
||||
}
|
||||
|
||||
func NewReader(s []byte) *Reader {
|
||||
return &Reader{s: s}
|
||||
}
|
||||
|
||||
func (r *Reader) fail(err error) {
|
||||
if r.err == nil {
|
||||
r.err = err
|
||||
}
|
||||
}
|
||||
|
||||
// need reports whether n more bytes are available, recording an error if not.
|
||||
//
|
||||
// The error is built by failShort rather than here so that need stays within
|
||||
// the inliner's budget. Reads of fixed-size values are the hottest path in the
|
||||
// driver, and an un-inlined bounds check costs more than the read itself.
|
||||
func (r *Reader) need(n int) bool {
|
||||
if r.err != nil {
|
||||
return false
|
||||
}
|
||||
if len(r.s)-r.rp < n {
|
||||
r.failShort(n)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *Reader) failShort(n int) {
|
||||
r.fail(fmt.Errorf("%w: %d needed at offset %d, %d remain", ErrInsufficientBytes, n, r.rp, len(r.s)-r.rp))
|
||||
}
|
||||
|
||||
// Err returns the first error encountered, if any.
|
||||
func (r *Reader) Err() error {
|
||||
return r.err
|
||||
}
|
||||
|
||||
// Remaining returns the number of unread bytes.
|
||||
func (r *Reader) Remaining() int {
|
||||
return len(r.s) - r.rp
|
||||
}
|
||||
|
||||
func (r *Reader) Byte() byte {
|
||||
if !r.need(1) {
|
||||
return 0
|
||||
}
|
||||
b := r.s[r.rp]
|
||||
r.rp += 1
|
||||
return b
|
||||
}
|
||||
|
||||
func (r *Reader) Uint16() uint16 {
|
||||
if !r.need(2) {
|
||||
return 0
|
||||
}
|
||||
n := binary.BigEndian.Uint16(r.s[r.rp:])
|
||||
r.rp += 2
|
||||
return n
|
||||
}
|
||||
|
||||
func (r *Reader) Int16() int16 {
|
||||
return int16(r.Uint16())
|
||||
}
|
||||
|
||||
func (r *Reader) Uint32() uint32 {
|
||||
if !r.need(4) {
|
||||
return 0
|
||||
}
|
||||
n := binary.BigEndian.Uint32(r.s[r.rp:])
|
||||
r.rp += 4
|
||||
return n
|
||||
}
|
||||
|
||||
func (r *Reader) Int32() int32 {
|
||||
return int32(r.Uint32())
|
||||
}
|
||||
|
||||
func (r *Reader) Uint64() uint64 {
|
||||
if !r.need(8) {
|
||||
return 0
|
||||
}
|
||||
n := binary.BigEndian.Uint64(r.s[r.rp:])
|
||||
r.rp += 8
|
||||
return n
|
||||
}
|
||||
|
||||
func (r *Reader) Int64() int64 {
|
||||
return int64(r.Uint64())
|
||||
}
|
||||
|
||||
// Bytes reads the next n bytes. The returned slice aliases the source; it is
|
||||
// not a copy.
|
||||
func (r *Reader) Bytes(n int) []byte {
|
||||
if n < 0 {
|
||||
r.fail(fmt.Errorf("invalid byte count %d at offset %d", n, r.rp))
|
||||
return nil
|
||||
}
|
||||
if !r.need(n) {
|
||||
return nil
|
||||
}
|
||||
b := r.s[r.rp : r.rp+n]
|
||||
r.rp += n
|
||||
return b
|
||||
}
|
||||
|
||||
// CString reads a NUL-terminated string, returning the bytes before the
|
||||
// terminator and consuming the terminator. The returned slice aliases the
|
||||
// source; it is not a copy.
|
||||
func (r *Reader) CString() []byte {
|
||||
if r.err != nil {
|
||||
return nil
|
||||
}
|
||||
i := bytes.IndexByte(r.s[r.rp:], 0)
|
||||
if i < 0 {
|
||||
r.fail(fmt.Errorf("%w: unterminated string at offset %d", ErrInsufficientBytes, r.rp))
|
||||
return nil
|
||||
}
|
||||
b := r.s[r.rp : r.rp+i]
|
||||
r.rp += i + 1
|
||||
return b
|
||||
}
|
||||
|
||||
// Count reads an int32 element count and validates it against the remaining
|
||||
// bytes: the count must be non-negative, and since each element occupies at
|
||||
// least minElemSize bytes, count*minElemSize must not exceed the remaining
|
||||
// message. This bounds allocations sized from the count against a malicious
|
||||
// or corrupt message claiming a huge count. Returns 0 on any failure.
|
||||
func (r *Reader) Count(minElemSize int) int {
|
||||
offset := r.rp
|
||||
count := int(r.Int32())
|
||||
if r.err != nil {
|
||||
return 0
|
||||
}
|
||||
if count < 0 {
|
||||
r.fail(fmt.Errorf("invalid element count %d at offset %d", count, offset))
|
||||
return 0
|
||||
}
|
||||
if minElemSize < 1 {
|
||||
minElemSize = 1
|
||||
}
|
||||
if count > r.Remaining()/minElemSize {
|
||||
r.fail(fmt.Errorf("element count %d at offset %d exceeds %d remaining bytes", count, offset, r.Remaining()))
|
||||
return 0
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// Value reads an int32 length followed by that many bytes — the standard
|
||||
// PostgreSQL binary representation of a value. A length of -1 means NULL and
|
||||
// returns (nil, true). Any other negative length is an error. The returned
|
||||
// slice aliases the source; null is only meaningful if Err returns nil.
|
||||
func (r *Reader) Value() (data []byte, null bool) {
|
||||
offset := r.rp
|
||||
length := r.Int32()
|
||||
if r.err != nil {
|
||||
return nil, false
|
||||
}
|
||||
if length == -1 {
|
||||
return nil, true
|
||||
}
|
||||
if length < 0 {
|
||||
r.fail(fmt.Errorf("invalid value length %d at offset %d", length, offset))
|
||||
return nil, false
|
||||
}
|
||||
return r.Bytes(int(length)), false
|
||||
}
|
||||
|
||||
// Finish returns the first error encountered, or an error if unread bytes
|
||||
// remain. Decoders that must consume the entire source should end with Finish.
|
||||
func (r *Reader) Finish() error {
|
||||
if r.err != nil {
|
||||
return r.err
|
||||
}
|
||||
if r.rp != len(r.s) {
|
||||
return r.errTrailing()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reader) errTrailing() error {
|
||||
return fmt.Errorf("%d unexpected trailing bytes at offset %d", len(r.s)-r.rp, r.rp)
|
||||
}
|
||||
|
||||
// ErrInvalidLength is wrapped by the errors returned from the exact-length
|
||||
// read functions below.
|
||||
var ErrInvalidLength = errors.New("invalid length")
|
||||
|
||||
func errLength(want, got int) error {
|
||||
return fmt.Errorf("%w: expected %d bytes, got %d", ErrInvalidLength, want, got)
|
||||
}
|
||||
|
||||
// The Uint*Exact functions read a single fixed-size value that makes up an
|
||||
// entire message, which is what the scan plans for the fixed-size PostgreSQL
|
||||
// types receive. They are the counterpart to Reader for values that have no
|
||||
// internal structure: there is no position to track and no error to make
|
||||
// sticky, just an exact-length assertion the caller cannot skip. Keeping them
|
||||
// separate from Reader is deliberate — these are the hottest decode paths in
|
||||
// the driver and they are small enough for the compiler to inline, which a
|
||||
// Reader method carrying a bounds check and a read pointer is not.
|
||||
|
||||
// Uint16Exact returns the big-endian uint16 in src, which must be exactly 2 bytes.
|
||||
func Uint16Exact(src []byte) (uint16, error) {
|
||||
if len(src) != 2 {
|
||||
return 0, errLength(2, len(src))
|
||||
}
|
||||
return binary.BigEndian.Uint16(src), nil
|
||||
}
|
||||
|
||||
// Uint32Exact returns the big-endian uint32 in src, which must be exactly 4 bytes.
|
||||
func Uint32Exact(src []byte) (uint32, error) {
|
||||
if len(src) != 4 {
|
||||
return 0, errLength(4, len(src))
|
||||
}
|
||||
return binary.BigEndian.Uint32(src), nil
|
||||
}
|
||||
|
||||
// Uint64Exact returns the big-endian uint64 in src, which must be exactly 8 bytes.
|
||||
func Uint64Exact(src []byte) (uint64, error) {
|
||||
if len(src) != 8 {
|
||||
return 0, errLength(8, len(src))
|
||||
}
|
||||
return binary.BigEndian.Uint64(src), nil
|
||||
}
|
||||
+8
-5
@@ -11,6 +11,8 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5/internal/pgdatetime"
|
||||
)
|
||||
|
||||
// Part is either a string or an int. A string is raw SQL. An int is a
|
||||
@@ -81,8 +83,12 @@ func (q *Query) Sanitize(args ...any) (string, error) {
|
||||
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'")
|
||||
// pgtype's timestamptz text encoder writes the same format. Going through
|
||||
// the same code keeps the two from drifting apart, and time.Format cannot
|
||||
// express PostgreSQL's BC era or its variable width year anyway.
|
||||
p = append(buf.AvailableBuffer(), '\'')
|
||||
p = pgdatetime.AppendTimestamp(p, arg.UTC(), "Z")
|
||||
p = append(p, '\'')
|
||||
default:
|
||||
return "", fmt.Errorf("invalid arg type: %T", arg)
|
||||
}
|
||||
@@ -444,9 +450,6 @@ func oneLineCommentState(l *sqlLexer) stateFn {
|
||||
l.pos += width
|
||||
|
||||
switch r {
|
||||
case '\\':
|
||||
_, width = utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
case '\n', '\r':
|
||||
return rawState
|
||||
case utf8.RuneError:
|
||||
|
||||
+1
-1
@@ -62,7 +62,7 @@ func (c *LRUCache) Put(sd *pgconn.StatementDescription) {
|
||||
return
|
||||
}
|
||||
|
||||
// The statement may have been invalidated but not yet handled. Do not readd it to the cache.
|
||||
// The statement may have been invalidated but not yet handled. Do not re-add it to the cache.
|
||||
if _, invalidated := c.invalidSet[sd.SQL]; invalidated {
|
||||
return
|
||||
}
|
||||
|
||||
+167
-2
@@ -1,8 +1,173 @@
|
||||
# mise is this project's single development entry point: the same `mise run <task>` works on
|
||||
# native macOS, on native Linux, and inside the devcontainer. See DEVELOPMENT.md.
|
||||
#
|
||||
# The division of labour:
|
||||
# mise tool versions, this checkout's environment, one-shot tasks
|
||||
# process-compose long-running services (process-compose.yaml) — five PostgreSQL clusters + CRDB
|
||||
# port-tamer this checkout's TCP ports (port-tamer.toml -> .dev/ports.env)
|
||||
#
|
||||
# PostgreSQL itself is the one prerequisite mise does not provide; DEVELOPMENT.md §1 lists it.
|
||||
|
||||
[tools]
|
||||
go = '1.26.3'
|
||||
go = '1.27.0'
|
||||
ruby = '4.0.4'
|
||||
"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'
|
||||
|
||||
# The linter .golangci.yml configures and CLAUDE.md documents. It was never actually provisioned
|
||||
# by the devcontainer, so `golangci-lint run ./...` only worked if you had installed it yourself.
|
||||
golangci-lint = '2.13.2'
|
||||
|
||||
# The process supervisor for the long-running development services. Pinned like every other tool
|
||||
# so macOS, Linux, and the devcontainer run the same version.
|
||||
process-compose = '1.122.0'
|
||||
|
||||
# Per-checkout TCP port allocation. The `github:` backend takes the prebuilt release binary, so it
|
||||
# does not depend on the Go toolchain this repo pins.
|
||||
"github:jackc/port-tamer" = '0.1.0'
|
||||
|
||||
# The CockroachDB test target. Previously a container image; the version tracks the one CI installs
|
||||
# in ci/setup_test.bash.
|
||||
cockroach = '25.4.4'
|
||||
|
||||
# --- Environment ---------------------------------------------------------------------------------
|
||||
#
|
||||
# This checkout's own service endpoints. Loading them here is what makes the per-checkout clusters
|
||||
# the DEFAULT: a bare `psql` and a bare `go test ./...` read PG*/PGX_TEST_* from the environment,
|
||||
# so pointing those at .dev/ in one place moves every consumer at once.
|
||||
#
|
||||
# Two files with two owners, and the order matters — the derived values are read after the
|
||||
# allocation they come from:
|
||||
#
|
||||
# .dev/ports.env port-tamer's state file (port-tamer.toml declares the names). NAME=<port>
|
||||
# lines only; port-tamer rewrites it canonically and rejects anything else.
|
||||
# .dev/derived.env PGHOST/PGPORT/PGUSER/PGDATABASE plus the default target's PGX_TEST_* set —
|
||||
# scripts/devenv.rb, via scripts/lib/test_targets.rb.
|
||||
#
|
||||
# Both are generated per checkout and gitignored; `mise run dev:init` creates them. Their absence
|
||||
# is not an error — mise skips a missing file and PG* falls back to whatever the shell already had.
|
||||
[env]
|
||||
_.file = ['.dev/ports.env', '.dev/derived.env']
|
||||
|
||||
# Homebrew's postgresql@<major> formulas are KEG-ONLY: nothing is linked into the prefix bin, so
|
||||
# psql and pg_isready are not on PATH after `brew install`. The scripts that need the SERVER
|
||||
# binaries resolve them per major explicitly (scripts/lib/pg_bin.rb), but the CLIENT tools are
|
||||
# invoked by name from the readiness probes, `rake db:psql`, and the database bootstrap.
|
||||
#
|
||||
# The newest major's client is used for every server: libpq is backward compatible, so one psql
|
||||
# talks to all five clusters. Both standard Homebrew prefixes are listed (Apple silicon, then
|
||||
# Intel). Neither exists on Linux, where a nonexistent PATH entry is simply ignored, so this is
|
||||
# inert in the devcontainer.
|
||||
_.path = [
|
||||
'/opt/homebrew/opt/postgresql@18/bin',
|
||||
'/usr/local/opt/postgresql@18/bin',
|
||||
]
|
||||
|
||||
# process-compose's control API address. The port comes from this checkout's allocation
|
||||
# (PC_PORT_NUM in .dev/ports.env), so every `process-compose ...` command reaches THIS checkout's
|
||||
# stack with no flags.
|
||||
PC_ADDRESS = "127.0.0.1"
|
||||
|
||||
# Kept separate deliberately: `mise run dev` writes the supervisor log, and a client command such
|
||||
# as `process-compose process list` would otherwise truncate the log of the stack it is inspecting.
|
||||
PC_SERVER_LOG_FILE = "{{config_root}}/.dev/process-compose.log"
|
||||
PC_LOG_FILE = "{{config_root}}/.dev/process-compose-client.log"
|
||||
|
||||
# --- Tasks: the project's development interface ---------------------------------------------------
|
||||
#
|
||||
# Thin wrappers. The logic lives in scripts/ and the Rakefile; these exist so a workflow is
|
||||
# reachable without knowing what is underneath, and so the same command works in every environment.
|
||||
|
||||
[tasks."dev:init"]
|
||||
description = "Bootstrap this checkout: allocate its ports, decode its certificates"
|
||||
run = "ruby scripts/devenv.rb ensure"
|
||||
|
||||
[tasks.dev]
|
||||
description = "Start PostgreSQL 18 and this checkout's on-demand database supervisor"
|
||||
run = "ruby scripts/dev.rb"
|
||||
|
||||
[tasks."dev:all"]
|
||||
description = "Start PostgreSQL 14-18 and CockroachDB eagerly under process-compose"
|
||||
run = "ruby scripts/dev.rb all"
|
||||
|
||||
[tasks."dev:down"]
|
||||
description = "Stop this checkout's development stack"
|
||||
run = "ruby scripts/dev.rb down"
|
||||
|
||||
[tasks."dev:wait"]
|
||||
description = "Wait for a detached development stack to become ready"
|
||||
run = "ruby scripts/dev_ready.rb --wait"
|
||||
|
||||
[tasks."dev:ready"]
|
||||
description = "Require the development stack to be running"
|
||||
run = "ruby scripts/dev_ready.rb"
|
||||
hide = true
|
||||
|
||||
[tasks."dev:ports"]
|
||||
description = "Print this checkout's port allocation and where each server's data lives"
|
||||
run = "rake dev:ports:show"
|
||||
|
||||
[tasks."dev:ports:ensure"]
|
||||
description = "Allocate this checkout's ports if it has none (idempotent)"
|
||||
run = "rake dev:ports:ensure"
|
||||
|
||||
[tasks."dev:ports:overwrite"]
|
||||
description = "Move this checkout to a different port group (stop its services first)"
|
||||
run = "rake dev:ports:overwrite"
|
||||
|
||||
# --- Databases -----------------------------------------------------------------------------------
|
||||
|
||||
[tasks."db:start"]
|
||||
description = "Prewarm database targets (default: pg18); e.g. mise run db:start pg16 crdb"
|
||||
run = "ruby scripts/dev_services.rb start"
|
||||
|
||||
[tasks."db:stop"]
|
||||
description = "Stop database targets (default: pg18); e.g. mise run db:stop pg16 crdb"
|
||||
run = "ruby scripts/dev_services.rb stop"
|
||||
|
||||
# These call scripts/devdb.rb rather than the equivalent rake tasks. mise APPENDS a task's
|
||||
# arguments to its `run` line, and `rake db:reset 16` does not mean "db:reset with the argument
|
||||
# 16" — rake reads the 16 as a SECOND TASK, runs db:reset with no major (which is every cluster),
|
||||
# and only then fails on the unknown task. devdb.rb takes the major as an ordinary argument, so
|
||||
# `mise run db:reset 16` reaches it as written. `rake db:reset[16]` is still the rake spelling.
|
||||
|
||||
[tasks."db:init"]
|
||||
description = "Create this checkout's PostgreSQL clusters under .dev (idempotent); e.g. mise run db:init 16"
|
||||
run = "ruby scripts/devdb.rb init"
|
||||
|
||||
[tasks."db:psql"]
|
||||
description = "psql against one of this checkout's clusters (default: the newest major)"
|
||||
run = "ruby scripts/devdb.rb psql"
|
||||
|
||||
[tasks."db:setup"]
|
||||
description = "Create pgx_test and its roles in a running cluster (idempotent)"
|
||||
run = "ruby scripts/devdb.rb setup"
|
||||
|
||||
[tasks."db:reset"]
|
||||
description = "Destroy and recreate this checkout's clusters (destructive; CONFIRM=yes, stack down)"
|
||||
run = "ruby scripts/devdb.rb reset"
|
||||
|
||||
# --- Test, format, generate ------------------------------------------------------------------------
|
||||
|
||||
[tasks.test]
|
||||
description = "Run the test suite against one target (default pg18); e.g. mise run test pg16"
|
||||
run = "./test.sh"
|
||||
|
||||
[tasks."test:all"]
|
||||
description = "Run the test suite against every target: PostgreSQL 14-18 and CockroachDB"
|
||||
run = "./test.sh all"
|
||||
|
||||
[tasks.fmt]
|
||||
description = "Format all Go sources with goimports"
|
||||
run = "goimports -w ."
|
||||
|
||||
[tasks.lint]
|
||||
description = "Run the linters configured in .golangci.yml"
|
||||
run = "golangci-lint run ./..."
|
||||
|
||||
[tasks.generate]
|
||||
description = "Regenerate the ERB-templated Go sources"
|
||||
run = "rake generate"
|
||||
+107
-34
@@ -151,13 +151,18 @@ func dbTagKey(sf reflect.StructField) (key string, ok bool, err error) {
|
||||
|
||||
type namedArg string
|
||||
|
||||
// utf8.RuneError is returned both for a decoding failure and for a literal U+FFFD, which is a valid
|
||||
// character in a query. Only the former ends the input.
|
||||
const replacementcharacterwidth = 3
|
||||
|
||||
type sqlLexer struct {
|
||||
src string
|
||||
start int
|
||||
pos int
|
||||
nested int // multiline comment nesting level.
|
||||
stateFn stateFn
|
||||
parts []any
|
||||
src string
|
||||
start int
|
||||
pos int
|
||||
nested int // multiline comment nesting level.
|
||||
dollarTag string // active dollar-quote delimiter, including both '$' characters.
|
||||
stateFn stateFn
|
||||
parts []any
|
||||
|
||||
nameToOrdinal map[namedArg]int
|
||||
}
|
||||
@@ -222,6 +227,12 @@ func rawState(l *sqlLexer) stateFn {
|
||||
return singleQuoteState
|
||||
case '"':
|
||||
return doubleQuoteState
|
||||
case '$':
|
||||
if tagLen, ok := scanDollarQuoteTag(l.src[l.pos:]); ok {
|
||||
l.dollarTag = l.src[l.pos-1 : l.pos+tagLen+1]
|
||||
l.pos += tagLen + 1
|
||||
return dollarQuoteState
|
||||
}
|
||||
case '@':
|
||||
nextRune, _ := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if isLetter(nextRune) || nextRune == '_' {
|
||||
@@ -244,15 +255,70 @@ func rawState(l *sqlLexer) stateFn {
|
||||
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
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
// A dollar sign within an unquoted identifier does not start a
|
||||
// dollar-quoted string. Consume identifiers as a single token.
|
||||
if isSQLIdentifierStart(r) {
|
||||
for l.pos < len(l.src) {
|
||||
next, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
if next == utf8.RuneError && width != replacementcharacterwidth {
|
||||
break
|
||||
}
|
||||
if !(isSQLIdentifierStart(next) || next >= '0' && next <= '9' || next == '$') {
|
||||
break
|
||||
}
|
||||
l.pos += width
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isSQLIdentifierStart(r rune) bool {
|
||||
return isLetter(r) || r == '_' || r >= 0x80
|
||||
}
|
||||
|
||||
// scanDollarQuoteTag scans an optional tag and its terminating '$', starting
|
||||
// just after the opening '$'. Tags follow PostgreSQL's unquoted identifier
|
||||
// rules except that they cannot contain '$'.
|
||||
func scanDollarQuoteTag(src string) (int, bool) {
|
||||
for i := 0; i < len(src); {
|
||||
r, width := utf8.DecodeRuneInString(src[i:])
|
||||
if r == '$' {
|
||||
return i, true
|
||||
}
|
||||
if r == utf8.RuneError && width != replacementcharacterwidth {
|
||||
return 0, false
|
||||
}
|
||||
if !(isSQLIdentifierStart(r) || i > 0 && r >= '0' && r <= '9') {
|
||||
return 0, false
|
||||
}
|
||||
i += width
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func dollarQuoteState(l *sqlLexer) stateFn {
|
||||
idx := strings.Index(l.src[l.pos:], l.dollarTag)
|
||||
if idx < 0 {
|
||||
// Preserve unterminated literals, leaving syntax validation to PostgreSQL.
|
||||
l.parts = append(l.parts, l.src[l.start:])
|
||||
l.pos = len(l.src)
|
||||
l.start = l.pos
|
||||
return nil
|
||||
}
|
||||
l.pos += idx + len(l.dollarTag)
|
||||
l.dollarTag = ""
|
||||
return rawState
|
||||
}
|
||||
|
||||
func isLetter(r rune) bool {
|
||||
return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')
|
||||
}
|
||||
@@ -262,7 +328,7 @@ func namedArgState(l *sqlLexer) stateFn {
|
||||
r, width := utf8.DecodeRuneInString(l.src[l.pos:])
|
||||
l.pos += width
|
||||
|
||||
if r == utf8.RuneError {
|
||||
if r == utf8.RuneError && width != replacementcharacterwidth {
|
||||
if l.pos-l.start > 0 {
|
||||
na := namedArg(l.src[l.start:l.pos])
|
||||
if _, found := l.nameToOrdinal[na]; !found {
|
||||
@@ -298,11 +364,13 @@ func singleQuoteState(l *sqlLexer) stateFn {
|
||||
}
|
||||
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
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -320,11 +388,13 @@ func doubleQuoteState(l *sqlLexer) stateFn {
|
||||
}
|
||||
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
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -345,11 +415,13 @@ func escapeStringState(l *sqlLexer) stateFn {
|
||||
}
|
||||
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
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -360,17 +432,16 @@ func oneLineCommentState(l *sqlLexer) stateFn {
|
||||
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
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -400,11 +471,13 @@ func multilineCommentState(l *sqlLexer) stateFn {
|
||||
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
|
||||
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
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -32,7 +32,10 @@ func (c *PgConn) oauthAuth(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
msg, err := c.receiveMessage()
|
||||
// Leave AuthenticationOk for the startup loop, which validates authentication
|
||||
// policy and records completion for every authentication method. All other
|
||||
// responses below fail authentication and cause the connection to close.
|
||||
msg, err := c.peekMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+39
-20
@@ -28,6 +28,7 @@ import (
|
||||
"hash"
|
||||
"slices"
|
||||
"strconv"
|
||||
"unicode"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgproto3"
|
||||
"golang.org/x/text/secure/precis"
|
||||
@@ -39,16 +40,18 @@ const (
|
||||
scramSHA256PlusName = "SCRAM-SHA-256-PLUS"
|
||||
)
|
||||
|
||||
// Perform SCRAM authentication.
|
||||
func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
|
||||
// Perform SCRAM authentication and report whether the completed exchange used
|
||||
// channel binding. A mechanism selection alone is not proof of authentication;
|
||||
// the server signature must be verified before returning channelBound=true.
|
||||
func (c *PgConn) scramAuth(serverAuthMechanisms []string) (channelBound bool, err error) {
|
||||
sc, err := newScramClient(serverAuthMechanisms, c.config.Password)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, 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")
|
||||
return false, 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
|
||||
@@ -56,7 +59,7 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
|
||||
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)
|
||||
return false, 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.
|
||||
@@ -69,7 +72,7 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
|
||||
}
|
||||
|
||||
if c.config.ChannelBinding == "require" && sc.channelBindingData == nil {
|
||||
return errors.New("channel binding required but channel binding data is not available")
|
||||
return false, errors.New("channel binding required but channel binding data is not available")
|
||||
}
|
||||
|
||||
// Send client-first-message in a SASLInitialResponse
|
||||
@@ -80,17 +83,17 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
|
||||
c.frontend.Send(saslInitialResponse)
|
||||
err = c.flushWithPotentialWriteReadDeadlock()
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Receive server-first-message payload in an AuthenticationSASLContinue.
|
||||
saslContinue, err := c.rxSASLContinue()
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
err = sc.recvServerFirstMessage(saslContinue.Data)
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Send client-final-message in a SASLResponse
|
||||
@@ -100,15 +103,18 @@ func (c *PgConn) scramAuth(serverAuthMechanisms []string) error {
|
||||
c.frontend.Send(saslResponse)
|
||||
err = c.flushWithPotentialWriteReadDeadlock()
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Receive server-final-message payload in an AuthenticationSASLFinal.
|
||||
saslFinal, err := c.rxSASLFinal()
|
||||
if err != nil {
|
||||
return err
|
||||
return false, err
|
||||
}
|
||||
return sc.recvServerFinalMessage(saslFinal.Data)
|
||||
if err := sc.recvServerFinalMessage(saslFinal.Data); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return sc.authMechanism == scramSHA256PlusName, nil
|
||||
}
|
||||
|
||||
func (c *PgConn) rxSASLContinue() (*pgproto3.AuthenticationSASLContinue, error) {
|
||||
@@ -192,16 +198,10 @@ func newScramClient(serverAuthMechanisms []string, password string) (*scramClien
|
||||
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
|
||||
}
|
||||
sc.password = normalizeScramPassword(password)
|
||||
|
||||
buf := make([]byte, clientNonceLen)
|
||||
_, err = rand.Read(buf)
|
||||
_, err := rand.Read(buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -211,6 +211,25 @@ func newScramClient(serverAuthMechanisms []string, password string) (*scramClien
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
// normalizeScramPassword preserves PostgreSQL's raw-password fallback for
|
||||
// characters that SASLprep considers unassigned. SASLprep uses Unicode 3.2,
|
||||
// while PRECIS uses newer Unicode tables that can change with x/text or Go
|
||||
// upgrades. Check the original password before PRECIS can change any bytes.
|
||||
func normalizeScramPassword(password string) string {
|
||||
for _, r := range password {
|
||||
if unicode.Is(saslprepUnassigned, r) {
|
||||
return password
|
||||
}
|
||||
}
|
||||
|
||||
normalized, err := precis.OpaqueString.String(password)
|
||||
if err != nil {
|
||||
// PostgreSQL allows passwords invalid according to SCRAM / SASLprep.
|
||||
return password
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
+424
-140
@@ -10,7 +10,6 @@ import (
|
||||
"maps"
|
||||
"math"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
@@ -43,6 +42,11 @@ type Config struct {
|
||||
LookupFunc LookupFunc // e.g. net.Resolver.LookupHost
|
||||
BuildFrontend BuildFrontendFunc
|
||||
|
||||
// MaxProtocolMessageBodyLen is the maximum length of a PostgreSQL wire protocol message body in octets. If a
|
||||
// message body exceeds this length, reading the message will fail with pgproto3.ExceededMaxBodyLenErr. The default
|
||||
// value is 0, which means no maximum is enforced.
|
||||
MaxProtocolMessageBodyLen int
|
||||
|
||||
// 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
|
||||
@@ -55,6 +59,14 @@ type Config struct {
|
||||
|
||||
SSLNegotiation string // sslnegotiation=postgres or sslnegotiation=direct
|
||||
|
||||
// SSLCertMode controls client certificate usage. Valid values are "disable", "allow", and "require".
|
||||
// The default is "allow"; an empty field is also treated as "allow".
|
||||
// "disable" prevents sending a certificate, even if TLSConfig supplies one.
|
||||
// "require" rejects successful authentication unless the server requested and the client sent a certificate.
|
||||
// TLS session resumption is disabled in "require" mode so that every connection exchanges a certificate.
|
||||
// It does not guarantee that the server validated the certificate.
|
||||
SSLCertMode string
|
||||
|
||||
// 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
|
||||
@@ -107,8 +119,17 @@ type Config struct {
|
||||
RequireAuth string
|
||||
|
||||
createdByParseConfig bool // Used to enforce created by ParseConfig rule.
|
||||
|
||||
// File-backed client certificates are installed only on connection-specific TLS
|
||||
// configs, so callers can override Certificates or GetClientCertificate.
|
||||
clientCertificateLoaders map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error)
|
||||
}
|
||||
|
||||
// defaultPort is the port used when neither the connection string, the environment, nor the
|
||||
// service file supplies one. It is also the per-element fallback for empty entries in a
|
||||
// multi-host port list.
|
||||
const defaultPort = "5432"
|
||||
|
||||
// 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.
|
||||
@@ -137,7 +158,11 @@ type ParseConfigOptions struct {
|
||||
// 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.
|
||||
// ("database"); both are accepted. The URI-only ssl=true alias for sslmode=require is
|
||||
// accepted when either "ssl" or "sslmode" is allowed; an explicit sslmode key or a
|
||||
// non-"true" ssl value only matches its own spelling. Every ssl/sslmode occurrence in
|
||||
// the connection string is validated, including occurrences superseded by a later
|
||||
// repeated parameter.
|
||||
//
|
||||
// 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.
|
||||
@@ -156,8 +181,18 @@ type ParseConfigOptions struct {
|
||||
func (c *Config) Copy() *Config {
|
||||
newConf := new(Config)
|
||||
*newConf = *c
|
||||
if c.clientCertificateLoaders != nil {
|
||||
newConf.clientCertificateLoaders = make(map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error), len(c.clientCertificateLoaders))
|
||||
}
|
||||
cloneTLSConfig := func(config *tls.Config) *tls.Config {
|
||||
cloned := config.Clone()
|
||||
if loader := c.clientCertificateLoaders[config]; loader != nil {
|
||||
newConf.clientCertificateLoaders[cloned] = loader
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
if newConf.TLSConfig != nil {
|
||||
newConf.TLSConfig = c.TLSConfig.Clone()
|
||||
newConf.TLSConfig = cloneTLSConfig(c.TLSConfig)
|
||||
}
|
||||
if newConf.RuntimeParams != nil {
|
||||
newConf.RuntimeParams = make(map[string]string, len(c.RuntimeParams))
|
||||
@@ -169,7 +204,7 @@ func (c *Config) Copy() *Config {
|
||||
newFallback := new(FallbackConfig)
|
||||
*newFallback = *fallback
|
||||
if newFallback.TLSConfig != nil {
|
||||
newFallback.TLSConfig = fallback.TLSConfig.Clone()
|
||||
newFallback.TLSConfig = cloneTLSConfig(fallback.TLSConfig)
|
||||
}
|
||||
newConf.Fallbacks[i] = newFallback
|
||||
}
|
||||
@@ -232,16 +267,21 @@ func NetworkAddress(host string, port uint16) (network, address string) {
|
||||
// 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
|
||||
// user=jack password=secret host=pg.example.com port=5432 dbname=mydb sslmode=verify-full
|
||||
//
|
||||
// # Example URL
|
||||
// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-ca
|
||||
// postgres://jack:secret@pg.example.com:5432/mydb?sslmode=verify-full
|
||||
//
|
||||
// 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.
|
||||
//
|
||||
// Client certificates configured with sslcert and sslkey are reloaded for each TLS certificate request.
|
||||
// Setting TLSConfig.Certificates (including a non-nil empty slice) or TLSConfig.GetClientCertificate overrides
|
||||
// this behavior. Replacing TLSConfig discards its file-backed certificate settings; use Config.Copy to retain
|
||||
// those settings when copying a configuration.
|
||||
//
|
||||
// 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.
|
||||
@@ -307,6 +347,21 @@ func NetworkAddress(host string, port uint16) (network, address string) {
|
||||
// When multiple hosts are specified, libpq allows them to have different passwords set via the .pgpass file. pgconn
|
||||
// does not.
|
||||
//
|
||||
// URL query parameters that libpq does not recognize cause libpq to fail with an "invalid URI query parameter" error.
|
||||
// ParseConfig accepts them: they become runtime parameters or pgx-specific options (e.g. pool_max_conns).
|
||||
//
|
||||
// Connection strings containing a NUL byte are rejected, in both URI and keyword/value form. libpq cannot encounter
|
||||
// one because its conninfo strings are NUL-terminated C strings, but a Go string can carry a NUL into the startup
|
||||
// packet, where it delimits parameters rather than being data. Settings reaching Config by other routes (a service
|
||||
// file, or direct assignment to Config.RuntimeParams, User, or Database) are not checked here; a NUL in those is
|
||||
// caught when the startup message is encoded, and Connect fails rather than sending it.
|
||||
//
|
||||
// Error messages from ParseConfig avoid quoting the unredacted connection string and attempt to redact recognizable
|
||||
// password fields, while libpq quotes the failing input verbatim. This redaction is best effort. An invalid connection
|
||||
// string can be structurally ambiguous, so pgconn cannot guarantee that every password in malformed input will be
|
||||
// identified or redacted. Applications should not assume that parse errors are safe to expose when connection strings
|
||||
// may contain secrets.
|
||||
//
|
||||
// In addition, ParseConfig accepts the following options:
|
||||
//
|
||||
// - servicefile.
|
||||
@@ -325,11 +380,12 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
envSettings := parseEnvSettings()
|
||||
|
||||
connStringSettings := make(map[string]string)
|
||||
var urlMeta parseURLMeta
|
||||
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)
|
||||
connStringSettings, urlMeta, err = parseURLSettings(connString)
|
||||
if err != nil {
|
||||
return nil, &ParseConfigError{ConnString: connString, msg: "failed to parse as URL", err: err}
|
||||
}
|
||||
@@ -346,14 +402,77 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
for _, k := range options.ConnStringAllowedKeys {
|
||||
allowed[canonicalConnStringKey(k)] = struct{}{}
|
||||
}
|
||||
notAllowed := func(k string) error {
|
||||
return &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("connection string key %q is not in ConnStringAllowedKeys", k)}
|
||||
}
|
||||
_, sslAllowed := allowed["ssl"]
|
||||
_, sslmodeAllowed := allowed["sslmode"]
|
||||
|
||||
// Repeated-key handling and the URI ssl=true alias rewrite can remove
|
||||
// ssl/sslmode occurrences from the final settings map, so those two keys
|
||||
// are validated from what the user actually wrote -- every occurrence,
|
||||
// fail closed -- rather than from what survived. The alias itself is
|
||||
// accepted under either spelling, the same way dbname/database are
|
||||
// interchangeable; an explicit sslmode key or a non-"true" ssl value
|
||||
// only matches its own spelling.
|
||||
if urlMeta.sawRawSSLKey && !sslAllowed {
|
||||
return nil, notAllowed("ssl")
|
||||
}
|
||||
if urlMeta.sawExplicitSSLModeKey && !sslmodeAllowed {
|
||||
return nil, notAllowed("sslmode")
|
||||
}
|
||||
if urlMeta.sawSSLTrueAlias && !sslAllowed && !sslmodeAllowed {
|
||||
return nil, notAllowed("ssl")
|
||||
}
|
||||
|
||||
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)}
|
||||
if _, ok := allowed[k]; ok {
|
||||
continue
|
||||
}
|
||||
// A multi-host URI with no explicit ports produces an implied
|
||||
// all-empty port list (e.g. ","), matching libpq. Only that list
|
||||
// -- identified by the parser from the raw syntax, not inferred
|
||||
// from the value -- is exempt from the allow-list: it carries no
|
||||
// user-supplied port text. An explicit empty port (?port= in a
|
||||
// URI or port= in keyword/value form) is user-supplied, and
|
||||
// because a present-but-empty port still shadows PGPORT it must
|
||||
// pass the allow-list like any other key.
|
||||
if k == "port" && urlMeta.impliedEmptyPortList {
|
||||
continue
|
||||
}
|
||||
// A surviving ssl or sslmode entry from a URI was already
|
||||
// validated above against every spelling the user wrote.
|
||||
if k == "ssl" && urlMeta.sawRawSSLKey {
|
||||
continue
|
||||
}
|
||||
if k == "sslmode" && (urlMeta.sawSSLTrueAlias || urlMeta.sawExplicitSSLModeKey) {
|
||||
continue
|
||||
}
|
||||
return nil, notAllowed(k)
|
||||
}
|
||||
}
|
||||
|
||||
settings := mergeSettings(defaultSettings, envSettings, connStringSettings)
|
||||
|
||||
// The home-directory-derived defaults (passfile, servicefile, sslcert,
|
||||
// sslkey, sslrootcert) are already present in settings at this point:
|
||||
// defaultSettings resolves them via the user's home directory, which is
|
||||
// safe and cheap to look up (see defaults.go / defaults_windows.go).
|
||||
//
|
||||
// The default PostgreSQL user name is different: resolving it requires
|
||||
// looking up the OS user account, which can be slow or, in some
|
||||
// restricted container environments, crash the process. So that lookup
|
||||
// is memoized and only performed lazily below, the first time it is
|
||||
// actually needed -- i.e. only when a connection string or environment
|
||||
// does not already supply a user.
|
||||
var cachedOSUserSettings map[string]string
|
||||
lazyOSUserSettings := func() map[string]string {
|
||||
if cachedOSUserSettings == nil {
|
||||
cachedOSUserSettings = osUserSettings()
|
||||
}
|
||||
return cachedOSUserSettings
|
||||
}
|
||||
|
||||
if service, present := settings["service"]; present {
|
||||
serviceSettings, err := parseServiceSettings(settings["servicefile"], service)
|
||||
if err != nil {
|
||||
@@ -363,6 +482,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
settings = mergeSettings(defaultSettings, envSettings, serviceSettings, connStringSettings)
|
||||
}
|
||||
|
||||
// Only fall back to the OS user account for the default PostgreSQL user
|
||||
// name when it was not already supplied by the connection string,
|
||||
// environment, or service file.
|
||||
if settings["user"] == "" {
|
||||
settings = mergeSettings(lazyOSUserSettings(), settings)
|
||||
}
|
||||
|
||||
config := &Config{
|
||||
createdByParseConfig: true,
|
||||
Database: settings["database"],
|
||||
@@ -382,6 +508,16 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
},
|
||||
}
|
||||
|
||||
sslCertMode, present := settings["sslcertmode"]
|
||||
if !present {
|
||||
sslCertMode = "allow"
|
||||
}
|
||||
var err error
|
||||
config.SSLCertMode, err = parseSSLCertMode(sslCertMode)
|
||||
if err != nil {
|
||||
return nil, &ParseConfigError{ConnString: connString, msg: "invalid sslcertmode", err: err}
|
||||
}
|
||||
|
||||
if connectTimeoutSetting, present := settings["connect_timeout"]; present {
|
||||
connectTimeout, err := parseConnectTimeoutSetting(connectTimeoutSetting)
|
||||
if err != nil {
|
||||
@@ -407,6 +543,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
"sslmode": {},
|
||||
"sslkey": {},
|
||||
"sslcert": {},
|
||||
"sslcertmode": {},
|
||||
"sslrootcert": {},
|
||||
"sslnegotiation": {},
|
||||
"sslpassword": {},
|
||||
@@ -442,17 +579,41 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
hosts := strings.Split(settings["host"], ",")
|
||||
ports := strings.Split(settings["port"], ",")
|
||||
|
||||
// Like libpq, if exactly one port is given it applies to all hosts;
|
||||
// otherwise there must be exactly one port per host. Empty list elements
|
||||
// mean "use the default".
|
||||
if len(ports) > 1 && len(ports) != len(hosts) {
|
||||
return nil, &ParseConfigError{ConnString: connString, msg: fmt.Sprintf("could not match %d port numbers to %d hosts", len(ports), len(hosts))}
|
||||
}
|
||||
|
||||
// defaultHost stats candidate socket directories, so resolve it at most
|
||||
// once even when several host list elements are empty. It never returns "".
|
||||
resolvedDefaultHost := ""
|
||||
for i, host := range hosts {
|
||||
var portStr string
|
||||
if i < len(ports) {
|
||||
portStr = ports[i]
|
||||
} else {
|
||||
portStr = ports[0]
|
||||
if host == "" {
|
||||
if resolvedDefaultHost == "" {
|
||||
resolvedDefaultHost = defaultHost()
|
||||
}
|
||||
host = resolvedDefaultHost
|
||||
}
|
||||
|
||||
portStr := ports[0]
|
||||
if len(ports) > 1 {
|
||||
portStr = ports[i]
|
||||
}
|
||||
if portStr == "" {
|
||||
portStr = defaultPort
|
||||
}
|
||||
|
||||
// The strconv error is deliberately not wrapped: it quotes the
|
||||
// offending text, and in a malformed URI the bytes that land in the
|
||||
// port position can be a mislaid password (postgres://u:sec:ret@h
|
||||
// parses "sec:ret@h" as the port). The best-effort-redacted connection
|
||||
// string in ParseConfigError provides the available context without
|
||||
// deliberately quoting the offending port text again.
|
||||
port, err := parsePort(portStr)
|
||||
if err != nil {
|
||||
return nil, &ParseConfigError{ConnString: connString, msg: "invalid port", err: err}
|
||||
return nil, &ParseConfigError{ConnString: connString, msg: "invalid port"}
|
||||
}
|
||||
|
||||
var tlsConfigs []*tls.Config
|
||||
@@ -462,7 +623,7 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
tlsConfigs = append(tlsConfigs, nil)
|
||||
} else {
|
||||
var err error
|
||||
tlsConfigs, err = configTLS(settings, host, options)
|
||||
tlsConfigs, err = config.configTLS(settings, host, options)
|
||||
if err != nil {
|
||||
return nil, &ParseConfigError{ConnString: connString, msg: "failed to configure TLS", err: err}
|
||||
}
|
||||
@@ -483,14 +644,13 @@ func ParseConfigWithOptions(connString string, options ParseConfigOptions) (*Con
|
||||
config.Fallbacks = fallbacks[1:]
|
||||
config.SSLNegotiation = settings["sslnegotiation"]
|
||||
|
||||
passfile, err := pgpassfile.ReadPassfile(settings["passfile"])
|
||||
if err == nil {
|
||||
if config.Password == "" {
|
||||
if config.Password == "" {
|
||||
passfile, err := pgpassfile.ReadPassfile(settings["passfile"])
|
||||
if err == nil {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -591,6 +751,7 @@ func parseEnvSettings() map[string]string {
|
||||
"PGSSLMODE": "sslmode",
|
||||
"PGSSLKEY": "sslkey",
|
||||
"PGSSLCERT": "sslcert",
|
||||
"PGSSLCERTMODE": "sslcertmode",
|
||||
"PGSSLSNI": "sslsni",
|
||||
"PGSSLROOTCERT": "sslrootcert",
|
||||
"PGSSLPASSWORD": "sslpassword",
|
||||
@@ -607,8 +768,9 @@ func parseEnvSettings() map[string]string {
|
||||
}
|
||||
|
||||
for envname, realname := range nameMap {
|
||||
value := os.Getenv(envname)
|
||||
if value != "" {
|
||||
value, present := os.LookupEnv(envname)
|
||||
// Preserve an explicitly empty sslcertmode so it is rejected, like libpq.
|
||||
if value != "" || (present && realname == "sslcertmode") {
|
||||
settings[realname] = value
|
||||
}
|
||||
}
|
||||
@@ -616,76 +778,46 @@ func parseEnvSettings() map[string]string {
|
||||
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}
|
||||
|
||||
// unescapeKeywordValue applies libpq's backslash rule to the raw text of a
|
||||
// keyword/value value: a backslash is dropped and whatever follows it is taken
|
||||
// literally, whatever that character is. A backslash at the very end escapes
|
||||
// the end of the string, so it is dropped and contributes nothing -- which is
|
||||
// how libpq accepts `host=a\`. Only the unquoted branch can reach that case;
|
||||
// inside quotes the escaped terminator leaves the string unterminated and the
|
||||
// caller has already rejected it.
|
||||
func unescapeKeywordValue(s string) string {
|
||||
if !strings.ContainsRune(s, '\\') {
|
||||
return s
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
sb.Grow(len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\\' {
|
||||
i++
|
||||
if i == len(s) {
|
||||
break
|
||||
}
|
||||
}
|
||||
sb.WriteByte(s[i])
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func parseKeywordValueSettings(s string) (map[string]string, error) {
|
||||
settings := make(map[string]string)
|
||||
|
||||
// Reject NUL bytes up front, as parseURLSettings does. libpq never sees one
|
||||
// because its conninfo strings are NUL-terminated C strings; a Go string can
|
||||
// carry a NUL through to the startup packet, where it acts as a parameter
|
||||
// delimiter rather than data. StartupMessage.Encode refuses such parameters,
|
||||
// but failing here reports the problem against the input that caused it.
|
||||
if strings.IndexByte(s, 0) >= 0 {
|
||||
return nil, errors.New("forbidden NUL byte in connection 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")
|
||||
@@ -697,6 +829,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) {
|
||||
}
|
||||
|
||||
key = strings.Trim(s[:eqIdx], " \t\n\r\v\f")
|
||||
// libpq reads a keyword as a run of non-space characters and then
|
||||
// requires the next non-space character to be '=', so whitespace
|
||||
// inside a keyword terminates it and is an error. Trimming alone would
|
||||
// accept the space as part of the key and turn a typo into a bogus
|
||||
// RuntimeParam that only the server rejects. Report it as libpq does,
|
||||
// naming the keyword it had read.
|
||||
if i := strings.IndexAny(key, " \t\n\r\v\f"); i >= 0 {
|
||||
return nil, fmt.Errorf(`missing "=" after %q in connection info string`, key[:i])
|
||||
}
|
||||
s = strings.TrimLeft(s[eqIdx+1:], " \t\n\r\v\f")
|
||||
switch {
|
||||
case len(s) == 0:
|
||||
@@ -708,12 +849,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) {
|
||||
}
|
||||
if s[end] == '\\' {
|
||||
end++
|
||||
// A trailing backslash escapes the end of the string.
|
||||
// libpq drops it and ends the value there. Break rather
|
||||
// than let the loop's post-increment push end past len(s).
|
||||
if end == len(s) {
|
||||
return nil, errors.New("invalid backslash")
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'")
|
||||
val = unescapeKeywordValue(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")
|
||||
@@ -726,12 +870,15 @@ func parseKeywordValueSettings(s string) (map[string]string, error) {
|
||||
}
|
||||
if s[end] == '\\' {
|
||||
end++
|
||||
if end == len(s) {
|
||||
return nil, errors.New("unterminated quoted string in connection info string")
|
||||
}
|
||||
}
|
||||
}
|
||||
if end == len(s) {
|
||||
return nil, errors.New("unterminated quoted string in connection info string")
|
||||
}
|
||||
val = strings.ReplaceAll(strings.ReplaceAll(s[:end], "\\\\", "\\"), "\\'", "'")
|
||||
val = unescapeKeywordValue(s[:end])
|
||||
// Consume the closing quote and any subsequent whitespace.
|
||||
s = strings.TrimLeft(s[end+1:], " \t\n\r\v\f")
|
||||
}
|
||||
@@ -773,12 +920,16 @@ func parseServiceSettings(servicefilePath, serviceName string) (map[string]strin
|
||||
// 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) {
|
||||
func (c *Config) 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"]
|
||||
if settings["sslcertmode"] == "disable" {
|
||||
// Like libpq, do not read client certificate or key files in this mode.
|
||||
sslcert, sslkey = "", ""
|
||||
}
|
||||
sslpassword := settings["sslpassword"]
|
||||
sslsni := settings["sslsni"]
|
||||
sslnegotiation := settings["sslnegotiation"]
|
||||
@@ -892,57 +1043,41 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P
|
||||
}
|
||||
|
||||
if sslcert != "" && sslkey != "" {
|
||||
buf, err := os.ReadFile(sslkey)
|
||||
// Retain the directory used at parse time, while still following symlinks
|
||||
// on each load so certificate rotation can replace their targets.
|
||||
var err error
|
||||
sslcert, err = filepath.Abs(sslcert)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to read sslkey: %w", err)
|
||||
return nil, fmt.Errorf("unable to resolve sslcert: %w", err)
|
||||
}
|
||||
block, _ := pem.Decode(buf)
|
||||
if block == nil {
|
||||
return nil, errors.New("failed to decode sslkey")
|
||||
sslkey, err = filepath.Abs(sslkey)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to resolve sslkey: %w", err)
|
||||
}
|
||||
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)
|
||||
|
||||
// Read the key & cert so
|
||||
// (a) we can provide error feedback now and
|
||||
// (b) invoke the GetSSLPassword callback once if necessary
|
||||
_, resolvedPassword, err := loadClientCertificate(sslcert, sslkey, sslpassword, parseConfigOptions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if c.clientCertificateLoaders == nil {
|
||||
c.clientCertificateLoaders = make(map[*tls.Config]func(*tls.CertificateRequestInfo) (*tls.Certificate, error))
|
||||
}
|
||||
c.clientCertificateLoaders[tlsConfig] = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
cert, _, err := loadClientCertificate(sslcert, sslkey, resolvedPassword, ParseConfigOptions{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pemBytes := pem.Block{
|
||||
Type: "RSA PRIVATE KEY",
|
||||
Bytes: decryptedKey,
|
||||
// Same check crypto/tls provides when passing certs through config.Certificates
|
||||
if cri != nil && cri.SupportsCertificate(&cert) != nil {
|
||||
return new(tls.Certificate), nil
|
||||
}
|
||||
pemKey = pem.EncodeToMemory(&pemBytes)
|
||||
} else {
|
||||
pemKey = pem.EncodeToMemory(block)
|
||||
return &cert, nil
|
||||
}
|
||||
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.
|
||||
@@ -964,6 +1099,144 @@ func configTLS(settings map[string]string, thisHost string, parseConfigOptions P
|
||||
}
|
||||
}
|
||||
|
||||
// loadClientCertificate reads sslcert and sslkey and returns the pair, along
|
||||
// with the password that decrypted the key (empty when the key is not
|
||||
// encrypted). When the key is encrypted and sslpassword does not decrypt it,
|
||||
// parseConfigOptions.GetSSLPassword is asked for one.
|
||||
func loadClientCertificate(sslcert, sslkey, sslpassword string, parseConfigOptions ParseConfigOptions) (tls.Certificate, string, error) {
|
||||
buf, err := os.ReadFile(sslkey)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, "", fmt.Errorf("unable to read sslkey: %w", err)
|
||||
}
|
||||
block, _ := pem.Decode(buf)
|
||||
if block == nil {
|
||||
return tls.Certificate{}, "", 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
|
||||
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 tls.Certificate{}, "", fmt.Errorf("unable to find sslpassword")
|
||||
}
|
||||
}
|
||||
decryptedKey, decryptedError = x509.DecryptPEMBlock(block, []byte(sslpassword))
|
||||
if decryptedError != nil {
|
||||
return tls.Certificate{}, "", fmt.Errorf("unable to decrypt key: %w", decryptedError)
|
||||
}
|
||||
|
||||
pemBytes := pem.Block{
|
||||
// Preserve the old loader's tolerance of non-key PEM labels.
|
||||
// X509KeyPair determines the key format from the decrypted DER.
|
||||
Type: "PRIVATE KEY",
|
||||
Bytes: decryptedKey,
|
||||
}
|
||||
pemKey = pem.EncodeToMemory(&pemBytes)
|
||||
} else {
|
||||
// Hand over the whole file rather than the first block: X509KeyPair
|
||||
// skips blocks that are not a key, so a combined key+certificate file
|
||||
// works whatever order it is written in.
|
||||
pemKey = buf
|
||||
}
|
||||
certfile, err := os.ReadFile(sslcert)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, "", fmt.Errorf("unable to read cert: %w", err)
|
||||
}
|
||||
cert, err := tls.X509KeyPair(certfile, pemKey)
|
||||
if err != nil {
|
||||
return tls.Certificate{}, "", fmt.Errorf("unable to load cert: %w", err)
|
||||
}
|
||||
return cert, sslpassword, nil
|
||||
}
|
||||
|
||||
type sslCertState struct {
|
||||
requested bool
|
||||
sent bool
|
||||
}
|
||||
|
||||
// checkRequired verifies the required certificate exchange during connection startup.
|
||||
// In require mode, a nil state means that no TLS connection was made.
|
||||
func (s *sslCertState) checkRequired() error {
|
||||
if s == nil || !s.requested {
|
||||
return &sslCertModeError{msg: "server did not request an SSL certificate"}
|
||||
}
|
||||
if !s.sent {
|
||||
return &sslCertModeError{msg: "server accepted connection without a valid SSL certificate"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// prepareTLSConfigForConnect prepares certificate reloading and sslcertmode for one connection.
|
||||
// In require mode, the returned state must be checked before accepting AuthenticationOk or ReadyForQuery.
|
||||
// Configs may be shared by concurrent connection attempts, so any callback state must
|
||||
// belong to a clone made for this attempt, not the original config.
|
||||
func (c *Config) prepareTLSConfigForConnect(config *tls.Config) (*tls.Config, *sslCertState) {
|
||||
if c.SSLCertMode != "disable" && config.Certificates == nil && config.GetClientCertificate == nil {
|
||||
if loader := c.clientCertificateLoaders[config]; loader != nil {
|
||||
config = config.Clone()
|
||||
config.GetClientCertificate = loader
|
||||
}
|
||||
}
|
||||
switch c.SSLCertMode {
|
||||
case "disable":
|
||||
config = config.Clone()
|
||||
config.Certificates = nil
|
||||
config.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
return new(tls.Certificate), nil
|
||||
}
|
||||
return config, nil
|
||||
case "require":
|
||||
state := new(sslCertState)
|
||||
original := config
|
||||
config = config.Clone()
|
||||
// Resumed sessions skip the certificate exchange and its callback.
|
||||
config.ClientSessionCache = nil
|
||||
config.GetClientCertificate = func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
state.requested = true
|
||||
var cert *tls.Certificate
|
||||
var err error
|
||||
if original.GetClientCertificate != nil {
|
||||
cert, err = original.GetClientCertificate(cri)
|
||||
} else {
|
||||
// Preserve crypto/tls's default certificate selection, including its
|
||||
// signature scheme and acceptable CA checks.
|
||||
cert = new(tls.Certificate)
|
||||
for i := range original.Certificates {
|
||||
if cri.SupportsCertificate(&original.Certificates[i]) == nil {
|
||||
cert = &original.Certificates[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
state.sent = err == nil && cert != nil && len(cert.Certificate) > 0
|
||||
return cert, err
|
||||
}
|
||||
return config, state
|
||||
default:
|
||||
return config, nil
|
||||
}
|
||||
}
|
||||
|
||||
func parseSSLCertMode(s string) (string, error) {
|
||||
switch s {
|
||||
case "disable", "allow", "require":
|
||||
return s, nil
|
||||
default:
|
||||
return "", fmt.Errorf("unknown sslcertmode value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func parsePort(s string) (uint16, error) {
|
||||
port, err := strconv.ParseUint(s, 10, 16)
|
||||
if err != nil {
|
||||
@@ -1001,6 +1274,17 @@ func makeConnectTimeoutDialFunc(timeout time.Duration) DialFunc {
|
||||
return d.DialContext
|
||||
}
|
||||
|
||||
var (
|
||||
// ErrReadOnlyConnection is returned when a read-write connection is required but the connection is read-only.
|
||||
ErrReadOnlyConnection = errors.New("read only connection")
|
||||
// ErrReadWriteConnection is returned when a read-only connection is required but the connection is read-write.
|
||||
ErrReadWriteConnection = errors.New("connection is not read only")
|
||||
// ErrPrimaryConnection is returned when a standby connection is required but the server is primary.
|
||||
ErrPrimaryConnection = errors.New("server is not in hot standby mode")
|
||||
// ErrStandbyConnection is returned when a primary connection is required but the server is in standby mode.
|
||||
ErrStandbyConnection = errors.New("server is in standby mode")
|
||||
)
|
||||
|
||||
// ValidateConnectTargetSessionAttrsReadWrite is a ValidateConnectFunc that implements libpq compatible
|
||||
// target_session_attrs=read-write.
|
||||
func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgConn) error {
|
||||
@@ -1010,7 +1294,7 @@ func ValidateConnectTargetSessionAttrsReadWrite(ctx context.Context, pgConn *PgC
|
||||
}
|
||||
|
||||
if string(result[0].Rows[0][0]) == "on" {
|
||||
return errors.New("read only connection")
|
||||
return ErrReadOnlyConnection
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -1025,7 +1309,7 @@ func ValidateConnectTargetSessionAttrsReadOnly(ctx context.Context, pgConn *PgCo
|
||||
}
|
||||
|
||||
if string(result[0].Rows[0][0]) != "on" {
|
||||
return errors.New("connection is not read only")
|
||||
return ErrReadWriteConnection
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -1040,7 +1324,7 @@ func ValidateConnectTargetSessionAttrsStandby(ctx context.Context, pgConn *PgCon
|
||||
}
|
||||
|
||||
if string(result[0].Rows[0][0]) != "t" {
|
||||
return errors.New("server is not in hot standby mode")
|
||||
return ErrPrimaryConnection
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -1055,7 +1339,7 @@ func ValidateConnectTargetSessionAttrsPrimary(ctx context.Context, pgConn *PgCon
|
||||
}
|
||||
|
||||
if string(result[0].Rows[0][0]) == "t" {
|
||||
return errors.New("server is in standby mode")
|
||||
return ErrStandbyConnection
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -1070,7 +1354,7 @@ func ValidateConnectTargetSessionAttrsPreferStandby(ctx context.Context, pgConn
|
||||
}
|
||||
|
||||
if string(result[0].Rows[0][0]) != "t" {
|
||||
return &NotPreferredError{err: errors.New("server is not in hot standby mode")}
|
||||
return &NotPreferredError{err: ErrPrimaryConnection}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
+57
-14
@@ -1,5 +1,4 @@
|
||||
//go:build !windows
|
||||
// +build !windows
|
||||
|
||||
package pgconn
|
||||
|
||||
@@ -9,22 +8,46 @@ import (
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// currentOSUser resolves the current OS user account. It is a seam so tests
|
||||
// can simulate os/user.Current failing -- including the unrecoverable
|
||||
// crashes reported in some restricted/broken-NSS container environments --
|
||||
// without needing such an environment.
|
||||
var currentOSUser = user.Current
|
||||
|
||||
// userHomeDir resolves the current user's home directory. It is a seam so
|
||||
// tests can simulate os.UserHomeDir failing without needing to unset $HOME
|
||||
// for the whole process.
|
||||
//
|
||||
// os.UserHomeDir only reads the $HOME environment variable on this platform;
|
||||
// it never calls into cgo or NSS, so unlike os/user.Current it cannot crash
|
||||
// in restricted/broken container environments. That also means it can
|
||||
// resolve a different directory than the OS account's passwd-file home
|
||||
// directory if $HOME has been overridden -- this is an accepted tradeoff so
|
||||
// that home-directory-derived defaults (pgpass, pg_service.conf, client SSL
|
||||
// certificate/key/root files) keep resolving even when the OS user account
|
||||
// lookup itself is unavailable or unsafe to call.
|
||||
var userHomeDir = os.UserHomeDir
|
||||
|
||||
func defaultSettings() map[string]string {
|
||||
settings := make(map[string]string)
|
||||
|
||||
settings["host"] = defaultHost()
|
||||
settings["port"] = "5432"
|
||||
settings["port"] = defaultPort
|
||||
settings["target_session_attrs"] = "any"
|
||||
|
||||
// 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")
|
||||
// The home-directory-derived defaults (~/.pgpass, ~/.pg_service.conf,
|
||||
// and the client SSL certificate/key/root files under ~/.postgresql)
|
||||
// only need the user's home directory, not the full OS user account, so
|
||||
// they are resolved unconditionally here via os.UserHomeDir. This keeps
|
||||
// them available even when looking up the OS user account (needed only
|
||||
// for the default PostgreSQL user name, see osUserSettings) is slow,
|
||||
// fails, or -- in some restricted container environments with a broken
|
||||
// NSS/CGO setup -- would crash the process.
|
||||
if homeDir, err := userHomeDir(); err == nil {
|
||||
settings["passfile"] = filepath.Join(homeDir, ".pgpass")
|
||||
settings["servicefile"] = filepath.Join(homeDir, ".pg_service.conf")
|
||||
sslcert := filepath.Join(homeDir, ".postgresql", "postgresql.crt")
|
||||
sslkey := filepath.Join(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
|
||||
@@ -32,13 +55,33 @@ func defaultSettings() map[string]string {
|
||||
settings["sslkey"] = sslkey
|
||||
}
|
||||
}
|
||||
sslrootcert := filepath.Join(user.HomeDir, ".postgresql", "root.crt")
|
||||
sslrootcert := filepath.Join(homeDir, ".postgresql", "root.crt")
|
||||
if _, err := os.Stat(sslrootcert); err == nil {
|
||||
settings["sslrootcert"] = sslrootcert
|
||||
}
|
||||
}
|
||||
|
||||
settings["target_session_attrs"] = "any"
|
||||
return settings
|
||||
}
|
||||
|
||||
// osUserSettings returns the default PostgreSQL user name derived from the
|
||||
// current OS user account.
|
||||
//
|
||||
// Resolving this requires looking up the OS user account, which can be slow
|
||||
// or, in some restricted container environments (e.g. distroless images
|
||||
// with a broken NSS/CGO setup), crash the process. Callers must only call
|
||||
// osUserSettings when the default user name is not already supplied by the
|
||||
// connection string, environment, or service file.
|
||||
func osUserSettings() map[string]string {
|
||||
settings := make(map[string]string)
|
||||
|
||||
// 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 := currentOSUser()
|
||||
if err == nil {
|
||||
settings["user"] = user.Username
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
+77
-17
@@ -7,28 +7,45 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// currentOSUser resolves the current OS user account. It is a seam so tests
|
||||
// can simulate os/user.Current failing -- including the unrecoverable
|
||||
// crashes reported in some restricted/broken-NSS container environments --
|
||||
// without needing such an environment.
|
||||
var currentOSUser = user.Current
|
||||
|
||||
// userHomeDir resolves the current user's home directory. It is a seam so
|
||||
// tests can simulate os.UserHomeDir failing without needing to unset the
|
||||
// relevant environment variables for the whole process.
|
||||
//
|
||||
// os.UserHomeDir only reads %USERPROFILE% (falling back to
|
||||
// %HOMEDRIVE%+%HOMEPATH%) on this platform; it never calls into the Windows
|
||||
// user account APIs, so unlike os/user.Current it cannot crash in
|
||||
// restricted/broken container environments. That also means it can resolve
|
||||
// a different directory than the OS account API's reported home directory
|
||||
// if those environment variables have been overridden -- this is an
|
||||
// accepted tradeoff so that home-directory-derived defaults (pg_service.conf)
|
||||
// keep resolving even when the OS user account lookup itself is unavailable
|
||||
// or unsafe to call.
|
||||
var userHomeDir = os.UserHomeDir
|
||||
|
||||
func defaultSettings() map[string]string {
|
||||
settings := make(map[string]string)
|
||||
|
||||
settings["host"] = defaultHost()
|
||||
settings["port"] = "5432"
|
||||
settings["port"] = defaultPort
|
||||
settings["target_session_attrs"] = "any"
|
||||
|
||||
// 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
|
||||
// The %APPDATA%\postgresql-derived defaults (pgpass.conf, .pg_service.conf
|
||||
// and the client SSL certificate/key/root files) only need the APPDATA
|
||||
// environment variable, not the full OS user account, so they are resolved
|
||||
// unconditionally here. This keeps them available even when looking up
|
||||
// the OS user account (needed only for the default PostgreSQL user
|
||||
// name, see osUserSettings) is slow, fails, or -- in some restricted
|
||||
// container environments with a broken NSS/CGO setup -- would crash the
|
||||
// process.
|
||||
if appData := os.Getenv("APPDATA"); appData != "" {
|
||||
settings["passfile"] = filepath.Join(appData, "postgresql", "pgpass.conf")
|
||||
settings["servicefile"] = filepath.Join(user.HomeDir, ".pg_service.conf")
|
||||
settings["servicefile"] = filepath.Join(appData, "postgresql", ".pg_service.conf")
|
||||
sslcert := filepath.Join(appData, "postgresql", "postgresql.crt")
|
||||
sslkey := filepath.Join(appData, "postgresql", "postgresql.key")
|
||||
if _, err := os.Stat(sslcert); err == nil {
|
||||
@@ -44,7 +61,50 @@ func defaultSettings() map[string]string {
|
||||
}
|
||||
}
|
||||
|
||||
settings["target_session_attrs"] = "any"
|
||||
// libpq looks for the service file at %APPDATA%\postgresql\.pg_service.conf
|
||||
// on Windows, but pgx used to look for it at ~/.pg_service.conf. Keep
|
||||
// using that file when there is none at the libpq location, so existing
|
||||
// setups keep working. The home directory is resolved the same crash-safe
|
||||
// way as on other platforms (see defaults.go).
|
||||
if homeDir, err := userHomeDir(); err == nil {
|
||||
homeServicefile := filepath.Join(homeDir, ".pg_service.conf")
|
||||
if servicefile, ok := settings["servicefile"]; !ok {
|
||||
settings["servicefile"] = homeServicefile
|
||||
} else if _, err := os.Stat(servicefile); os.IsNotExist(err) {
|
||||
if _, err := os.Stat(homeServicefile); err == nil {
|
||||
settings["servicefile"] = homeServicefile
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
// osUserSettings returns the default PostgreSQL user name derived from the
|
||||
// current OS user account.
|
||||
//
|
||||
// Resolving this requires looking up the OS user account, which can be slow
|
||||
// or, in some restricted container environments (e.g. distroless images
|
||||
// with a broken NSS/CGO setup), crash the process. Callers must only call
|
||||
// osUserSettings when the default user name is not already supplied by the
|
||||
// connection string, environment, or service file.
|
||||
func osUserSettings() map[string]string {
|
||||
settings := make(map[string]string)
|
||||
|
||||
// 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 := currentOSUser()
|
||||
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
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
+12
@@ -34,6 +34,18 @@ explicitly:
|
||||
These parameters may also be set via the PGSSLMODE, PGSSLROOTCERT, PGCHANNELBINDING, and PGREQUIREAUTH environment
|
||||
variables.
|
||||
|
||||
Client Certificates
|
||||
|
||||
The sslcertmode connection parameter (or PGSSLCERTMODE environment variable) controls whether a client certificate
|
||||
is sent. The default, allow, sends a certificate if the server requests one and a suitable certificate is available.
|
||||
The disable mode prevents sending a certificate, including certificates supplied through Config.TLSConfig, and skips
|
||||
loading sslcert and sslkey files. The require mode fails if the server successfully authenticates the client without
|
||||
requesting and receiving a client certificate. It does not guarantee that the server validated the certificate.
|
||||
If this check fails, no further TLS or host fallbacks are tried.
|
||||
TLS session resumption is disabled in require mode so every connection exchanges a certificate.
|
||||
An explicitly empty sslcertmode parameter or PGSSLCERTMODE environment variable is invalid.
|
||||
This parameter is independent of sslmode, which controls TLS and server certificate verification.
|
||||
|
||||
Executing a Query
|
||||
|
||||
ExecParams and ExecPrepared execute a single query. They return readers that iterate over each row. The Read method
|
||||
|
||||
+180
-16
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
@@ -93,10 +92,20 @@ func (e *perDialConnectError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
// sslCertModeError is a client-side authentication failure that must stop
|
||||
// connection fallback, matching libpq's sslcertmode=require behavior.
|
||||
type sslCertModeError struct {
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e *sslCertModeError) Error() string {
|
||||
return e.msg
|
||||
}
|
||||
|
||||
// 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.
|
||||
// errors.Is to test for it, since it is usually wrapped in another error.
|
||||
var ErrConnClosed = errors.New("conn closed")
|
||||
|
||||
type connLockError struct {
|
||||
@@ -118,9 +127,11 @@ func (e *connLockError) Unwrap() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseConfigError is the error returned when a connection string cannot be parsed.
|
||||
// ParseConfigError is the error returned when a connection string cannot be
|
||||
// parsed. Its error text masks recognizable passwords on a best-effort basis,
|
||||
// but malformed input can be too ambiguous to redact completely.
|
||||
type ParseConfigError struct {
|
||||
ConnString string // The connection string that could not be parsed.
|
||||
ConnString string // The original, unredacted connection string that could not be parsed.
|
||||
msg string
|
||||
err error
|
||||
}
|
||||
@@ -134,9 +145,11 @@ func NewParseConfigError(conn, msg string, err error) error {
|
||||
}
|
||||
|
||||
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.
|
||||
// redactPW is necessarily best effort: an invalid connection string can be
|
||||
// too ambiguous to identify every password. Returning only a static string
|
||||
// would be the way to guarantee that Error cannot leak one. The public
|
||||
// ConnString field would still 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)
|
||||
@@ -227,11 +240,12 @@ func newContextAlreadyDoneError(ctx context.Context) (err error) {
|
||||
return &errTimeout{&contextAlreadyDoneError{err: ctx.Err()}}
|
||||
}
|
||||
|
||||
// redactPW masks recognizable password fields on a best-effort basis. It
|
||||
// cannot guarantee redaction when malformed input makes component boundaries
|
||||
// ambiguous.
|
||||
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)
|
||||
}
|
||||
return redactURLPassword(connString)
|
||||
}
|
||||
quotedKV := regexp.MustCompile(`password='[^']*'`)
|
||||
connString = quotedKV.ReplaceAllLiteralString(connString, "password=xxxxx")
|
||||
@@ -242,14 +256,164 @@ func redactPW(connString string) string {
|
||||
return connString
|
||||
}
|
||||
|
||||
func redactURL(u *url.URL) string {
|
||||
if u == nil {
|
||||
return ""
|
||||
// redactURLPassword masks recognizable password values in a connection URI.
|
||||
// For a URI that parses cleanly the component boundaries are certain, and
|
||||
// every password position -- the userinfo password and password/sslpassword
|
||||
// query values -- is reliably masked with the rest of the string left intact.
|
||||
// It is also deliberately usable without a successful parse -- the strings
|
||||
// that reach ParseConfigError are often exactly the ones that failed to parse
|
||||
// -- but malformed syntax can make component boundaries ambiguous, so for
|
||||
// such input redaction is best-effort and may over-mask.
|
||||
//
|
||||
// For URI shapes it recognizes, it mirrors parseURLSettings structurally
|
||||
// rather than pattern-matching the raw text: the userinfo password is whatever
|
||||
// follows the first ':' before the terminating '@' (found with the parser's
|
||||
// lookahead), and a query value is masked when its percent-decoded key
|
||||
// canonicalizes to password or sslpassword. This uses the same decoding as the
|
||||
// parser, so encoded spellings like pass%77ord are caught and the whole
|
||||
// recognized raw value is masked no matter what bytes it contains.
|
||||
func redactURLPassword(connString string) string {
|
||||
const mask = "xxxxx"
|
||||
var b strings.Builder
|
||||
b.Grow(len(connString))
|
||||
|
||||
p := connString
|
||||
for _, prefix := range []string{"postgresql://", "postgres://"} {
|
||||
if rest, ok := strings.CutPrefix(connString, prefix); ok {
|
||||
b.WriteString(prefix)
|
||||
p = rest
|
||||
break
|
||||
}
|
||||
}
|
||||
if _, pwSet := u.User.Password(); pwSet {
|
||||
u.User = url.UserPassword(u.User.Username(), "xxxxx")
|
||||
|
||||
// Userinfo: same lookahead as parseURLSettings.
|
||||
if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' {
|
||||
user, _, hasPassword := strings.Cut(p[:i], ":")
|
||||
p = p[i+1:]
|
||||
b.WriteString(user)
|
||||
if hasPassword {
|
||||
b.WriteString(":" + mask)
|
||||
}
|
||||
b.WriteByte('@')
|
||||
}
|
||||
return u.String()
|
||||
|
||||
// Nothing after the userinfo is a password position, but a password can
|
||||
// land there in malformed URIs: an unencoded '/' or '?' in a userinfo
|
||||
// password turns everything after it into path or query, stranding the
|
||||
// '@' (postgres://user:pass/word?x=y@host). As a best-effort heuristic,
|
||||
// while an '@' remains, mask everything shaped like
|
||||
// ":candidate-credential@" across the whole
|
||||
// remainder -- before the query is split off, or a stranded '@' inside
|
||||
// the query would hide the pattern, and greedily up to each '@', so a
|
||||
// ':' inside the stranded password (user:sec:ret@host) cannot split the
|
||||
// mask and leak the part before it.
|
||||
//
|
||||
// The heuristic must not run when the connection string is structurally
|
||||
// unambiguous: then nothing can be stranded, a remaining '@' is ordinary
|
||||
// data (typically in a query value), and the greedy mask would swallow
|
||||
// the '/' and '?' delimiters -- hiding the query from the password-key
|
||||
// masking below, so a password=... query parameter would leak. Valid
|
||||
// URIs must always redact exactly; the heuristic is reserved for
|
||||
// malformed input, where only best effort is possible.
|
||||
if strings.IndexByte(p, '@') >= 0 && !uriStructureUnambiguous(connString) {
|
||||
brokenUserinfo := regexp.MustCompile(`:[^@]+@`)
|
||||
p = brokenUserinfo.ReplaceAllLiteralString(p, ":xxxxxx@")
|
||||
}
|
||||
|
||||
qi := uriQueryStart(p)
|
||||
if qi < 0 {
|
||||
b.WriteString(p)
|
||||
return b.String()
|
||||
}
|
||||
b.WriteString(p[:qi])
|
||||
query := p[qi+1:]
|
||||
b.WriteByte('?')
|
||||
|
||||
for i, pair := range strings.Split(query, "&") {
|
||||
if i > 0 {
|
||||
b.WriteByte('&')
|
||||
}
|
||||
rawKey, _, hasValue := strings.Cut(pair, "=")
|
||||
if !hasValue {
|
||||
b.WriteString(pair)
|
||||
continue
|
||||
}
|
||||
switch canonicalConnStringKey(uriDecodeLenient(rawKey)) {
|
||||
case "password", "sslpassword":
|
||||
b.WriteString(rawKey)
|
||||
b.WriteByte('=')
|
||||
b.WriteString(mask)
|
||||
default:
|
||||
b.WriteString(pair)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// uriStructureUnambiguous reports whether connString parses as a connection
|
||||
// URI whose component boundaries are certain, meaning redactURLPassword's
|
||||
// structural walk is exact and no password bytes can sit outside the two
|
||||
// positions it masks (the userinfo password and password-keyed query values).
|
||||
// That requires parseURLSettings to accept the string and every port element
|
||||
// to be numeric or empty: the parser accepts arbitrary text in the port slot
|
||||
// (postgres://a@u:sec:ret@h parses with port "sec:ret@h"), so a non-numeric
|
||||
// port may be a mislaid password and keeps the string in best-effort
|
||||
// territory.
|
||||
func uriStructureUnambiguous(connString string) bool {
|
||||
settings, _, err := parseURLSettings(connString)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for part := range strings.SplitSeq(settings["port"], ",") {
|
||||
for i := 0; i < len(part); i++ {
|
||||
if part[i] < '0' || part[i] > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// uriQueryStart returns the index of the '?' that begins the query component
|
||||
// of p (the post-scheme, post-userinfo part of a connection URI), or -1 if
|
||||
// there is none. It follows parseURLSettings' structure: '[' at the start of
|
||||
// a netloc element opens an IPv6 bracket whose contents -- deliberately
|
||||
// unvalidated -- may contain a literal '?' that is host data, not the query
|
||||
// delimiter. On an unterminated bracket (the parser errors there) it falls
|
||||
// back to the first '?' anywhere. With no valid structure to follow,
|
||||
// over-including text gives the best-effort redactor more candidate pairs to
|
||||
// inspect.
|
||||
func uriQueryStart(p string) int {
|
||||
i := 0
|
||||
for {
|
||||
if i < len(p) && p[i] == '[' {
|
||||
end := strings.IndexByte(p[i:], ']')
|
||||
if end < 0 {
|
||||
return strings.IndexByte(p, '?')
|
||||
}
|
||||
i += end + 1
|
||||
}
|
||||
// Host and port data: everything up to a '/', '?', or ','.
|
||||
for i < len(p) && p[i] != '/' && p[i] != '?' && p[i] != ',' {
|
||||
i++
|
||||
}
|
||||
if i < len(p) && p[i] == ',' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
if i == len(p) {
|
||||
return -1
|
||||
}
|
||||
if p[i] == '?' {
|
||||
return i
|
||||
}
|
||||
// p[i] == '/': a path follows; the first '?' after it starts the query.
|
||||
if j := strings.IndexByte(p[i:], '?'); j >= 0 {
|
||||
return i + j
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
type NotPreferredError struct {
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
"""Generate RFC 3454 table A.1 using Python's fixed Unicode 3.2 database.
|
||||
|
||||
Run from this directory with: python3 gen_saslprep_unassigned.py
|
||||
Only the Python standard library is needed; no network access is required.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
import stringprep
|
||||
from unicodedata import ucd_3_2_0
|
||||
|
||||
assert ucd_3_2_0.unidata_version == "3.2.0"
|
||||
|
||||
|
||||
def ranges(start, stop):
|
||||
first = None
|
||||
for code in range(start, stop):
|
||||
if stringprep.in_table_a1(chr(code)):
|
||||
if first is None:
|
||||
first = code
|
||||
elif first is not None:
|
||||
yield first, code - 1
|
||||
first = None
|
||||
if first is not None:
|
||||
yield first, stop - 1
|
||||
|
||||
|
||||
lines = [
|
||||
"// Code generated by gen_saslprep_unassigned.py; DO NOT EDIT.",
|
||||
"",
|
||||
"package pgconn",
|
||||
"",
|
||||
'import "unicode"',
|
||||
"",
|
||||
"//go:generate python3 gen_saslprep_unassigned.py",
|
||||
"",
|
||||
"// saslprepUnassigned is RFC 3454 table A.1: code points unassigned in",
|
||||
"// Unicode 3.2. This table must not track the Go toolchain's Unicode version.",
|
||||
"// https://www.rfc-editor.org/rfc/rfc3454#appendix-A.1",
|
||||
"var saslprepUnassigned = &unicode.RangeTable{",
|
||||
]
|
||||
for name, width, start, stop in [
|
||||
("R16", 16, 0, 0x10000),
|
||||
("R32", 32, 0x10000, 0x110000),
|
||||
]:
|
||||
lines.append(f"\t{name}: []unicode.Range{width}{{")
|
||||
for first, last in ranges(start, stop):
|
||||
lines.append(f"\t\t{{0x{first:04x}, 0x{last:04x}, 1}},")
|
||||
lines.append("\t},")
|
||||
lines.extend(["}", ""])
|
||||
Path(__file__).with_name("saslprep_unassigned.go").write_text(
|
||||
"\n".join(lines), encoding="utf-8"
|
||||
)
|
||||
+24
-9
@@ -2,7 +2,9 @@
|
||||
package bgreader
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/jackc/pgx/v5/internal/iobufpool"
|
||||
@@ -76,7 +78,18 @@ func (r *BGReader) bgRead() {
|
||||
*buf = (*buf)[:n]
|
||||
|
||||
r.cond.L.Lock()
|
||||
r.readResults = append(r.readResults, readResult{buf: buf, err: err})
|
||||
// A timeout belongs to the deadline that was in effect for this read, not to the data stream. It is not buffered
|
||||
// because a later Read could receive it after the deadline has already been cleared. The background reader stops
|
||||
// instead and the next Read goes to the underlying reader, which returns a fresh timeout if the deadline is still
|
||||
// in effect.
|
||||
switch {
|
||||
case !isTimeout(err):
|
||||
r.readResults = append(r.readResults, readResult{buf: buf, err: err})
|
||||
case n > 0:
|
||||
r.readResults = append(r.readResults, readResult{buf: buf})
|
||||
default:
|
||||
iobufpool.Put(buf)
|
||||
}
|
||||
if r.status == StatusStopping || err != nil {
|
||||
r.status = StatusStopped
|
||||
keepReading = false
|
||||
@@ -91,20 +104,22 @@ func (r *BGReader) Read(p []byte) (int, error) {
|
||||
r.cond.L.Lock()
|
||||
defer r.cond.L.Unlock()
|
||||
|
||||
// Wait for results from the background reader
|
||||
for len(r.readResults) == 0 && r.status != StatusStopped {
|
||||
r.cond.Wait()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
return r.r.Read(p)
|
||||
}
|
||||
|
||||
// Wait for results from the background reader
|
||||
for len(r.readResults) == 0 {
|
||||
r.cond.Wait()
|
||||
}
|
||||
return r.readFromReadResults(p)
|
||||
func isTimeout(err error) bool {
|
||||
var netErr net.Error
|
||||
return errors.As(err, &netErr) && netErr.Timeout()
|
||||
}
|
||||
|
||||
// readBackgroundResults reads a result previously read by the background reader. r.cond.L must be held.
|
||||
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
package pgconn
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// This file parses PostgreSQL connection URIs using a parser designed to
|
||||
// exactly match libpq's URI parser behavior (conninfo_uri_parse_options,
|
||||
// conninfo_uri_parse_params, and conninfo_uri_decode in
|
||||
// src/interfaces/libpq/fe-connect.c), so that pgx accepts and rejects exactly
|
||||
// the same URIs as libpq, including libpq's multiple-host extension
|
||||
// (postgresql://host1:port1,host2:port2/db), which is not valid RFC 3986 syntax.
|
||||
//
|
||||
// Deliberate differences from libpq:
|
||||
//
|
||||
// - Query parameters that libpq does not recognize are accepted. They become
|
||||
// runtime parameters or pgx-specific options (e.g. pool_max_conns) instead
|
||||
// of failing the parse.
|
||||
// - Error messages avoid quoting the unredacted connection string and mask
|
||||
// recognizable password fields on a best-effort basis. Invalid connection
|
||||
// strings can be structurally ambiguous, so password redaction cannot be
|
||||
// guaranteed for every malformed input. libpq quotes the failing input
|
||||
// verbatim, which can leak a password into error messages and logs.
|
||||
// - Literal NUL bytes are rejected. libpq never sees them because C strings
|
||||
// end at the first NUL; a Go string can carry one into the startup packet,
|
||||
// where it would act as a protocol delimiter and inject extra parameters.
|
||||
|
||||
// parseURLMeta reports provenance facts about a parsed URI that
|
||||
// ParseConfigWithOptions needs for ConnStringAllowedKeys validation and that
|
||||
// cannot be recovered from the settings map itself.
|
||||
type parseURLMeta struct {
|
||||
// impliedEmptyPortList: the "port" entry is an all-empty list synthesized
|
||||
// from the host list (postgres://h1,h2 yields port=",") with no port
|
||||
// bytes supplied by the user. Determined from the raw port syntax, not
|
||||
// the decoded value: a port of literal spaces (postgres://h: /db)
|
||||
// decodes to empty but was user-supplied.
|
||||
impliedEmptyPortList bool
|
||||
// sawRawSSLKey / sawSSLTrueAlias / sawExplicitSSLModeKey record which
|
||||
// spellings of the ssl and sslmode query keys appeared anywhere in the
|
||||
// URI -- including occurrences later superseded under last-occurrence-
|
||||
// wins. The ssl=true alias rewrite and ordinary repeated-key handling can
|
||||
// remove those occurrences from the final settings map, so
|
||||
// ConnStringAllowedKeys cannot fail closed from that map alone; it must see
|
||||
// every key the user actually wrote.
|
||||
sawRawSSLKey bool // key "ssl" with a value other than "true"
|
||||
sawSSLTrueAlias bool // key "ssl" with value "true" (stored as sslmode=require)
|
||||
sawExplicitSSLModeKey bool // key "sslmode"
|
||||
}
|
||||
|
||||
// parseURLSettings parses a connection URI into a settings map. connString
|
||||
// must start with "postgres://" or "postgresql://".
|
||||
//
|
||||
// Multiple hosts are represented in the returned map the same way libpq
|
||||
// represents them internally: settings["host"] and settings["port"] are
|
||||
// comma-separated lists that are positionally aligned, with empty elements
|
||||
// meaning "use the default". The lists are split in ParseConfigWithOptions.
|
||||
func parseURLSettings(connString string) (settings map[string]string, meta parseURLMeta, err error) {
|
||||
settings = make(map[string]string)
|
||||
|
||||
if strings.IndexByte(connString, 0) >= 0 {
|
||||
return nil, meta, errors.New("forbidden NUL byte in connection string")
|
||||
}
|
||||
|
||||
p, ok := strings.CutPrefix(connString, "postgresql://")
|
||||
if !ok {
|
||||
p, ok = strings.CutPrefix(connString, "postgres://")
|
||||
}
|
||||
if !ok {
|
||||
return nil, meta, errors.New("invalid URI propagated to internal parser routine")
|
||||
}
|
||||
|
||||
// Look ahead for a possible user credentials designator. Like libpq, only
|
||||
// a '/' stops the search, so a '@' anywhere before the path -- even inside
|
||||
// what looks like a query string -- is treated as the userinfo terminator.
|
||||
if i := strings.IndexAny(p, "@/"); i >= 0 && p[i] == '@' {
|
||||
user, password, hasPassword := strings.Cut(p[:i], ":")
|
||||
p = p[i+1:]
|
||||
if user != "" {
|
||||
val, err := uriDecode(user, "")
|
||||
if err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
settings["user"] = val
|
||||
}
|
||||
if hasPassword && password != "" {
|
||||
val, err := uriDecode(password, "password")
|
||||
if err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
settings["password"] = val
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the comma-separated list of netloc[:port] specifications. Hosts
|
||||
// and ports accumulate into positionally aligned comma-joined lists: every
|
||||
// separator appends a comma to both, so postgres://h1,h2:5433 yields
|
||||
// host="h1,h2" port=",5433".
|
||||
var hostBuf, portBuf strings.Builder
|
||||
|
||||
for {
|
||||
if peekByte(p) == '[' {
|
||||
// IPv6 address. The bracket contents are not validated, matching libpq.
|
||||
end := strings.IndexByte(p, ']')
|
||||
if end < 0 {
|
||||
return nil, meta, errors.New(`end of string reached when looking for matching "]" in IPv6 host address in URI`)
|
||||
}
|
||||
if end == 1 {
|
||||
return nil, meta, errors.New("IPv6 host address may not be empty in URI")
|
||||
}
|
||||
hostBuf.WriteString(p[1:end])
|
||||
p = p[end+1:]
|
||||
if c := peekByte(p); c != 0 && c != ':' && c != '/' && c != '?' && c != ',' {
|
||||
return nil, meta, fmt.Errorf(`unexpected character "%c" at position %d in URI (expected ":" or "/")`, c, len(connString)-len(p)+1)
|
||||
}
|
||||
} else {
|
||||
// DNS-named or IPv4 netloc: everything up to a ':', '/', '?', or ','.
|
||||
i := strings.IndexAny(p, ":/?,")
|
||||
if i < 0 {
|
||||
i = len(p)
|
||||
}
|
||||
hostBuf.WriteString(p[:i])
|
||||
p = p[i:]
|
||||
}
|
||||
|
||||
if peekByte(p) == ':' {
|
||||
p = p[1:]
|
||||
i := strings.IndexAny(p, "/?,")
|
||||
if i < 0 {
|
||||
i = len(p)
|
||||
}
|
||||
portBuf.WriteString(p[:i])
|
||||
p = p[i:]
|
||||
}
|
||||
|
||||
if peekByte(p) != ',' {
|
||||
break
|
||||
}
|
||||
p = p[1:]
|
||||
hostBuf.WriteByte(',')
|
||||
portBuf.WriteByte(',')
|
||||
}
|
||||
|
||||
// The joined lists are percent-decoded as a unit, after joining. This
|
||||
// means %2C decodes to a comma that later splits like a real separator --
|
||||
// a host name containing a literal comma is inexpressible, as in libpq.
|
||||
if hostBuf.Len() > 0 {
|
||||
hostList, err := uriDecode(hostBuf.String(), "")
|
||||
if err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
settings["host"] = hostList
|
||||
}
|
||||
// Like libpq, the port list is stored even when every element is empty
|
||||
// (postgres://h1,h2 yields port=","). This matters: a connection string
|
||||
// port shadows PGPORT during settings merge, so with PGPORT=1,2 a
|
||||
// three-host URI without ports must use the default port for every host,
|
||||
// not fail the port/host count check. Such an implied all-empty list
|
||||
// carries no user-supplied port text, which is what
|
||||
// meta.impliedEmptyPortList reports -- judged on the raw bytes, before
|
||||
// percent-decoding trims spaces, so a port the user actually typed never
|
||||
// counts as implied even when it decodes to empty.
|
||||
if portBuf.Len() > 0 {
|
||||
meta.impliedEmptyPortList = strings.Trim(portBuf.String(), ",") == ""
|
||||
portList, err := uriDecode(portBuf.String(), "")
|
||||
if err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
settings["port"] = portList
|
||||
}
|
||||
|
||||
if peekByte(p) == '/' {
|
||||
p = p[1:]
|
||||
dbname := p
|
||||
p = ""
|
||||
if i := strings.IndexByte(dbname, '?'); i >= 0 {
|
||||
p = dbname[i:]
|
||||
dbname = dbname[:i]
|
||||
}
|
||||
// Like libpq, an empty path component leaves dbname unset so the
|
||||
// default stays in effect.
|
||||
if dbname != "" {
|
||||
val, err := uriDecode(dbname, "")
|
||||
if err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
settings["database"] = val
|
||||
}
|
||||
}
|
||||
|
||||
if peekByte(p) == '?' {
|
||||
// Query parameters land in their own map first: an explicit ?port=
|
||||
// overrides the netloc-derived port list and is user-supplied port
|
||||
// text, so it cancels the implied-list exemption even when its value
|
||||
// is empty.
|
||||
query := make(map[string]string)
|
||||
if err := parseURLQueryParams(p[1:], query, &meta); err != nil {
|
||||
return nil, meta, err
|
||||
}
|
||||
if _, ok := query["port"]; ok {
|
||||
meta.impliedEmptyPortList = false
|
||||
}
|
||||
maps.Copy(settings, query)
|
||||
}
|
||||
|
||||
return settings, meta, nil
|
||||
}
|
||||
|
||||
// peekByte returns the first byte of s, or 0 if s is empty. A NUL byte is a
|
||||
// safe end-of-input sentinel because parseURLSettings rejects literal NULs.
|
||||
func peekByte(s string) byte {
|
||||
if len(s) == 0 {
|
||||
return 0
|
||||
}
|
||||
return s[0]
|
||||
}
|
||||
|
||||
// parseURLQueryParams parses the query part of a connection URI into settings,
|
||||
// mirroring libpq's conninfo_uri_parse_params: '&'-separated pairs, exactly
|
||||
// one raw '=' per pair, both halves percent-decoded, last occurrence wins. It
|
||||
// records in meta which spellings of the ssl/sslmode keys it saw (see
|
||||
// parseURLMeta).
|
||||
func parseURLQueryParams(params string, settings map[string]string, meta *parseURLMeta) error {
|
||||
// sslWasLast records whether ssl or sslmode was encountered most recently.
|
||||
// This matters if the final repeated ssl value is "true": the alias wins
|
||||
// only when it occurs after the final explicit sslmode.
|
||||
sslWasLast := false
|
||||
|
||||
for params != "" {
|
||||
pair := params
|
||||
if i := strings.IndexByte(params, '&'); i >= 0 {
|
||||
pair = params[:i]
|
||||
params = params[i+1:]
|
||||
} else {
|
||||
params = ""
|
||||
}
|
||||
|
||||
rawKey, rawValue, found := strings.Cut(pair, "=")
|
||||
if !found {
|
||||
return fmt.Errorf(`missing key/value separator "=" in URI query parameter: "%s"`, rawKey)
|
||||
}
|
||||
if strings.IndexByte(rawValue, '=') >= 0 {
|
||||
return fmt.Errorf(`extra key/value separator "=" in URI query parameter: "%s"`, rawKey)
|
||||
}
|
||||
|
||||
key, err := uriDecode(rawKey, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key = canonicalConnStringKey(key)
|
||||
|
||||
secretName := ""
|
||||
if key == "password" || key == "sslpassword" {
|
||||
secretName = key
|
||||
}
|
||||
value, err := uriDecode(rawValue, secretName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Resolve repeated ssl values under their raw key before applying the
|
||||
// JDBC compatibility alias. Otherwise ssl=true would overwrite an
|
||||
// independent explicit sslmode that must reappear if a later ssl value
|
||||
// supersedes the alias. The alias is URI-only and applies only to the
|
||||
// literal value "true".
|
||||
switch key {
|
||||
case "ssl":
|
||||
sslWasLast = true
|
||||
if value == "true" {
|
||||
meta.sawSSLTrueAlias = true
|
||||
} else {
|
||||
meta.sawRawSSLKey = true
|
||||
}
|
||||
case "sslmode":
|
||||
sslWasLast = false
|
||||
meta.sawExplicitSSLModeKey = true
|
||||
}
|
||||
|
||||
settings[key] = value
|
||||
}
|
||||
|
||||
if value, ok := settings["ssl"]; ok && value == "true" {
|
||||
delete(settings, "ssl")
|
||||
if sslWasLast {
|
||||
settings["sslmode"] = "require"
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// uriDecode percent-decodes a URI component with the same rules as libpq's
|
||||
// conninfo_uri_decode: '%' followed by exactly two case-insensitive hex
|
||||
// digits, %00 forbidden, leading and trailing ASCII spaces skipped, interior
|
||||
// spaces rejected. Decoded bytes are emitted raw with no character set
|
||||
// validation.
|
||||
//
|
||||
// If secretName is non-empty, error messages identify that component by name
|
||||
// instead of quoting its raw value. This prevents the known component's raw
|
||||
// contents from being copied into the decode error; it does not make the
|
||||
// separate, best-effort redaction of an invalid connection string complete.
|
||||
func uriDecode(raw, secretName string) (string, error) {
|
||||
// The component may be a secret; every error must be built by fail so the
|
||||
// quote-the-raw-value-or-not redaction decision lives in exactly one place.
|
||||
fail := func(secretFormat, publicFormat string) (string, error) {
|
||||
if secretName != "" {
|
||||
return "", fmt.Errorf(secretFormat, secretName)
|
||||
}
|
||||
return "", fmt.Errorf(publicFormat, raw)
|
||||
}
|
||||
|
||||
var b strings.Builder
|
||||
b.Grow(len(raw))
|
||||
|
||||
i := 0
|
||||
for i < len(raw) && raw[i] == ' ' {
|
||||
i++
|
||||
}
|
||||
for i < len(raw) && raw[i] != ' ' {
|
||||
if raw[i] != '%' {
|
||||
b.WriteByte(raw[i])
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
var hi, lo byte
|
||||
var ok1, ok2 bool
|
||||
if i+1 < len(raw) {
|
||||
hi, ok1 = hexDigit(raw[i+1])
|
||||
}
|
||||
if i+2 < len(raw) {
|
||||
lo, ok2 = hexDigit(raw[i+2])
|
||||
}
|
||||
if !ok1 || !ok2 {
|
||||
return fail("invalid percent-encoded token in %s", `invalid percent-encoded token: "%s"`)
|
||||
}
|
||||
|
||||
c := hi<<4 | lo
|
||||
if c == 0 {
|
||||
return fail("forbidden value %%00 in percent-encoded value in %s", `forbidden value %%00 in percent-encoded value: "%s"`)
|
||||
}
|
||||
b.WriteByte(c)
|
||||
i += 3
|
||||
}
|
||||
for i < len(raw) && raw[i] == ' ' {
|
||||
i++
|
||||
}
|
||||
if i < len(raw) {
|
||||
return fail("unexpected spaces found in %s, use percent-encoded spaces (%%20) instead", `unexpected spaces found in "%s", use percent-encoded spaces (%%20) instead`)
|
||||
}
|
||||
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// uriDecodeLenient is a non-failing variant of uriDecode used for best-effort
|
||||
// redaction: valid percent-encodings are decoded, anything uriDecode would
|
||||
// reject passes through unchanged. Redaction processing itself must not fail,
|
||||
// and it must see the same key spelling the parser would (pass%77ord decodes
|
||||
// to password), so encoded password keys are recognized even in connection
|
||||
// strings that do not parse. This helps recognize keys but cannot make
|
||||
// redaction complete when malformed input has ambiguous component boundaries.
|
||||
func uriDecodeLenient(raw string) string {
|
||||
raw = strings.Trim(raw, " ")
|
||||
|
||||
var b strings.Builder
|
||||
b.Grow(len(raw))
|
||||
|
||||
for i := 0; i < len(raw); {
|
||||
if raw[i] == '%' && i+2 < len(raw) {
|
||||
hi, ok1 := hexDigit(raw[i+1])
|
||||
lo, ok2 := hexDigit(raw[i+2])
|
||||
if ok1 && ok2 {
|
||||
b.WriteByte(hi<<4 | lo)
|
||||
i += 3
|
||||
continue
|
||||
}
|
||||
}
|
||||
b.WriteByte(raw[i])
|
||||
i++
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func hexDigit(c byte) (byte, bool) {
|
||||
switch {
|
||||
case c >= '0' && c <= '9':
|
||||
return c - '0', true
|
||||
case c >= 'A' && c <= 'F':
|
||||
return c - 'A' + 10, true
|
||||
case c >= 'a' && c <= 'f':
|
||||
return c - 'a' + 10, true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
Loaded 100 of 620 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user