Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"account_test.go",
"audit_test.go",
"bilibili_card_test.go",
"dao_test.go",
"databus_test.go",
"memcache_test.go",
"mysql_test.go",
"qcloud_test.go",
"redis_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/spy/conf:go_default_library",
"//app/service/main/spy/model:go_default_library",
"//library/time:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"account.go",
"audit.go",
"bilibili_card.go",
"dao.go",
"databus.go",
"memcache.go",
"mysql.go",
"qcloud.go",
"redis.go",
],
importpath = "go-common/app/service/main/spy/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/spy/conf:go_default_library",
"//app/service/main/spy/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/cache/redis:go_default_library",
"//library/database/sql:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/queue/databus:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,132 @@
package dao
import (
"context"
"fmt"
"net/url"
"go-common/app/service/main/spy/model"
"go-common/library/log"
)
// tel level.
const (
TelRiskLevelLow = 1
TelRiskLevelMedium = 2
TelRiskLevelHigh = 3
TelRiskLevelUnknown = 4
)
// TelRiskLevel tel risk level.
func (d *Dao) TelRiskLevel(c context.Context, mid int64) (riskLevel int8, err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
params.Set("type", "123")
var resp struct {
TS int64 `json:"ts"`
Code int64 `json:"code"`
Data struct {
Level int8 `json:"level"`
Mid int64 `json:"mid"`
Score int64 `json:"score"`
} `json:"data"`
}
if err = d.httpClient.Get(c, d.c.Property.TelValidateURL, "", params, &resp); err != nil {
log.Error("d.httpClient.Do() error(%v) , riskLevel = TelRiskLevelUnknown", err)
riskLevel = TelRiskLevelUnknown
err = nil
return
}
if resp.Code != 0 {
err = fmt.Errorf("GET TelRiskLevel url resp(%v)", resp)
return
}
log.Info("GET TelValidateURL suc url(%s) resp(%v)", d.c.Property.TelValidateURL+"?"+params.Encode(), resp)
riskLevel = resp.Data.Level
return
}
// BlockAccount block account.
func (d *Dao) BlockAccount(c context.Context, mid int64) (err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
params.Set("admin_reason", "spy")
params.Set("blockType", "3")
params.Set("operator", "spy")
params.Set("type", "json")
var resp struct {
Code int64 `json:"code"`
}
if err = d.httpClient.Get(c, d.c.Property.BlockAccountURL, "", params, &resp); err != nil {
log.Error("httpClient.Do() error(%v)", err)
return
}
if resp.Code != 0 {
err = fmt.Errorf("GET block account url resp(%v)", resp)
}
return
}
// SecurityLogin security login
func (d *Dao) SecurityLogin(c context.Context, mid int64, reason string) (err error) {
params := url.Values{}
params.Set("mids", fmt.Sprintf("%d", mid))
params.Set("operator", "spy")
params.Set("desc", reason)
params.Set("type", "json")
var resp struct {
Code int64 `json:"code"`
}
if err = d.httpClient.Post(c, d.c.Property.SecurityLoginURL, "", params, &resp); err != nil {
log.Error("message url(%s) error(%v)", d.c.Property.SecurityLoginURL+"?"+params.Encode(), err)
return
}
if resp.Code != 0 {
err = fmt.Errorf("POST SecurityLogin url resp(%v)", resp)
return
}
log.Info("POST SecurityLogin suc url(%s) resp(%v)", resp)
return
}
// TelInfo tel info.
func (d *Dao) TelInfo(c context.Context, mid int64) (tel *model.TelInfo, err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
var resp struct {
Code int64 `json:"code"`
Data model.TelInfo `json:"data"`
}
if err = d.httpClient.Get(c, d.c.Property.TelInfoByMidURL, "", params, &resp); err != nil {
log.Error("d.httpClient.Do() error(%v) ,TelInfo", err)
return
}
if resp.Code != 0 {
err = fmt.Errorf("GET TelRiskLevel url resp(%v)", resp)
return
}
tel = &resp.Data
log.Info("GET TelInfoByMidURL suc url(%s) resp(%v)", d.c.Property.TelInfoByMidURL+"?"+params.Encode(), resp)
return
}
// ProfileInfo get user profile info from account service.
func (d *Dao) ProfileInfo(c context.Context, mid int64, remoteIP string) (profile *model.ProfileInfo, err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
var resp struct {
Code int64 `json:"code"`
Data model.ProfileInfo `json:"data"`
}
if err = d.httpClient.Get(c, d.c.Property.ProfileInfoByMidURL, remoteIP, params, &resp); err != nil {
log.Error("d.httpClient.Do() error(%v), ProfileInfo", err)
return
}
if resp.Code != 0 {
err = fmt.Errorf("GET ProfileInfo url resp(%v)", resp)
return
}
profile = &resp.Data
log.Info("GET ProfileInfoByMidURL suc url(%s) resp(%v)", d.c.Property.ProfileInfoByMidURL+"?"+params.Encode(), resp)
return
}

View File

