MSP-1388 [+] тесты
This commit is contained in:
1 parent
9bd31bf6c9
commit
42d2dd18ac
22 files changed
+160
-700
No files matched your search
@@ -9,8 +9,8 @@ import (
|
||||
)
|
||||
|
||||
type LockerService interface {
|
||||
Lock(ctx context.Context, req domain.Request) (*domain.LockResponse, error)
|
||||
UnLock(ctx context.Context, req domain.Request) (*domain.LockResponse, error)
|
||||
Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error)
|
||||
UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error)
|
||||
}
|
||||
|
||||
type Locker struct {
|
||||
@@ -22,13 +22,13 @@ type Locker struct {
|
||||
// @Tags locker
|
||||
// @Summary выставляем лок на строку
|
||||
// @Description `key` - строка для лока
|
||||
// @Description `ttl` - число секунд после которых блокировка снимется автоматически
|
||||
// @Description Возвращаем ключ для разблокировки
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} domain.LockResponse
|
||||
// @Failure 500 {object}
|
||||
// @Router /api/isp-lock-service/lock [POST]
|
||||
func (l Locker) Lock(ctx context.Context, req domain.Request) (*domain.LockResponse, error) {
|
||||
func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) {
|
||||
l.logger.Debug(ctx, "call ctrl.Lock")
|
||||
return l.s.Lock(ctx, req)
|
||||
}
|
||||
@@ -40,10 +40,9 @@ func (l Locker) Lock(ctx context.Context, req domain.Request) (*domain.LockRespo
|
||||
// @Description `locKKey` - ключ для разблокировки, полученный из Lock
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {object} domain.LockResponse
|
||||
// @Failure 500 {object} {}
|
||||
// @Router /api/isp-lock-service/lock [POST]
|
||||
func (l Locker) UnLock(ctx context.Context, req domain.Request) (*domain.LockResponse, error) {
|
||||
// @Success 200
|
||||
// @Router /api/isp-lock-service/unlock [POST]
|
||||
func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) {
|
||||
l.logger.Debug(ctx, "call ctrl.UnLock")
|
||||
return l.s.UnLock(ctx, req)
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"isp-lock-service/domain"
|
||||
"isp-lock-service/entity"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type ObjectService interface {
|
||||
All(ctx context.Context) ([]domain.Object, error)
|
||||
Get(ctx context.Context, id int) (*domain.Object, error)
|
||||
}
|
||||
|
||||
type Object struct {
|
||||
s ObjectService
|
||||
}
|
||||
|
||||
func NewObject(s ObjectService) Object {
|
||||
return Object{
|
||||
s: s,
|
||||
}
|
||||
}
|
||||
|
||||
// All
|
||||
// @Tags object
|
||||
// @Summary Получить все объекты
|
||||
// @Description Возвращает список объектов
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} domain.Object
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /object/all [POST]
|
||||
func (c Object) All(ctx context.Context) ([]domain.Object, error) {
|
||||
return c.s.All(ctx)
|
||||
}
|
||||
|
||||
// GetById
|
||||
// @Tags object
|
||||
// @Summary Получить объект по его идентификатору
|
||||
// @Description Возвращает объект
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param body body domain.ByIdRequest true "Идентификатор объекта"
|
||||
// @Success 200 {object} domain.Object
|
||||
// @Failure 404 {object} domain.GrpcError
|
||||
// @Failure 500 {object} domain.GrpcError
|
||||
// @Router /object/get_by_id [POST]
|
||||
func (c Object) GetById(ctx context.Context, req domain.ByIdRequest) (*domain.Object, error) {
|
||||
d, err := c.s.Get(ctx, req.Id)
|
||||
switch {
|
||||
case errors.Is(err, entity.ErrObjectNotFound):
|
||||
return nil, status.Errorf(codes.NotFound, "object by id '%d' not found", req.Id)
|
||||
default:
|
||||
return d, err
|
||||
}
|
||||
}
|
||||
+17
-53
@@ -1,26 +1,8 @@
|
||||
basePath: /api/isp-lock-service
|
||||
definitions:
|
||||
domain.ByIdRequest:
|
||||
domain.LockResponse:
|
||||
properties:
|
||||
id:
|
||||
type: integer
|
||||
required:
|
||||
- id
|
||||
type: object
|
||||
domain.GrpcError:
|
||||
properties:
|
||||
details:
|
||||
items:
|
||||
type: object
|
||||
type: array
|
||||
errorCode:
|
||||
type: string
|
||||
errorMessage:
|
||||
type: string
|
||||
type: object
|
||||
domain.Object:
|
||||
properties:
|
||||
name:
|
||||
lockKey:
|
||||
type: string
|
||||
type: object
|
||||
host: localhost:9000
|
||||
@@ -32,55 +14,37 @@ info:
|
||||
title: isp-lock-service
|
||||
version: 1.0.0
|
||||
paths:
|
||||
/object/all:
|
||||
/api/isp-lock-service/lock:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает список объектов
|
||||
description: |-
|
||||
`key` - строка для лока
|
||||
`ttl` - число секунд после которых блокировка снимется автоматически
|
||||
Возвращаем ключ для разблокировки
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/domain.Object'
|
||||
type: array
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Получить все объекты
|
||||
$ref: '#/definitions/domain.LockResponse'
|
||||
summary: выставляем лок на строку
|
||||
tags:
|
||||
- object
|
||||
/object/get_by_id:
|
||||
- locker
|
||||
/api/isp-lock-service/unlock:
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает объект
|
||||
parameters:
|
||||
- description: Идентификатор объекта
|
||||
in: body
|
||||
name: body
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/domain.ByIdRequest'
|
||||
description: |-
|
||||
`key` - строка для лока
|
||||
`locKKey` - ключ для разблокировки, полученный из Lock
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/domain.Object'
|
||||
"404":
|
||||
description: Not Found
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
"500":
|
||||
description: Internal Server Error
|
||||
schema:
|
||||
$ref: '#/definitions/domain.GrpcError'
|
||||
summary: Получить объект по его идентификатору
|
||||
description: ""
|
||||
summary: снимаем лок со строки
|
||||
tags:
|
||||
- object
|
||||
- locker
|
||||
swagger: "2.0"
|
||||
+6
-2
@@ -2,10 +2,14 @@ package domain
|
||||
|
||||
import "time"
|
||||
|
||||
type Request struct {
|
||||
type LockRequest struct {
|
||||
Key string `json:"Key" valid:"required"`
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type UnLockRequest struct {
|
||||
Key string `json:"Key" valid:"required"`
|
||||
LockKey string
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type LockResponse struct {
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
package domain
|
||||
|
||||
type Object struct {
|
||||
Name string
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package domain
|
||||
|
||||
type ByIdRequest struct {
|
||||
Id int `valid:"required"`
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
|
||||
"github.com/integration-system/isp-kit/json"
|
||||
)
|
||||
|
||||
type Message struct {
|
||||
Id int64
|
||||
Version int64
|
||||
Data MessageData
|
||||
}
|
||||
|
||||
type MessageData struct {
|
||||
Text string
|
||||
}
|
||||
|
||||
// nolint
|
||||
func (m *MessageData) Scan(src interface{}) error {
|
||||
return json.Unmarshal(src.([]byte), m)
|
||||
}
|
||||
|
||||
func (m MessageData) Value() (driver.Value, error) {
|
||||
bytes, err := json.Marshal(m)
|
||||
return driver.Value(bytes), err
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package entity
|
||||
|
||||
type Object struct {
|
||||
Id string
|
||||
Name string
|
||||
}
|
||||
@@ -8,13 +8,15 @@ require (
|
||||
github.com/integration-system/isp-kit v1.15.0
|
||||
github.com/integration-system/jsonschema v1.0.1
|
||||
github.com/pkg/errors v0.9.1
|
||||
go.uber.org/zap v1.24.0
|
||||
google.golang.org/grpc v1.52.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/asaskevich/govalidator v0.0.0-20210307081110-f21760c49a8d // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
@@ -23,7 +25,6 @@ require (
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/iancoleman/strcase v0.2.0 // indirect
|
||||
github.com/integration-system/bellows v1.0.1 // indirect
|
||||
github.com/integration-system/grmq v1.2.0 // indirect
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
@@ -37,9 +38,10 @@ require (
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
|
||||
github.com/onsi/gomega v1.25.0 // indirect
|
||||
github.com/pelletier/go-toml v1.9.5 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
|
||||
github.com/pressly/goose v2.7.0+incompatible // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/prometheus/client_golang v1.14.0 // indirect
|
||||
github.com/prometheus/client_model v0.3.0 // indirect
|
||||
github.com/prometheus/common v0.37.0 // indirect
|
||||
@@ -50,14 +52,15 @@ require (
|
||||
github.com/spf13/jwalterweatherman v1.1.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/spf13/viper v1.14.0 // indirect
|
||||
github.com/stretchr/testify v1.8.1 // indirect
|
||||
github.com/subosito/gotenv v1.4.1 // indirect
|
||||
go.uber.org/atomic v1.10.0 // indirect
|
||||
go.uber.org/goleak v1.2.0 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
go.uber.org/zap v1.24.0 // indirect
|
||||
golang.org/x/crypto v0.4.0 // indirect
|
||||
golang.org/x/net v0.4.0 // indirect
|
||||
golang.org/x/sys v0.3.0 // indirect
|
||||
golang.org/x/text v0.5.0 // indirect
|
||||
golang.org/x/net v0.5.0 // indirect
|
||||
golang.org/x/sys v0.4.0 // indirect
|
||||
golang.org/x/text v0.6.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20221207170731-23e4bf6bdc37 // indirect
|
||||
google.golang.org/protobuf v1.28.1 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
|
||||
@@ -53,8 +53,9 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
@@ -206,7 +207,6 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:
|
||||
github.com/integration-system/bellows v1.0.1 h1:7g1lhD/6EcvsSo9iuiFqw98XGS78Sko6kUKPzfte/SY=
|
||||
github.com/integration-system/bellows v1.0.1/go.mod h1:qHPg1ptN3AHHr0f/wvoicfA2LOCprOyrbXnIa5QIRe0=
|
||||
github.com/integration-system/grmq v1.2.0 h1:wD2dQ2ds8n/2nAivrjVU+iyLFT4izGnFbJGcstjrBto=
|
||||
github.com/integration-system/grmq v1.2.0/go.mod h1:edPZgkBBRHpDuppDp2SoQnXMg81pZHigYmr7ETKRS68=
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3 h1:vcHP/PE7p1G3rxqoVKrKtXzoSxFA4ryxigd+zPkAb3w=
|
||||
github.com/integration-system/isp-etp-go/v2 v2.1.3/go.mod h1:ZpB+FIH3hy7md+f8ylVSQx5zwZVjczhkc45f1B2z9nw=
|
||||
github.com/integration-system/isp-kit v1.15.0 h1:vwC1qpSewzrvvzhnJfhkZra+HE34op+BFVNWK2z5EEU=
|
||||
@@ -287,8 +287,9 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y
|
||||
github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
|
||||
github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
|
||||
github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro=
|
||||
github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q=
|
||||
github.com/onsi/gomega v1.20.0/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo=
|
||||
github.com/onsi/gomega v1.25.0 h1:Vw7br2PCDYijJHSfBOWhov+8cAnUf8MfMaIOV323l6Y=
|
||||
github.com/onsi/gomega v1.25.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM=
|
||||
github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=
|
||||
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
|
||||
github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU=
|
||||
@@ -300,8 +301,6 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pressly/goose v2.7.0+incompatible h1:PWejVEv07LCerQEzMMeAtjuyCKbyprZ/LBa6K5P0OCQ=
|
||||
github.com/pressly/goose v2.7.0+incompatible/go.mod h1:m+QHWCqxR3k8D9l7qfzuC/djtlfzxr34mozWDYEu1z8=
|
||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo=
|
||||
github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
|
||||
@@ -476,8 +475,8 @@ golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qx
|
||||
golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.4.0 h1:Q5QPcMlvfxFTAPV0+07Xz/MpK9NTXu2VDUuy0FeMfaU=
|
||||
golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
|
||||
golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw=
|
||||
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||
@@ -558,8 +557,8 @@ golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBc
|
||||
golang.org/x/sys v0.0.0-20220319134239-a9b59b0215f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220422013727-9388b58f7150/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
|
||||
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@@ -570,8 +569,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.5.0 h1:OLmvp0KP+FVG99Ct/qFiL/Fhk4zp4QQnZ7b2U+5piUM=
|
||||
golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k=
|
||||
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
|
||||
@@ -2,7 +2,6 @@ package rc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -12,10 +11,9 @@ import (
|
||||
"github.com/go-redsync/redsync/v4"
|
||||
"github.com/go-redsync/redsync/v4/redis/goredis/v8"
|
||||
"github.com/integration-system/isp-kit/log"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var ErrAlreadyLocked = errors.New("already locked")
|
||||
|
||||
type RC struct {
|
||||
cli *redsync.Redsync
|
||||
timeOut time.Duration
|
||||
@@ -23,10 +21,10 @@ type RC struct {
|
||||
l *log.Adapter
|
||||
}
|
||||
|
||||
func NewRCWithClient(cfg conf.Remote, l *log.Adapter, cli *goredislib.Client) (*RC, error) {
|
||||
func NewRCWithClient(prefix string, timeOut time.Duration, l *log.Adapter, cli *goredislib.Client) (*RC, error) {
|
||||
r := RC{
|
||||
timeOut: cfg.Redis.DefaultTimeOut * time.Second,
|
||||
prefix: cfg.Redis.Prefix,
|
||||
timeOut: timeOut,
|
||||
prefix: prefix,
|
||||
l: l,
|
||||
}
|
||||
|
||||
@@ -69,6 +67,19 @@ func makeKey(prefix, key string) string {
|
||||
return prefix + "::" + key
|
||||
}
|
||||
|
||||
func (rc *RC) log(level string, message interface{}, fields ...zap.Field) {
|
||||
if rc.l != nil {
|
||||
switch level {
|
||||
case "error":
|
||||
rc.l.Error(context.Background(), message, fields...)
|
||||
case "info":
|
||||
rc.l.Info(context.Background(), message, fields...)
|
||||
default:
|
||||
rc.l.Debug(context.Background(), message, fields...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Lock - функция установки лока по ключу
|
||||
//
|
||||
// key - суффикс ключа
|
||||
@@ -81,16 +92,17 @@ func (rc *RC) Lock(key string, ttl time.Duration) (string, error) {
|
||||
if ttl == 0 {
|
||||
ttl = rc.timeOut
|
||||
}
|
||||
rc.log("debug", "пробуем залочить "+key+" на "+ttl.String())
|
||||
|
||||
rc.l.Debug(context.Background(), "пробуем залочить "+key+" на "+ttl.String())
|
||||
mtx := rc.cli.NewMutex(key, redsync.WithExpiry(ttl))
|
||||
|
||||
if err := mtx.Lock(); err != nil {
|
||||
rc.l.Debug(context.Background(), fmt.Sprintf("err=%#v", err))
|
||||
rc.log("debug", fmt.Sprintf("err=%#v", err))
|
||||
return "", err
|
||||
}
|
||||
|
||||
value := mtx.Value()
|
||||
rc.l.Debug(context.Background(), "ключ для разблокировки "+value)
|
||||
rc.log("debug", "ключ для разблокировки "+value)
|
||||
return value, nil
|
||||
}
|
||||
|
||||
@@ -101,13 +113,13 @@ func (rc *RC) Lock(key string, ttl time.Duration) (string, error) {
|
||||
func (rc *RC) UnLock(key, lockKey string) (bool, error) {
|
||||
key = makeKey(rc.prefix, key)
|
||||
|
||||
rc.l.Debug(context.Background(), "пробуем разлочить "+key+"+"+lockKey)
|
||||
rc.log("debug", "пробуем разлочить "+key+"+"+lockKey)
|
||||
|
||||
ok, err := rc.cli.NewMutex(key, redsync.WithValue(lockKey)).Unlock()
|
||||
|
||||
rc.l.Debug(context.Background(), fmt.Sprint("ok=", ok))
|
||||
rc.log("debug", fmt.Sprint("ok=", ok))
|
||||
if err != nil {
|
||||
rc.l.Debug(context.Background(), fmt.Sprintf("err=%#v", err))
|
||||
rc.log("debug", fmt.Sprintf("err=%#v", err))
|
||||
}
|
||||
|
||||
return ok, err
|
||||
|
||||
@@ -1,54 +0,0 @@
|
||||
package repository
|
||||
|
||||
//
|
||||
// import (
|
||||
// "context"
|
||||
// "hash/fnv"
|
||||
//
|
||||
// "github.com/integration-system/isp-kit/db"
|
||||
// "github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
// "github.com/pkg/errors"
|
||||
// )
|
||||
//
|
||||
// type Locker struct {
|
||||
// db db.DB
|
||||
// }
|
||||
//
|
||||
// func NewLocker(db db.DB) Locker {
|
||||
// return Locker{db: db}
|
||||
// }
|
||||
//
|
||||
// func (l Locker) Lock(ctx context.Context, req domain.Request) error {
|
||||
// ctx = sql_metrics.OperationLabelToContext(ctx, "Locker.Lock")
|
||||
//
|
||||
// hash := fnv.New32a()
|
||||
// _, err := hash.Write([]byte(key))
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "generate hash")
|
||||
// }
|
||||
// sum := hash.Sum32()
|
||||
//
|
||||
// _, err = l.db.Exec(ctx, "SELECT pg_advisory_xact_lock($1)", sum)
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "pg acquire advisory lock")
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
//
|
||||
// func (l Locker) TryLock(ctx context.Context, req domain.Request) (bool, error) {
|
||||
// ctx = sql_metrics.OperationLabelToContext(ctx, "Locker.TryLock")
|
||||
//
|
||||
// hash := fnv.New32a()
|
||||
// _, err := hash.Write([]byte(key))
|
||||
// if err != nil {
|
||||
// return false, errors.WithMessage(err, "generate hash")
|
||||
// }
|
||||
// sum := hash.Sum32()
|
||||
//
|
||||
// acquired := false
|
||||
// err = l.db.SelectRow(ctx, &acquired, "SELECT pg_try_advisory_xact_lock($1)", sum)
|
||||
// if err != nil {
|
||||
// return false, errors.WithMessage(err, "pg try acquire advisory lock")
|
||||
// }
|
||||
// return acquired, nil
|
||||
// }
|
||||
@@ -16,7 +16,7 @@ type Locker struct {
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func (l Locker) Lock(ctx context.Context, req domain.Request) (*domain.LockResponse, error) {
|
||||
func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) {
|
||||
l.logger.Debug(ctx, "call repo.Lock")
|
||||
val, err := l.rc.Lock(req.Key, req.TTL*time.Second)
|
||||
if err != nil {
|
||||
@@ -25,7 +25,7 @@ func (l Locker) Lock(ctx context.Context, req domain.Request) (*domain.LockRespo
|
||||
return &domain.LockResponse{LockKey: val}, nil
|
||||
}
|
||||
|
||||
func (l Locker) UnLock(ctx context.Context, req domain.Request) (*domain.LockResponse, error) {
|
||||
func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) {
|
||||
l.logger.Debug(ctx, "call repo.UnLock")
|
||||
_, err := l.rc.UnLock(req.Key, req.LockKey)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package repository
|
||||
|
||||
//
|
||||
// import (
|
||||
// "context"
|
||||
// "database/sql"
|
||||
//
|
||||
// "isp-lock-service/entity"
|
||||
//
|
||||
// "github.com/Masterminds/squirrel"
|
||||
// "github.com/integration-system/isp-kit/db"
|
||||
// "github.com/integration-system/isp-kit/db/query"
|
||||
// "github.com/integration-system/isp-kit/metrics/sql_metrics"
|
||||
// "github.com/pkg/errors"
|
||||
// )
|
||||
//
|
||||
// type Message struct {
|
||||
// db db.DB
|
||||
// }
|
||||
//
|
||||
// func NewMessage(db db.DB) Message {
|
||||
// return Message{
|
||||
// db: db,
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// func (m Message) Insert(ctx context.Context, msg entity.Message) error {
|
||||
// ctx = sql_metrics.OperationLabelToContext(ctx, "Message.Insert")
|
||||
//
|
||||
// _, err := m.db.Exec(
|
||||
// ctx,
|
||||
// "INSERT INTO message (id, version, data) VALUES ($1, $2, $3)",
|
||||
// msg.Id, msg.Version, msg.Data,
|
||||
// )
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "insert message")
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
//
|
||||
// func (m Message) GetLastVersion(ctx context.Context, id int64) (int64, error) {
|
||||
// ctx = sql_metrics.OperationLabelToContext(ctx, "Message.GetLastVersion")
|
||||
//
|
||||
// version := int64(0)
|
||||
// err := m.db.SelectRow(ctx, &version, "SELECT version FROM message WHERE id = $1", id)
|
||||
// if errors.Is(err, sql.ErrNoRows) {
|
||||
// return 0, entity.ErrMessageNotFound
|
||||
// }
|
||||
// if err != nil {
|
||||
// return 0, errors.WithMessage(err, "select last version")
|
||||
// }
|
||||
// return version, nil
|
||||
// }
|
||||
//
|
||||
// func (m Message) UpdateById(ctx context.Context, msg entity.Message) error {
|
||||
// ctx = sql_metrics.OperationLabelToContext(ctx, "Message.UpdateById")
|
||||
//
|
||||
// query, args, err := query.New().
|
||||
// Update("message").
|
||||
// Set("version", msg.Version).
|
||||
// Set("data", msg.Data).
|
||||
// Where(squirrel.Eq{"id": msg.Id}).
|
||||
// ToSql()
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "build query")
|
||||
// }
|
||||
//
|
||||
// _, err = m.db.Exec(ctx, query, args...)
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "update")
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
@@ -1,52 +0,0 @@
|
||||
package repository
|
||||
|
||||
//
|
||||
// import (
|
||||
// "context"
|
||||
//
|
||||
// "isp-lock-service/entity"
|
||||
// )
|
||||
//
|
||||
// type Object struct {
|
||||
// // db db.DB
|
||||
// }
|
||||
//
|
||||
// func NewObject() Object {
|
||||
// return Object{
|
||||
// // db: db,
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// func (r Object) All(ctx context.Context) ([]entity.Object, error) {
|
||||
// // ctx = sql_metrics.OperationLabelToContext(ctx, "Object.All")
|
||||
//
|
||||
// arr := make([]entity.Object, 0)
|
||||
// // err := r.db.Select(ctx, &arr, "SELECT id, name FROM object ORDER BY id")
|
||||
// // if err != nil {
|
||||
// // return nil, errors.WithMessage(err, "select objects")
|
||||
// // }
|
||||
// return arr, nil
|
||||
// }
|
||||
//
|
||||
// func (r Object) Get(ctx context.Context, id int) (*entity.Object, error) {
|
||||
// // ctx = sql_metrics.OperationLabelToContext(ctx, "Object.Get")
|
||||
// //
|
||||
// // query, args, err := query.New().
|
||||
// // Select("id", "name").
|
||||
// // From("object").
|
||||
// // Where(squirrel.Eq{"id": id}).
|
||||
// // ToSql()
|
||||
// // if err != nil {
|
||||
// // return nil, errors.WithMessage(err, "build query")
|
||||
// // }
|
||||
// //
|
||||
// o := entity.Object{}
|
||||
// // err = r.db.SelectRow(ctx, &o, query, args...)
|
||||
// // if errors.Is(err, sql.ErrNoRows) {
|
||||
// // return nil, entity.ErrObjectNotFound
|
||||
// // }
|
||||
// // if err != nil {
|
||||
// // return nil, errors.WithMessage(err, "select object")
|
||||
// // }
|
||||
// return &o, nil
|
||||
// }
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
)
|
||||
|
||||
type Controllers struct {
|
||||
Object controller.Object
|
||||
Locker controller.Locker
|
||||
}
|
||||
|
||||
|
||||
+4
-4
@@ -9,8 +9,8 @@ import (
|
||||
)
|
||||
|
||||
type LockerRepo interface {
|
||||
Lock(ctx context.Context, req domain.Request) (*domain.LockResponse, error)
|
||||
UnLock(ctx context.Context, req domain.Request) (*domain.LockResponse, error)
|
||||
Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error)
|
||||
UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error)
|
||||
}
|
||||
|
||||
type Locker struct {
|
||||
@@ -18,12 +18,12 @@ type Locker struct {
|
||||
logger log.Logger
|
||||
}
|
||||
|
||||
func (l Locker) Lock(ctx context.Context, req domain.Request) (*domain.LockResponse, error) {
|
||||
func (l Locker) Lock(ctx context.Context, req domain.LockRequest) (*domain.LockResponse, error) {
|
||||
l.logger.Debug(ctx, "call srv.Lock")
|
||||
return l.repo.Lock(ctx, req)
|
||||
}
|
||||
|
||||
func (l Locker) UnLock(ctx context.Context, req domain.Request) (*domain.LockResponse, error) {
|
||||
func (l Locker) UnLock(ctx context.Context, req domain.UnLockRequest) (*domain.LockResponse, error) {
|
||||
l.logger.Debug(ctx, "call srv.UnLock")
|
||||
return l.repo.UnLock(ctx, req)
|
||||
}
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
package service
|
||||
|
||||
//
|
||||
// import (
|
||||
// "context"
|
||||
// "strconv"
|
||||
//
|
||||
// "isp-lock-service/entity"
|
||||
//
|
||||
// "github.com/integration-system/isp-kit/log"
|
||||
// "github.com/pkg/errors"
|
||||
// )
|
||||
//
|
||||
// type MessageTransaction interface {
|
||||
// Lock(ctx context.Context, req domain.Request) error
|
||||
// Insert(ctx context.Context, msg entity.Message) error
|
||||
// GetLastVersion(ctx context.Context, id int64) (int64, error)
|
||||
// UpdateById(ctx context.Context, msg entity.Message) error
|
||||
// }
|
||||
//
|
||||
// type MessageTransactionRunner interface {
|
||||
// MessageTransaction(ctx context.Context, tx func(ctx context.Context, tx MessageTransaction) error) error
|
||||
// }
|
||||
//
|
||||
// type Message struct {
|
||||
// logger log.Logger
|
||||
// txRunner MessageTransactionRunner
|
||||
// }
|
||||
//
|
||||
// func NewMessage(logger log.Logger, txRunner MessageTransactionRunner) *Message {
|
||||
// return &Message{
|
||||
// logger: logger,
|
||||
// txRunner: txRunner,
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// func (m Message) Handle(ctx context.Context, msg entity.Message) error {
|
||||
// ctx = log.ToContext(ctx, log.Int("message_id", int(msg.Id)))
|
||||
// err := m.txRunner.MessageTransaction(ctx, func(ctx context.Context, tx MessageTransaction) error {
|
||||
// return m.handle(ctx, msg, tx)
|
||||
// })
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "message transaction")
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
//
|
||||
// func (m Message) handle(ctx context.Context, msg entity.Message, tx MessageTransaction) error {
|
||||
// err := tx.Lock(ctx, strconv.FormatInt(msg.Id, 10)) //nolint:gomnd
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "lock by id")
|
||||
// }
|
||||
//
|
||||
// lastVersion, err := tx.GetLastVersion(ctx, msg.Id)
|
||||
// if errors.Is(err, entity.ErrMessageNotFound) {
|
||||
// m.logger.Debug(ctx, "message is not found. insert new one")
|
||||
// err = tx.Insert(ctx, msg)
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "insert")
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "get last msg version")
|
||||
// }
|
||||
//
|
||||
// if lastVersion < msg.Version {
|
||||
// m.logger.Debug(ctx, "newer message is received. update")
|
||||
// err = tx.UpdateById(ctx, msg)
|
||||
// if err != nil {
|
||||
// return errors.WithMessage(err, "update by id")
|
||||
// }
|
||||
// return nil
|
||||
// }
|
||||
//
|
||||
// m.logger.Debug(ctx, "old version. skipping update")
|
||||
//
|
||||
// return nil
|
||||
// }
|
||||
@@ -1,52 +0,0 @@
|
||||
package service
|
||||
|
||||
//
|
||||
// import (
|
||||
// "context"
|
||||
//
|
||||
// "isp-lock-service/domain"
|
||||
// "isp-lock-service/entity"
|
||||
//
|
||||
// "github.com/pkg/errors"
|
||||
// )
|
||||
//
|
||||
// type Repo interface {
|
||||
// All(ctx context.Context) ([]entity.Object, error)
|
||||
// Get(ctx context.Context, id int) (*entity.Object, error)
|
||||
// }
|
||||
//
|
||||
// type Object struct {
|
||||
// repo Repo
|
||||
// }
|
||||
//
|
||||
// func NewObject(repo Repo) Object {
|
||||
// return Object{
|
||||
// repo: repo,
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// func (s Object) All(ctx context.Context) ([]domain.Object, error) {
|
||||
// objects, err := s.repo.All(ctx)
|
||||
// if err != nil {
|
||||
// return nil, errors.WithMessage(err, "get all objects")
|
||||
// }
|
||||
// result := make([]domain.Object, 0, len(objects))
|
||||
// for _, object := range objects {
|
||||
// d := domain.Object{
|
||||
// Name: object.Name,
|
||||
// }
|
||||
// result = append(result, d)
|
||||
// }
|
||||
// return result, nil
|
||||
// }
|
||||
//
|
||||
// func (s Object) Get(ctx context.Context, id int) (*domain.Object, error) {
|
||||
// object, err := s.repo.Get(ctx, id)
|
||||
// if err != nil {
|
||||
// return nil, errors.WithMessagef(err, "get object by id %d", id)
|
||||
// }
|
||||
// d := domain.Object{
|
||||
// Name: object.Name,
|
||||
// }
|
||||
// return &d, nil
|
||||
// }
|
||||
@@ -1,77 +0,0 @@
|
||||
package tests_test
|
||||
|
||||
//
|
||||
// import (
|
||||
// "testing"
|
||||
// "time"
|
||||
//
|
||||
// "isp-lock-service/entity"
|
||||
//
|
||||
// "github.com/integration-system/isp-kit/dbx"
|
||||
// "github.com/integration-system/isp-kit/test"
|
||||
// "github.com/integration-system/isp-kit/test/dbt"
|
||||
// "github.com/integration-system/isp-kit/test/grmqt"
|
||||
// "github.com/rabbitmq/amqp091-go"
|
||||
// )
|
||||
//
|
||||
// func TestConsuming(t *testing.T) {
|
||||
// t.Parallel()
|
||||
// test, require := test.New(t)
|
||||
// testMq := grmqt.New(test)
|
||||
// testDb := dbt.New(test, dbx.WithMigration("../migrations"))
|
||||
//
|
||||
// // locator := assembly.NewLocator(test.Logger())
|
||||
// // config := conf.Consumer{
|
||||
// // Config: grmqx.Consumer{
|
||||
// // Queue: "test",
|
||||
// // Dlq: true,
|
||||
// // },
|
||||
// // }
|
||||
// // brokerConfig := locator.BrokerConfig(config)
|
||||
// // testMq.Upgrade(brokerConfig)
|
||||
//
|
||||
// // invalid message
|
||||
// testMq.Publish("", "test", amqp091.Publishing{Body: []byte("invalid json")})
|
||||
// time.Sleep(1 * time.Second)
|
||||
// require.EqualValues(1, testMq.QueueLength("test.DLQ"))
|
||||
//
|
||||
// // insert new message
|
||||
// expected := entity.Message{
|
||||
// Id: 1,
|
||||
// Version: 2,
|
||||
// Data: entity.MessageData{Text: "a"},
|
||||
// }
|
||||
//
|
||||
// testMq.PublishJson("", "test", expected)
|
||||
// time.Sleep(1 * time.Second)
|
||||
// actual := entity.Message{}
|
||||
// testDb.Must().SelectRow(&actual, "select * from message where id = $1", expected.Id)
|
||||
// require.EqualValues(0, testMq.QueueLength("test"))
|
||||
// require.EqualValues(expected, actual)
|
||||
//
|
||||
// // ignore message
|
||||
// oldMsg := entity.Message{
|
||||
// Id: 1,
|
||||
// Version: 1,
|
||||
// Data: entity.MessageData{Text: "b"},
|
||||
// }
|
||||
// testMq.PublishJson("", "test", oldMsg)
|
||||
// time.Sleep(1 * time.Second)
|
||||
// actual = entity.Message{}
|
||||
// testDb.Must().SelectRow(&actual, "select * from message where id = $1", expected.Id)
|
||||
// require.EqualValues(0, testMq.QueueLength("test"))
|
||||
// require.EqualValues(expected, actual)
|
||||
//
|
||||
// // update message
|
||||
// expected = entity.Message{
|
||||
// Id: 1,
|
||||
// Version: 3,
|
||||
// Data: entity.MessageData{Text: "b"},
|
||||
// }
|
||||
// testMq.PublishJson("", "test", expected)
|
||||
// time.Sleep(1 * time.Second)
|
||||
// actual = entity.Message{}
|
||||
// testDb.Must().SelectRow(&actual, "select * from message where id = $1", expected.Id)
|
||||
// require.EqualValues(0, testMq.QueueLength("test"))
|
||||
// require.EqualValues(expected, actual)
|
||||
// }
|
||||
@@ -1,109 +0,0 @@
|
||||
package tests_test
|
||||
|
||||
//
|
||||
// import (
|
||||
// "context"
|
||||
// "testing"
|
||||
//
|
||||
// "isp-lock-service/assembly"
|
||||
//
|
||||
// "github.com/integration-system/isp-kit/dbx"
|
||||
// "github.com/integration-system/isp-kit/grpc/client"
|
||||
// "github.com/integration-system/isp-kit/test"
|
||||
// "github.com/integration-system/isp-kit/test/dbt"
|
||||
// "github.com/integration-system/isp-kit/test/grpct"
|
||||
// "github.com/stretchr/testify/require"
|
||||
// "google.golang.org/grpc/codes"
|
||||
// "google.golang.org/grpc/status"
|
||||
// )
|
||||
//
|
||||
// type Object struct {
|
||||
// Name string
|
||||
// }
|
||||
//
|
||||
// func TestGetAll(t *testing.T) {
|
||||
// t.Parallel()
|
||||
// assert, testDb, cli := prepareTest(t)
|
||||
//
|
||||
// result := make([]Object, 0)
|
||||
// err := cli.Invoke("isp-lock-service/object/all").
|
||||
// ReadJsonResponse(&result).
|
||||
// Do(context.Background())
|
||||
// assert.NoError(err)
|
||||
// assert.Empty(result)
|
||||
//
|
||||
// testDb.Must().Exec("insert into object (id, name) values ($1, $2)", 1, "a")
|
||||
// testDb.Must().Exec("insert into object (id, name) values ($1, $2)", 2, "b")
|
||||
//
|
||||
// result = make([]Object, 0)
|
||||
// err = cli.Invoke("isp-lock-service/object/all").
|
||||
// ReadJsonResponse(&result).
|
||||
// Do(context.Background())
|
||||
// assert.NoError(err)
|
||||
//
|
||||
// expected := []Object{{
|
||||
// Name: "a",
|
||||
// }, {
|
||||
// Name: "b",
|
||||
// }}
|
||||
// assert.EqualValues(expected, result)
|
||||
// }
|
||||
//
|
||||
// func TestGetById(t *testing.T) {
|
||||
// t.Parallel()
|
||||
// assert, testDb, cli := prepareTest(t)
|
||||
//
|
||||
// testDb.Must().Exec("insert into object (id, name) values ($1, $2)", 1, "a")
|
||||
//
|
||||
// type reqBody struct {
|
||||
// Id int
|
||||
// }
|
||||
//
|
||||
// // empty req body
|
||||
// result := Object{}
|
||||
// err := cli.Invoke("isp-lock-service/object/get_by_id").
|
||||
// ReadJsonResponse(&result).
|
||||
// Do(context.Background())
|
||||
// assert.Error(err)
|
||||
// assert.EqualValues(codes.InvalidArgument, status.Code(err))
|
||||
//
|
||||
// // id is required
|
||||
// result = Object{}
|
||||
// err = cli.Invoke("isp-lock-service/object/get_by_id").
|
||||
// ReadJsonResponse(&result).
|
||||
// JsonRequestBody(reqBody{}).
|
||||
// Do(context.Background())
|
||||
// assert.Error(err)
|
||||
// assert.EqualValues(codes.InvalidArgument, status.Code(err))
|
||||
//
|
||||
// // not found
|
||||
// result = Object{}
|
||||
// err = cli.Invoke("isp-lock-service/object/get_by_id").
|
||||
// ReadJsonResponse(&result).
|
||||
// JsonRequestBody(reqBody{Id: 2}).
|
||||
// Do(context.Background())
|
||||
// assert.Error(err)
|
||||
// assert.EqualValues(codes.NotFound, status.Code(err))
|
||||
//
|
||||
// // happy path
|
||||
// result = Object{}
|
||||
// err = cli.Invoke("isp-lock-service/object/get_by_id").
|
||||
// ReadJsonResponse(&result).
|
||||
// JsonRequestBody(reqBody{Id: 1}).
|
||||
// Do(context.Background())
|
||||
// assert.NoError(err)
|
||||
//
|
||||
// expected := Object{Name: "a"}
|
||||
// assert.EqualValues(expected, result)
|
||||
// }
|
||||
//
|
||||
// func prepareTest(t *testing.T) (*require.Assertions, *dbt.TestDb, *client.Client) {
|
||||
// t.Helper()
|
||||
// test, assert := test.New(t)
|
||||
// testDb := dbt.New(test, dbx.WithMigration("../migrations"))
|
||||
//
|
||||
// locator := assembly.NewLocator(test.Logger())
|
||||
// _, cli := grpct.TestServer(test, locator.Handler())
|
||||
//
|
||||
// return assert, testDb, cli
|
||||
// }
|
||||
@@ -0,0 +1,80 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"isp-lock-service/rc"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"github.com/go-redsync/redsync/v4"
|
||||
"github.com/integration-system/isp-kit/test"
|
||||
)
|
||||
|
||||
func NewRedis(test *test.Test) *redis.Client {
|
||||
redisHost := test.Config().Optional().String("REDIS_HOST", "localhost")
|
||||
redisPort := test.Config().Optional().String("REDIS_PORT", "6379")
|
||||
addr := fmt.Sprintf("%s:%s", redisHost, redisPort)
|
||||
return redis.NewClient(&redis.Options{Addr: addr})
|
||||
}
|
||||
|
||||
func TestOne(t *testing.T) {
|
||||
tst, _ := test.New(t)
|
||||
rcli := NewRedis(tst)
|
||||
|
||||
r, err := rc.NewRCWithClient("testPrefix", time.Second*2, nil, rcli)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
// success story
|
||||
l, err := r.Lock("abc", time.Second)
|
||||
if err != nil {
|
||||
t.Error("#1.1::", err)
|
||||
}
|
||||
|
||||
_, err = r.UnLock("abc", l)
|
||||
if err != nil {
|
||||
t.Error("#1.2::", err)
|
||||
}
|
||||
|
||||
// look at wait
|
||||
l, err = r.Lock("abc", time.Second)
|
||||
if err != nil {
|
||||
t.Error("#2.1::", err)
|
||||
}
|
||||
|
||||
n := time.Now()
|
||||
l, err = r.Lock("abc", time.Second)
|
||||
if err != nil {
|
||||
t.Error("#2.2::", err)
|
||||
}
|
||||
diff := time.Now().Sub(n)
|
||||
if diff < time.Second {
|
||||
t.Error("#2.3::error with second lock::", diff.String())
|
||||
}
|
||||
|
||||
// look at error
|
||||
l, err = r.Lock("abc", time.Minute)
|
||||
if err != nil {
|
||||
t.Error("#3.1::", err)
|
||||
}
|
||||
|
||||
n = time.Now()
|
||||
_, err = r.Lock("abc", time.Second)
|
||||
diff = time.Now().Sub(n)
|
||||
if err == nil {
|
||||
t.Error("#3.2::", err)
|
||||
} else {
|
||||
if _, ok := err.(redsync.ErrTaken); !ok {
|
||||
t.Error("#3.3::", err)
|
||||
}
|
||||
}
|
||||
|
||||
_, err = r.UnLock("abc", l)
|
||||
if err != nil {
|
||||
t.Error("#3.4::", err)
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user