@@ -0,0 +1,87 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoTelRiskLevel(t *testing.T) {
convey.Convey("TelRiskLevel", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
riskLevel, err := d.TelRiskLevel(c, mid)
ctx.Convey("Then err should be nil.riskLevel should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(riskLevel, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBlockAccount(t *testing.T) {
convey.Convey("BlockAccount", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.BlockAccount(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoSecurityLogin(t *testing.T) {
convey.Convey("SecurityLogin", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
reason = "unit test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SecurityLogin(c, mid, reason)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTelInfo(t *testing.T) {
convey.Convey("TelInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tel, err := d.TelInfo(c, mid)
ctx.Convey("Then err should be nil.tel should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(tel, convey.ShouldNotBeNil)
})
})
})
}
func TestProfileInfo(t *testing.T) {
convey.Convey("ProfileInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tel, err := d.ProfileInfo(c, mid, "")
ctx.Convey("Then err should be nil.tel should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(tel, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,37 @@
package dao
import (
"context"
"net/url"
"strconv"
"go-common/app/service/main/spy/model"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_auditInfo = "/api/member/audit"
)
// AuditInfo get user audit info
func (d *Dao) AuditInfo(c context.Context, mid int64, remoteIP string) (rs *model.AuditInfo, err error) {
params := url.Values{}
params.Set("mid", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
Data model.AuditInfo `json:"data"`
}
if err = d.httpClient.Get(c, d.auditInfoURI, remoteIP, params, &res); err != nil {
log.Error("account get audit info url(%s) error(%v)", d.auditInfoURI+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
log.Error("account get audit info url(%s) error(%v)", d.auditInfoURI+"?"+params.Encode(), res.Code)
err = ecode.Int(res.Code)
return
}
rs = &res.Data
log.Info("GET AuditInfoURL suc url(%s) resp(%v)", d.auditInfoURI+"?"+params.Encode(), res)
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAuditInfo(t *testing.T) {
convey.Convey("AuditInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
remoteIP = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.AuditInfo(c, mid, remoteIP)
ctx.Convey("Then err should be nil.rs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,31 @@
package dao
import (
"context"
"fmt"
"net/url"
"go-common/app/service/main/spy/model"
"go-common/library/log"
)
// UnicomGiftState get unicom gift state by mid from account service.
func (d *Dao) UnicomGiftState(c context.Context, mid int64) (state int, err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
var resp struct {
Code int64 `json:"code"`
Data *model.UnicomGiftState `json:"data"`
}
if err = d.httpClient.Get(c, d.c.Property.UnicomGiftStateURL, "", params, &resp); err != nil {
log.Error("message url(%s) error(%v)", d.c.Property.UnicomGiftStateURL+"?"+params.Encode(), err)
return
}
if resp.Code != 0 {
err = fmt.Errorf("GET UnicomGiftStateURL url resp(%v)", resp)
return
}
log.Info("GET UnicomGiftStateURL suc url(%s) resp(%v)", d.c.Property.UnicomGiftStateURL+"?"+params.Encode(), resp)
state = resp.Data.State
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoUnicomGiftState(t *testing.T) {
convey.Convey("UnicomGiftState", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(27515247)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
state, err := d.UnicomGiftState(c, mid)
ctx.Convey("Then err should be nil.state should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(state, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,87 @@
package dao
import (
"context"
"math/rand"
"time"
"go-common/app/service/main/spy/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/sql"
bm "go-common/library/net/http/blademaster"
"go-common/library/queue/databus"
)
// Dao event dao def.
type Dao struct {
c *conf.Config
// db
db *sql.DB
// mc
mcUser *memcache.Pool
mcUserExpire int32
// redis
redis *redis.Pool
expire int
verifyExpire int
// http client
httpClient *bm.Client
auditInfoURI string
// databus for spy score change
dbScoreChange *databus.Databus
r *rand.Rand
}
// New create instance of dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
// db
db: sql.NewMySQL(c.DB.Spy),
// mc
mcUser: memcache.NewPool(c.Memcache.User),
mcUserExpire: int32(time.Duration(c.Memcache.UserExpire) / time.Second),
// redis
redis: redis.NewPool(c.Redis.Config),
expire: int(time.Duration(c.Redis.Expire) / time.Second),
verifyExpire: int(time.Duration(c.Redis.VerifyCdTimes) / time.Second),
// http client
httpClient: bm.NewClient(c.HTTPClient),
auditInfoURI: c.Account + _auditInfo,
// databus
dbScoreChange: databus.New(c.DBScoreChange),
r: rand.New(rand.NewSource(time.Now().Unix())),
}
if conf.Conf.Property.UserInfoShard <= 0 {
panic("conf.Conf.Property.UserInfoShard <= 0")
}
if conf.Conf.Property.HistoryShard <= 0 {
panic("conf.Conf.Property.HistoryShard <= 0")
}
return
}
// Ping check db health.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.pingMC(c); err != nil {
return
}
if err = d.PingRedis(c); err != nil {
return
}
return d.db.Ping(c)
}
// Close close all db connections.
func (d *Dao) Close() {
if d.mcUser != nil {
d.mcUser.Close()
}
if d.redis != nil {
d.redis.Close()
}
if d.db != nil {
d.db.Close()
}
}

View File

@@ -0,0 +1,35 @@
package dao
import (
"flag"
"go-common/app/service/main/spy/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.account.spy-service")
flag.Set("conf_token", "22741f7d4338595a152f282062e4e2fa")
flag.Set("tree_id", "2855")
flag.Set("conf_version", "docker-1")
flag.Set("deploy_env", "uat")
flag.Set("conf_host", "config.bilibili.co")
flag.Set("conf_path", "/tmp")
flag.Set("region", "sh")
flag.Set("zone", "sh001")
} else {
flag.Set("conf", "../cmd/spy-service.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}

View File

@@ -0,0 +1,17 @@
package dao
import (
"context"
"strconv"
"go-common/library/log"
)
// PubScoreChange pub spy score change msg into databus.
func (d *Dao) PubScoreChange(c context.Context, mid int64, msg interface{}) (err error) {
key := strconv.FormatInt(mid, 10)
if err = d.dbScoreChange.Send(c, key, msg); err != nil {
log.Error("d.dbScoreChange.Send(%s, %v) error (%v)", key, msg, err)
}
return
}

View File

@@ -0,0 +1,24 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoPubScoreChange(t *testing.T) {
convey.Convey("PubScoreChange", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
msg = interface{}(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.PubScoreChange(c, mid, msg)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,103 @@
package dao
import (
"context"
"fmt"
"go-common/app/service/main/spy/model"
"go-common/library/cache/memcache"
"go-common/library/log"
)
const (
_userKey = "u_%d"
)
// pingMC ping memcache.
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mcUser.Get(c)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 0}); err != nil {
log.Error("conn.Store(set,ping,1) error(%v)", err)
}
return
}
func userInfoCacheKey(mid int64) string {
return fmt.Sprintf(_userKey, mid)
}
// UserInfoCache get user info to cache.
func (d *Dao) UserInfoCache(c context.Context, mid int64) (ui *model.UserInfo, err error) {
var (
key = userInfoCacheKey(mid)
conn = d.mcUser.Get(c)
)
defer conn.Close()
reply, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("conn.Get(get, %s) error(%v)", key, err)
return
}
ui = &model.UserInfo{}
if err = conn.Scan(reply, ui); err != nil {
log.Error("reply.Scan(%s) error(%v)", string(reply.Value), err)
}
return
}
// AddUserInfoCache add info to cache , return err if key is exist already.
func (d *Dao) AddUserInfoCache(c context.Context, ui *model.UserInfo) (err error) {
if ui == nil {
return fmt.Errorf("AddUserInfoCache got nil *model.UserInfo")
}
var (
key = userInfoCacheKey(ui.Mid)
conn = d.mcUser.Get(c)
)
defer conn.Close()
if err = conn.Add(&memcache.Item{Key: key, Object: ui, Expiration: d.mcUserExpire, Flags: memcache.FlagJSON}); err != nil {
log.Error("conn.Add(%s, %v) error(%v)", key, ui, err)
return
}
return
}
// SetUserInfoCache set info cache.
func (d *Dao) SetUserInfoCache(c context.Context, ui *model.UserInfo) (err error) {
if ui == nil {
return fmt.Errorf("SetUserInfoCache got nil *model.UserInfo")
}
var (
key = userInfoCacheKey(ui.Mid)
conn = d.mcUser.Get(c)
)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: key, Object: ui, Expiration: d.mcUserExpire, Flags: memcache.FlagJSON}); err != nil {
log.Error("conn.Set(%s, %v) error(%v)", key, ui, err)
}
return
}
// DelInfoCache delete info cache.
func (d *Dao) DelInfoCache(c context.Context, mid int64) (err error) {
var (
key = userInfoCacheKey(mid)
conn = d.mcUser.Get(c)
)
defer conn.Close()
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
err = nil
return
}
log.Error("conn.Delete(%s) error(%v)", key, err)
}
return
}

View File

@@ -0,0 +1,97 @@
package dao
import (
"context"
"go-common/app/service/main/spy/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaopingMC(t *testing.T) {
convey.Convey("pingMC", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.pingMC(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaouserInfoCacheKey(t *testing.T) {
convey.Convey("userInfoCacheKey", t, func(ctx convey.C) {
var (
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := userInfoCacheKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUserInfoCache(t *testing.T) {
convey.Convey("UserInfoCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.UserInfoCache(c, mid)
ctx.Convey("Then err should be nil.ui should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddUserInfoCache(t *testing.T) {
convey.Convey("AddUserInfoCache", t, func(ctx convey.C) {
var (
c = context.Background()
ui = &model.UserInfo{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddUserInfoCache(c, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetUserInfoCache(t *testing.T) {
convey.Convey("SetUserInfoCache", t, func(ctx convey.C) {
var (
c = context.Background()
ui = &model.UserInfo{}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.SetUserInfoCache(c, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoDelInfoCache(t *testing.T) {
convey.Convey("DelInfoCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.DelInfoCache(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}

View File

@@ -0,0 +1,475 @@
package dao
import (
"context"
xsql "database/sql"
"fmt"
"time"
"go-common/app/service/main/spy/conf"
"go-common/app/service/main/spy/model"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
_serviceSQL = "SELECT id,name,nick_name,status,ctime,mtime FROM spy_service WHERE name=? AND status<>0 LIMIT 1"
_addServiceSQL = "INSERT INTO spy_service (name,nick_name,status,ctime) VALUES (?,?,?,?)"
_eventSQL = "SELECT id,name,nick_name,service_id,status,ctime,mtime FROM spy_event WHERE name=? AND status<>0 LIMIT 1"
_addEventSQL = "INSERT INTO spy_event (name,nick_name,service_id,status,ctime) VALUES (?,?,?,?,?)"
_factorSQL = "SELECT id,nick_name,service_id,event_id,group_id,risk_level,factor_val,ctime,mtime FROM spy_factor WHERE service_id=? AND event_id=? AND risk_level=? LIMIT 1"
_factorGroupSQL = "SELECT id,name,ctime FROM spy_factor_group WHERE name=? LIMIT 1"
_userInfoSQL = "SELECT id,mid,score,base_score,event_score,state,relive_times,ctime,mtime FROM spy_user_info_%02d WHERE mid=? LIMIT 1"
_addUserInfoSQL = "INSERT IGNORE INTO spy_user_info_%02d (mid,score,base_score,event_score,state,ctime,mtime) VALUES (?,?,?,?,?,?,?)"
_updateEventScoreSQL = "UPDATE spy_user_info_%02d SET event_score=?, score=? WHERE mid=?"
_updateInfoSQL = "UPDATE spy_user_info_%02d SET base_score=?, event_score=?, score=?, state=? WHERE mid=?;"
_updateBaseScoreSQL = "UPDATE spy_user_info_%02d SET base_score=?, score=? WHERE mid=?;"
_addEventHistorySQL = "INSERT INTO spy_user_event_history_%02d (mid,event_id,score,base_score,event_score,remark,reason,factor_val,ctime) VALUES (?,?,?,?,?,?,?,?,?);"
_getEventHistoryByMidAndEventSQL = "SELECT mid, event_id FROM spy_user_event_history_%02d WHERE mid = ? and event_id = ? limit 1"
_addPunishmentSQL = "INSERT INTO spy_punishment (mid,type,reason,ctime) VALUES (?,?,?,?);"
_addPunishmentQueueSQL = "INSERT INTO spy_punishment_queue (mid,batch_no,ctime) VALUES (?,?,?) ON DUPLICATE KEY UPDATE mtime=?;"
_getAllConfigSQL = "SELECT id, property,name,val,ctime FROM spy_system_config;"
_clearReliveTimesSQL = "UPDATE spy_user_info_%02d SET relive_times=? WHERE mid=?;"
_getHistoryListSQL = "SELECT remark,reason FROM spy_user_event_history_%02d WHERE mid= ? ORDER BY id DESC LIMIT ?;"
_updateEventScoreReLiveSQL = "UPDATE spy_user_info_%02d SET event_score=?, score=?, relive_times=relive_times+1 WHERE mid=?"
_statListByMidSQL = "SELECT event_id,quantity FROM spy_statistics WHERE target_mid = ? AND isdel = 0 ORDER BY id desc LIMIT 100;"
_statListByIDSQL = "SELECT event_id,quantity FROM spy_statistics WHERE target_id = ? AND isdel = 0 ORDER BY id desc LIMIT 100;"
_statListByIDAndMidSQL = "SELECT event_id,quantity FROM spy_statistics WHERE target_mid = ? AND target_id = ? AND isdel = 0 ORDER BY id desc LIMIT 100;"
_allEventSQL = "SELECT id,name,nick_name,service_id,status,ctime,mtime FROM spy_event WHERE status<>0"
_telLevelSQL = "SELECT id,mid,level,origin,ctime,mtime FROM spy_tel_risk_level WHERE mid = ? LIMIT 1;"
_addTelLevelSQL = "INSERT INTO spy_tel_risk_level (mid,level,origin,ctime) VALUES (?,?,?,?) "
)
// Service get service from db.
func (d *Dao) Service(c context.Context, serviceName string) (service *model.Service, err error) {
var (
row *sql.Row
)
service = &model.Service{}
row = d.db.QueryRow(c, _serviceSQL, serviceName)
if err = row.Scan(&service.ID, &service.Name, &service.NickName, &service.Status, &service.CTime, &service.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
service = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}
// Event get event from db.
func (d *Dao) Event(c context.Context, eventName string) (event *model.Event, err error) {
var row *sql.Row
event = &model.Event{}
row = d.db.QueryRow(c, _eventSQL, eventName)
if err = row.Scan(&event.ID, &event.Name, &event.NickName, &event.ServiceID, &event.Status, &event.CTime, &event.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
event = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}
// AddService insert service to db.
func (d *Dao) AddService(c context.Context, service *model.Service) (id int64, err error) {
var (
res xsql.Result
)
if res, err = d.db.Exec(c, _addServiceSQL, service.Name, service.NickName, service.Status, time.Now()); err != nil {
log.Error("d.db.Exec(%s, %s, %d) error(%v)", _addServiceSQL, service.Name, service.Status, err)
return
}
if id, err = res.LastInsertId(); err != nil {
log.Error("res.LastInsertId() error(%v)", err)
}
return
}
// AddEvent insert service to db.
func (d *Dao) AddEvent(c context.Context, event *model.Event) (id int64, err error) {
var (
res xsql.Result
)
if res, err = d.db.Exec(c, _addEventSQL, event.Name, event.NickName, event.ServiceID, event.Status, time.Now()); err != nil {
log.Error("d.db.Exec(%s, %s, %s, %d, %d) error(%v)", _addEventSQL, event.Name, event.NickName, event.ServiceID, event.Status, err)
return
}
if id, err = res.LastInsertId(); err != nil {
log.Error("res.LastInsertId() error(%v)", err)
}
return
}
// Factor get factor from db.
func (d *Dao) Factor(c context.Context, serviceID, eventID int64, riskLevel int8) (factor *model.Factor, err error) {
var (
row *sql.Row
)
factor = &model.Factor{}
row = d.db.QueryRow(c, _factorSQL, serviceID, eventID, riskLevel)
if err = row.Scan(&factor.ID, &factor.NickName, &factor.ServiceID, &factor.EventID, &factor.GroupID, &factor.RiskLevel, &factor.FactorVal, &factor.CTime, &factor.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
factor = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}
// FactorGroup get factor group from db.
func (d *Dao) FactorGroup(c context.Context, groupName string) (factorGroup *model.FactorGroup, err error) {
var (
row *sql.Row
)
factorGroup = &model.FactorGroup{}
row = d.db.QueryRow(c, _factorGroupSQL, groupName)
if err = row.Scan(&factorGroup.ID, &factorGroup.Name, &factorGroup.CTime); err != nil {
if err == sql.ErrNoRows {
err = nil
factorGroup = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}
func hitInfo(id int64) int64 {
return id % conf.Conf.Property.UserInfoShard
}
func hitHistory(id int64) int64 {
return id % conf.Conf.Property.HistoryShard
}
// BeginTran begin transaction.
func (d *Dao) BeginTran(c context.Context) (*sql.Tx, error) {
return d.db.Begin(c)
}
// UserInfo get info by mid.
func (d *Dao) UserInfo(c context.Context, mid int64) (res *model.UserInfo, err error) {
var (
row *sql.Row
)
res = &model.UserInfo{}
row = d.db.QueryRow(c, fmt.Sprintf(_userInfoSQL, hitInfo(mid)), mid)
if err = row.Scan(&res.ID, &res.Mid, &res.Score, &res.BaseScore, &res.EventScore, &res.State, &res.ReliveTimes, &res.CTime, &res.MTime); err != nil {
if err == sql.ErrNoRows {
err = nil
res = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}
// TxUpdateInfo insert or update user info by mid.
func (d *Dao) TxUpdateInfo(c context.Context, tx *sql.Tx, info *model.UserInfo) (err error) {
if _, err = d.db.Exec(c, fmt.Sprintf(_updateInfoSQL, hitInfo(info.Mid)), info.BaseScore, info.EventScore, info.Score, info.State, info.Mid); err != nil {
log.Error("db.Exec(%d, %+v) error(%v)", info.Mid, info, err)
return
}
return
}
// TxAddInfo add user info.
func (d *Dao) TxAddInfo(c context.Context, tx *sql.Tx, info *model.UserInfo) (id int64, err error) {
var (
res xsql.Result
now = time.Now()
)
if res, err = tx.Exec(fmt.Sprintf(_addUserInfoSQL, hitInfo(info.Mid)), info.Mid, info.Score, info.BaseScore, info.EventScore, info.State, now, now); err != nil {
log.Error("db.Exec(%d, %v) error(%v)", info.Mid, *info, err)
return
}
return res.LastInsertId()
}
// TxAddEventHistory insert user_event_history.
func (d *Dao) TxAddEventHistory(c context.Context, tx *sql.Tx, ueh *model.UserEventHistory) (err error) {
var (
now = time.Now()
)
if _, err = tx.Exec(fmt.Sprintf(_addEventHistorySQL, hitHistory(ueh.Mid)), ueh.Mid, ueh.EventID, ueh.Score, ueh.BaseScore, ueh.EventScore, ueh.Remark, ueh.Reason, ueh.FactorVal, now); err != nil {
log.Error("db.Exec(%v) error(%v)", ueh, err)
return
}
return
}
// EventHistoryByMidAndEvent get one event history with mid and eventID from db.
func (d *Dao) EventHistoryByMidAndEvent(c context.Context, mid int64, eventID int64) (res *model.UserEventHistory, err error) {
var (
row *sql.Row
)
res = &model.UserEventHistory{}
row = d.db.QueryRow(c, fmt.Sprintf(_getEventHistoryByMidAndEventSQL, hitHistory(mid)), mid, eventID)
if err = row.Scan(&res.Mid, &res.EventID); err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
log.Error("row.Scan() error:(%v)", err)
}
return
}
// TxAddPunishment insert punishment.
func (d *Dao) TxAddPunishment(c context.Context, tx *sql.Tx, mid int64, t int8, reason string) (err error) {
var (
now = time.Now()
)
if _, err = tx.Exec(_addPunishmentSQL, mid, t, reason, now); err != nil {
log.Error("db.Exec(%d, %d, %s) error(%v)", mid, t, reason, err)
return
}
return
}
// TxAddPunishmentQueue insert punishment queue.
func (d *Dao) TxAddPunishmentQueue(c context.Context, tx *sql.Tx, mid int64, blockNo int64) (err error) {
var (
now = time.Now()
)
if _, err = tx.Exec(_addPunishmentQueueSQL, mid, blockNo, now, now); err != nil {
log.Error("TxAddPunishmentQueue:db.Exec(%d) error(%v)", mid, err)
return
}
return
}
// AddPunishmentQueue insert punishment queue.
func (d *Dao) AddPunishmentQueue(c context.Context, mid int64, blockNo int64) (err error) {
var (
now = time.Now()
)
if _, err = d.db.Exec(c, _addPunishmentQueueSQL, mid, blockNo, now, now); err != nil {
log.Error("AddPunishmentQueue:db.Exec(%d) error(%v)", mid, err)
return
}
return
}
// TxUpdateEventScore update user event score.
func (d *Dao) TxUpdateEventScore(c context.Context, tx *sql.Tx, mid int64, escore, score int8) (err error) {
if _, err = tx.Exec(fmt.Sprintf(_updateEventScoreSQL, hitInfo(mid)), escore, score, mid); err != nil {
log.Error("db.TxUpdateEventScore(%s, %d, %d, %d) error(%v)", _updateEventScoreSQL, escore, score, mid, err)
return
}
return
}
//TxUpdateBaseScore do update user base score.
func (d *Dao) TxUpdateBaseScore(c context.Context, tx *sql.Tx, ui *model.UserInfo) (err error) {
if _, err = tx.Exec(fmt.Sprintf(_updateBaseScoreSQL, hitInfo(ui.Mid)), ui.BaseScore, ui.Score, ui.Mid); err != nil {
log.Error("db.TxUpdateBaseScore(%d, %d, %d) error(%v)", ui.BaseScore, ui.Score, ui.Mid, err)
return
}
return
}
//TxClearReliveTimes do clear user relivetimes.
func (d *Dao) TxClearReliveTimes(c context.Context, tx *sql.Tx, ui *model.UserInfo) (err error) {
if _, err = tx.Exec(fmt.Sprintf(_clearReliveTimesSQL, hitInfo(ui.Mid)), ui.ReliveTimes, ui.Mid); err != nil {
log.Error("db.TxClearReliveTimes(%d, %d) error(%v)", ui.ReliveTimes, ui.Mid, err)
return
}
return
}
// Configs spy system configs.
func (d *Dao) Configs(c context.Context) (res map[string]string, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, _getAllConfigSQL); err != nil {
log.Error("d.getAllConfigSQL.Query error(%v)", err)
return
}
defer rows.Close()
res = make(map[string]string)
for rows.Next() {
var r model.Config
if err = rows.Scan(&r.ID, &r.Property, &r.Name, &r.Val, &r.Ctime); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res[r.Property] = r.Val
}
err = rows.Err()
return
}
// HistoryList query .
func (d *Dao) HistoryList(c context.Context, mid int64, size int) (res []*model.UserEventHistory, err error) {
var rows *sql.Rows
if rows, err = d.db.Query(c, fmt.Sprintf(_getHistoryListSQL, hitHistory(mid)), mid, size); err != nil {
log.Error("d.HistoryList.Query(%d, %d) error(%v)", mid, size, err)
return
}
defer rows.Close()
for rows.Next() {
r := &model.UserEventHistory{}
if err = rows.Scan(&r.Remark, &r.Reason); err != nil {
log.Error("row.Scan() error(%v)", err)
res = nil
return
}
res = append(res, r)
}
err = rows.Err()
return
}
// TxUpdateEventScoreReLive update event score and times
func (d *Dao) TxUpdateEventScoreReLive(c context.Context, tx *sql.Tx, mid int64, escore, score int8) (err error) {
if _, err = tx.Exec(fmt.Sprintf(_updateEventScoreReLiveSQL, hitInfo(mid)), escore, score, mid); err != nil {
log.Error("db.TxUpdateEventScoreReLive(%s, %d, %d, %d) error(%v)", _updateEventScoreReLiveSQL, escore, score, mid, err)
return
}
return
}
//StatListByMid stat list by mid.
func (d *Dao) StatListByMid(c context.Context, mid int64) (list []*model.Statistics, err error) {
var (
rows *sql.Rows
)
list = make([]*model.Statistics, 0)
if rows, err = d.db.Query(c, _statListByMidSQL, mid); err != nil {
log.Error("d.db.Query(%s) error(%v)", _statListByMidSQL, err)
return
}
defer rows.Close()
for rows.Next() {
var r = &model.Statistics{}
if err = rows.Scan(&r.EventID, &r.Quantity); err != nil {
log.Error("rows.Scan() error(%v)", err)
return
}
list = append(list, &model.Statistics{
EventID: r.EventID,
Quantity: r.Quantity,
})
}
return
}
//StatListByIDAndMid stat list by id.
func (d *Dao) StatListByIDAndMid(c context.Context, mid, id int64) (list []*model.Statistics, err error) {
var (
rows *sql.Rows
)
list = make([]*model.Statistics, 0)
if rows, err = d.db.Query(c, _statListByIDAndMidSQL, mid, id); err != nil {
log.Error("d.db.Query(%s) error(%v)", _statListByIDAndMidSQL, err)
return
}
defer rows.Close()
for rows.Next() {
var r = &model.Statistics{}
if err = rows.Scan(&r.EventID, &r.Quantity); err != nil {
log.Error("rows.Scan() error(%v)", err)
return
}
list = append(list, &model.Statistics{
EventID: r.EventID,
Quantity: r.Quantity,
})
}
return
}
//StatListByID stat list by id.
func (d *Dao) StatListByID(c context.Context, id int64) (list []*model.Statistics, err error) {
var (
rows *sql.Rows
)
list = make([]*model.Statistics, 0)
if rows, err = d.db.Query(c, _statListByIDSQL, id); err != nil {
log.Error("d.db.Query(%s) error(%v)", _statListByIDSQL, err)
return
}
defer rows.Close()
for rows.Next() {
var r = &model.Statistics{}
if err = rows.Scan(&r.EventID, &r.Quantity); err != nil {
log.Error("rows.Scan() error(%v)", err)
return
}
list = append(list, &model.Statistics{
EventID: r.EventID,
Quantity: r.Quantity,
})
}
return
}
//AllEvent all event.
func (d *Dao) AllEvent(c context.Context) (list []*model.Event, err error) {
var (
rows *sql.Rows
)
list = make([]*model.Event, 0)
if rows, err = d.db.Query(c, _allEventSQL); err != nil {
log.Error("d.db.Query(%s) error(%v)", _allEventSQL, err)
return
}
defer rows.Close()
for rows.Next() {
var event = &model.Event{}
if err = rows.Scan(&event.ID, &event.Name, &event.NickName, &event.ServiceID, &event.Status, &event.CTime, &event.MTime); err != nil {
log.Error("rows.Scan() error(%v)", err)
return
}
list = append(list, &model.Event{
ID: event.ID,
Name: event.Name,
NickName: event.NickName,
ServiceID: event.ServiceID,
Status: event.Status,
CTime: event.CTime,
MTime: event.MTime,
})
}
return
}
// TelLevel tel level.
func (d *Dao) TelLevel(c context.Context, mid int64) (res *model.TelRiskLevel, err error) {
var (
row *sql.Row
)
res = &model.TelRiskLevel{}
row = d.db.QueryRow(c, _telLevelSQL, mid)
if err = row.Scan(&res.ID, &res.Mid, &res.Level, &res.Origin, &res.Ctime, &res.Mtime); err != nil {
if err == sql.ErrNoRows {
err = nil
res = nil
return
}
log.Error("row.Scan() error(%v)", err)
}
return
}
// AddTelLevelInfo add tel level info.
func (d *Dao) AddTelLevelInfo(c context.Context, t *model.TelRiskLevel) (id int64, err error) {
var (
res xsql.Result
)
if res, err = d.db.Exec(c, _addTelLevelSQL, t.Mid, t.Level, t.Origin, time.Now()); err != nil {
log.Error("d.db.Exec(%s, %v) error(%v)", _addTelLevelSQL, t, err)
return
}
if id, err = res.LastInsertId(); err != nil {
log.Error("res.LastInsertId() error(%v)", err)
}
return
}

View File

@@ -0,0 +1,498 @@
package dao
import (
"context"
"fmt"
"testing"
"time"
"go-common/app/service/main/spy/model"
xtime "go-common/library/time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoService(t *testing.T) {
convey.Convey("Service", t, func(ctx convey.C) {
var (
c = context.Background()
serviceName = "account-service"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
service, err := d.Service(c, serviceName)
ctx.Convey("Then err should be nil.service should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(service, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoEvent(t *testing.T) {
convey.Convey("Event", t, func(ctx convey.C) {
var (
c = context.Background()
eventName = "init_user_info"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.Event(c, eventName)
ctx.Convey("Then err should be nil.event should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddService(t *testing.T) {
convey.Convey("AddService", t, func(ctx convey.C) {
var (
c = context.Background()
service = &model.Service{
Name: fmt.Sprintf("ut_%d", time.Now().Unix()),
NickName: "test",
Status: 0,
CTime: xtime.Time(time.Now().Unix()),
MTime: xtime.Time(time.Now().Unix()),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
id, err := d.AddService(c, service)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddEvent(t *testing.T) {
convey.Convey("AddEvent", t, func(ctx convey.C) {
var (
c = context.Background()
event = &model.Event{
Name: fmt.Sprintf("ut_%d", time.Now().Unix()),
NickName: "test",
Status: 1,
CTime: xtime.Time(time.Now().Unix()),
MTime: xtime.Time(time.Now().Unix()),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
id, err := d.AddEvent(c, event)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoFactor(t *testing.T) {
convey.Convey("Factor", t, func(ctx convey.C) {
var (
c = context.Background()
serviceID = int64(1)
eventID = int64(1)
riskLevel = int8(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
factor, err := d.Factor(c, serviceID, eventID, riskLevel)
ctx.Convey("Then err should be nil.factor should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(factor, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoFactorGroup(t *testing.T) {
convey.Convey("FactorGroup", t, func(ctx convey.C) {
var (
c = context.Background()
groupName = "基础资料分值"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.FactorGroup(c, groupName)
ctx.Convey("Then err should be nil.factorGroup should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaohitInfo(t *testing.T) {
convey.Convey("hitInfo", t, func(ctx convey.C) {
var (
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := hitInfo(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaohitHistory(t *testing.T) {
convey.Convey("hitHistory", t, func(ctx convey.C) {
var (
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := hitHistory(id)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoBeginTran(t *testing.T) {
convey.Convey("BeginTran", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1, err := d.BeginTran(c)
ctx.Convey("Then err should be nil.p1 should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoUserInfo(t *testing.T) {
convey.Convey("UserInfo", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.UserInfo(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateInfo(t *testing.T) {
convey.Convey("TxUpdateInfo", t, func(ctx convey.C) {
var (
c = context.Background()
info = &model.UserInfo{
Mid: 1,
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxUpdateInfo(c, tx, info)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxAddInfo(t *testing.T) {
convey.Convey("TxAddInfo", t, func(ctx convey.C) {
var (
c = context.Background()
info = &model.UserInfo{
Mid: time.Now().Unix(),
}
id int64
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
id, err = d.TxAddInfo(c, tx, info)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxAddEventHistory(t *testing.T) {
convey.Convey("TxAddEventHistory", t, func(ctx convey.C) {
var (
c = context.Background()
ueh = &model.UserEventHistory{
Mid: 1,
Remark: "un_test",
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxAddEventHistory(c, tx, ueh)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxAddPunishment(t *testing.T) {
convey.Convey("TxAddPunishment", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
no = int8(0)
reason = "unit test"
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxAddPunishment(c, tx, mid, no, reason)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxAddPunishmentQueue(t *testing.T) {
convey.Convey("TxAddPunishmentQueue", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
blockNo = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxAddPunishmentQueue(c, tx, mid, blockNo)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddPunishmentQueue(t *testing.T) {
convey.Convey("AddPunishmentQueue", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
blockNo = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddPunishmentQueue(c, mid, blockNo)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxUpdateEventScore(t *testing.T) {
convey.Convey("TxUpdateEventScore", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
escore = int8(0)
score = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxUpdateEventScore(c, tx, mid, escore, score)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxUpdateBaseScore(t *testing.T) {
convey.Convey("TxUpdateBaseScore", t, func(ctx convey.C) {
var (
c = context.Background()
ui = &model.UserInfo{Mid: 1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxUpdateBaseScore(c, tx, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoTxClearReliveTimes(t *testing.T) {
convey.Convey("TxClearReliveTimes", t, func(ctx convey.C) {
var (
c = context.Background()
ui = &model.UserInfo{Mid: 1}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxClearReliveTimes(c, tx, ui)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoConfigs(t *testing.T) {
convey.Convey("Configs", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.Configs(c)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoHistoryList(t *testing.T) {
convey.Convey("HistoryList", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
size = int(10)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.HistoryList(c, mid, size)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTxUpdateEventScoreReLive(t *testing.T) {
convey.Convey("TxUpdateEventScoreReLive", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
escore = int8(0)
score = int8(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
tx, err := d.BeginTran(c)
ctx.So(err, convey.ShouldBeNil)
err = d.TxUpdateEventScoreReLive(c, tx, mid, escore, score)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoStatListByMid(t *testing.T) {
convey.Convey("StatListByMid", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
list, err := d.StatListByMid(c, mid)
ctx.Convey("Then err should be nil.list should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(list, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoStatListByIDAndMid(t *testing.T) {
convey.Convey("StatListByIDAndMid", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
list, err := d.StatListByIDAndMid(c, mid, id)
ctx.Convey("Then err should be nil.list should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(list, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoStatListByID(t *testing.T) {
convey.Convey("StatListByID", t, func(ctx convey.C) {
var (
c = context.Background()
id = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
list, err := d.StatListByID(c, id)
ctx.Convey("Then err should be nil.list should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(list, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAllEvent(t *testing.T) {
convey.Convey("AllEvent", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
list, err := d.AllEvent(c)
ctx.Convey("Then err should be nil.list should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(list, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoTelLevel(t *testing.T) {
convey.Convey("TelLevel", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(1)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.TelLevel(c, mid)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoAddTelLevelInfo(t *testing.T) {
convey.Convey("AddTelLevelInfo", t, func(ctx convey.C) {
var (
c = context.Background()
no = &model.TelRiskLevel{
Mid: time.Now().Unix(),
Level: 1,
Origin: 1,
Ctime: time.Now(),
Mtime: time.Now(),
}
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
id, err := d.AddTelLevelInfo(c, no)
ctx.Convey("Then err should be nil.id should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(id, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,85 @@
package dao
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"net/http"
"net/url"
"sort"
"time"
"go-common/app/service/main/spy/model"
"go-common/library/log"
)
func (d *Dao) hmacsha1(key, text string) (h string) {
mac := hmac.New(sha1.New, []byte(key))
mac.Write([]byte(text))
h = base64.StdEncoding.EncodeToString(mac.Sum(nil))
return
}
func (d *Dao) makeURL(method string, action string, region string, secretID string, secretKey string,
args url.Values, charset string, URL string) (req string) {
args.Set("Nonce", fmt.Sprintf("%d", d.r.Uint32()))
args.Set("Action", action)
args.Set("Region", region)
args.Set("SecretId", secretID)
args.Set("Timestamp", fmt.Sprintf("%d", time.Now().Unix()))
args.Set("Signature", d.hmacsha1(secretKey, fmt.Sprintf("%s%s?%s", method, URL, d.makeQueryString(args))))
req = args.Encode()
return
}
func (d *Dao) makeQueryString(v url.Values) (str string) {
if v == nil {
return ""
}
var buf bytes.Buffer
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
vs := v[k]
prefix := k + "="
for _, v := range vs {
if buf.Len() > 0 {
buf.WriteString("&")
}
buf.WriteString(prefix)
buf.WriteString(v)
}
}
return buf.String()
}
// RegisterProtection register protection.
func (d *Dao) RegisterProtection(c context.Context, args url.Values, ip string) (level int8, err error) {
query := d.makeURL("GET", d.c.Qcloud.Path, d.c.Qcloud.Region, d.c.Qcloud.SecretID,
d.c.Qcloud.SecretKey, args, d.c.Qcloud.Charset, d.c.Qcloud.BaseURL)
req, err := http.NewRequest("GET", "https://"+d.c.Qcloud.BaseURL+"?"+query, nil)
if err != nil {
log.Error("d.RegisterProtection uri(%s) error(%v)", query, err)
return
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res := &model.QcloudRegProResp{}
if err = d.httpClient.Do(c, req, res); err != nil {
log.Error("d.client.Do error(%v) | uri(%s)) res(%v)", err, query, res)
return
}
if res.Code != 0 {
err = fmt.Errorf("GET RegisterProtection req faild query(%s) resp(%v)", d.c.Qcloud.BaseURL+"?"+query, res)
log.Error(" RegisterProtection fail res(%v)", res)
return
}
level = res.Level
log.Info("GET RegisterProtection suc query(%s) resp(%v)", query, res)
return
}

View File

@@ -0,0 +1,89 @@
package dao
import (
"context"
"fmt"
"go-common/app/service/main/spy/model"
"net/url"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestDaohmacsha1(t *testing.T) {
convey.Convey("hmacsha1", t, func(ctx convey.C) {
var (
key = ""
text = ""
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
h := d.hmacsha1(key, text)
ctx.Convey("Then h should not be nil.", func(ctx convey.C) {
ctx.So(h, convey.ShouldNotBeNil)
})
})
})
}
func TestDaomakeURL(t *testing.T) {
convey.Convey("makeURL", t, func(ctx convey.C) {
var (
method = "1"
action = "1"
region = "1"
secretID = "1"
secretKey = "1"
charset = "1"
URL = "1"
)
args := url.Values{}
args.Set("accountType", fmt.Sprintf("%d", model.AccountType))
args.Set("uid", fmt.Sprintf("%d", 1))
args.Set("phoneNumber", "13262609601")
args.Set("registerTime", fmt.Sprintf("%d", time.Now().Unix()))
args.Set("registerIp", "127.0.0.1")
ctx.Convey("When everything goes positive", func(ctx convey.C) {
req := d.makeURL(method, action, region, secretID, secretKey, args, charset, URL)
ctx.Convey("Then req should not be nil.", func(ctx convey.C) {
ctx.So(req, convey.ShouldNotBeNil)
})
})
})
}
func TestDaomakeQueryString(t *testing.T) {
convey.Convey("makeQueryString", t, func(ctx convey.C) {
var (
v url.Values
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
str := d.makeQueryString(v)
ctx.Convey("Then str should not be nil.", func(ctx convey.C) {
ctx.So(str, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoRegisterProtection(t *testing.T) {
convey.Convey("RegisterProtection", t, func(ctx convey.C) {
var (
c = context.Background()
ip = "127.0.0.1"
)
args := url.Values{}
args.Set("accountType", fmt.Sprintf("%d", model.AccountType))
args.Set("uid", fmt.Sprintf("%d", 1))
args.Set("phoneNumber", "13262609601")
args.Set("registerTime", fmt.Sprintf("%d", time.Now().Unix()))
args.Set("registerIp", ip)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
level, err := d.RegisterProtection(c, args, ip)
ctx.Convey("Then err should be nil.level should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(level, convey.ShouldNotBeNil)
})
})
})
}

View File

@@ -0,0 +1,96 @@
package dao
import (
"context"
"fmt"
"go-common/library/cache/redis"
"go-common/library/log"
)
const (
_keyWaitBlock = "wb_" // b_batch_no wait block
_preLock = "lk_"
)
// keyWaitBlock return block cache key.
func keyWaitBlock(batchNo int64) string {
return _keyWaitBlock + fmt.Sprintf("%d", batchNo)
}
func lockKey(key int64) string {
return fmt.Sprintf("%s%d", _preLock, key)
}
// AddBlockCache add block cache.
func (d *Dao) AddBlockCache(c context.Context, mid int64, score int8, blockNo int64) (err error) {
var (
key = keyWaitBlock(blockNo)
)
conn := d.redis.Get(c)
defer conn.Close()
if err = conn.Send("ZADD", key, score, mid); err != nil {
log.Error("conn.Send(ZADD %s,%d,%d) error(%v)", key, score, mid, err)
return
}
if err = conn.Send("EXPIRE", key, d.expire); err != nil {
log.Error("conn.Send(EXPIRE) error(%v)", err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush() error(%v)", err)
return
}
for i := 0; i < 2; i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive() error(%v)", err)
return
}
}
return
}
// BlockMidCache get wait block mids.
func (d *Dao) BlockMidCache(c context.Context, batchNo int64, num int64) (res []int64, err error) {
var (
conn = d.redis.Get(c)
key = keyWaitBlock(batchNo)
)
defer conn.Close()
if res, err = redis.Int64s(conn.Do("ZREVRANGEBYSCORE", key, "+inf", "-inf", "LIMIT", 0, num)); err != nil {
log.Error("redis(ZREVRANGEBYSCORE %s,%d) error(%v)", key, num, err)
return
}
return
}
//SetNXLockCache redis lock.
func (d *Dao) SetNXLockCache(c context.Context, k int64) (res bool, err error) {
var (
key = lockKey(k)
conn = d.redis.Get(c)
)
defer conn.Close()
if res, err = redis.Bool(conn.Do("SETNX", key, "1")); err != nil {
if err == redis.ErrNil {
err = nil
} else {
log.Error("conn.Do(SETNX(%d)) error(%v)", key, err)
return
}
}
if res {
if _, err = redis.Bool(conn.Do("EXPIRE", key, d.verifyExpire)); err != nil {
log.Error("conn.Do(EXPIRE, %s, %d) error(%v)", key, d.verifyExpire, err)
return
}
}
return
}
// PingRedis check redis connection
func (d *Dao) PingRedis(c context.Context) (err error) {
conn := d.redis.Get(c)
_, err = conn.Do("SET", "PING", "PONG")
conn.Close()
return
}

View File

@@ -0,0 +1,99 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaokeyWaitBlock(t *testing.T) {
convey.Convey("keyWaitBlock", t, func(ctx convey.C) {
var (
batchNo = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := keyWaitBlock(batchNo)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaolockKey(t *testing.T) {
convey.Convey("lockKey", t, func(ctx convey.C) {
var (
key = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
p1 := lockKey(key)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoAddBlockCache(t *testing.T) {
convey.Convey("AddBlockCache", t, func(ctx convey.C) {
var (
c = context.Background()
mid = int64(0)
score = int8(0)
blockNo = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.AddBlockCache(c, mid, score, blockNo)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoBlockMidCache(t *testing.T) {
convey.Convey("BlockMidCache", t, func(ctx convey.C) {
var (
c = context.Background()
batchNo = int64(0)
num = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
_, err := d.BlockMidCache(c, batchNo, num)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}
func TestDaoSetNXLockCache(t *testing.T) {
convey.Convey("SetNXLockCache", t, func(ctx convey.C) {
var (
c = context.Background()
k = int64(0)
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
res, err := d.SetNXLockCache(c, k)
ctx.Convey("Then err should be nil.res should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(res, convey.ShouldNotBeNil)
})
})
})
}
func TestDaoPingRedis(t *testing.T) {
convey.Convey("PingRedis", t, func(ctx convey.C) {
var (
c = context.Background()
)
ctx.Convey("When everything goes positive", func(ctx convey.C) {
err := d.PingRedis(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
})
}