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,50 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["dao_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/account/api:go_default_library",
"//app/service/main/assist/conf:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/golang/mock/gomock:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/service/main/assist/dao/account",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/account/api:go_default_library",
"//app/service/main/assist/conf:go_default_library",
"//library/ecode:go_default_library",
"//library/log: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,131 @@
package account
import (
"context"
accapi "go-common/app/service/main/account/api"
"go-common/app/service/main/assist/conf"
"go-common/library/ecode"
"go-common/library/log"
)
// Dao is account dao.
type Dao struct {
c *conf.Config
acc accapi.AccountClient
}
// New new a dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
}
var err error
if d.acc, err = accapi.NewClient(c.AccClient); err != nil {
panic(err)
}
return
}
// IsFollow check assist follow up.
func (d *Dao) IsFollow(c context.Context, mid, assistMid int64) (follow bool, err error) {
var arg = &accapi.RelationReq{
Mid: assistMid,
Owner: mid,
}
res, err := d.acc.Relation3(c, arg)
if err != nil {
log.Error("d.acc.Relation2(%d,%d) error(%v)", mid, assistMid, err)
return
}
follow = res.Following
return
}
// IdentifyInfo 获取用户实名认证状态
func (d *Dao) IdentifyInfo(c context.Context, mid int64, ip string) (err error) {
var (
arg = &accapi.MidReq{
Mid: mid,
}
rpcRes *accapi.ProfileReply
mf *accapi.Profile
)
if rpcRes, err = d.acc.Profile3(c, arg); err != nil {
log.Error("d.acc.Profile3 error(%v) | mid(%d) ip(%s) arg(%v)", err, mid, ip, arg)
err = ecode.CreativeAccServiceErr
return
}
if rpcRes != nil {
mf = rpcRes.Profile
}
if mf.Identification == 1 {
return
}
if err = d.switchIDInfoRet(mf.TelStatus); err != nil {
log.Error("switchIDInfoRet res(%v)", mf.TelStatus)
return
}
return
}
func (d *Dao) switchIDInfoRet(phoneRet int32) (err error) {
switch phoneRet {
case 0:
err = ecode.UserCheckNoPhone
case 1:
err = nil
case 2:
err = ecode.UserCheckInvalidPhone
}
return
}
// UserBanned 获取用户封禁状态, disabled when spacesta == 2
func (d *Dao) UserBanned(c context.Context, mid int64) (err error) {
var card *accapi.Card
if card, err = d.Card(c, mid, ""); err != nil {
log.Error("d.Card() error(%v)", err)
err = nil
return
}
if card.Silence == 1 {
err = ecode.UserDisabled
return
}
return
}
// Card get account.
func (d *Dao) Card(c context.Context, mid int64, ip string) (res *accapi.Card, err error) {
var (
rpcRes *accapi.CardReply
arg = &accapi.MidReq{
Mid: mid,
}
)
if rpcRes, err = d.acc.Card3(c, arg); err != nil {
log.Error("s.acc.Card3() error(%v)", err)
err = ecode.CreativeAccServiceErr
}
if rpcRes != nil {
res = rpcRes.Card
}
return
}
// Cards get infos for space
func (d *Dao) Cards(c context.Context, mids []int64) (res map[int64]*accapi.Card, err error) {
var (
arg = &accapi.MidsReq{
Mids: mids,
}
rpcRes *accapi.CardsReply
)
if rpcRes, err = d.acc.Cards3(c, arg); err != nil {
log.Error("s.acc.Cards3() error(%v)", err)
err = ecode.CreativeAccServiceErr
}
if rpcRes != nil {
res = rpcRes.Cards
}
return
}

View File

@@ -0,0 +1,131 @@
package account
import (
"context"
"flag"
accapi "go-common/app/service/main/account/api"
"go-common/app/service/main/assist/conf"
"go-common/library/ecode"
"os"
"testing"
"github.com/golang/mock/gomock"
"github.com/smartystreets/goconvey/convey"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.assist-service")
flag.Set("conf_token", "6e0dae2c95d90ff8d0da53460ef11ae8")
flag.Set("tree_id", "2084")
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/assist-service.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}
func WithMock(t *testing.T, f func(mock *gomock.Controller)) func() {
return func() {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
f(mockCtrl)
}
}
func TestIdentifyInfo(t *testing.T) {
convey.Convey("1", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
err error
)
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.MidReq{
Mid: mid,
}
mock.EXPECT().Profile3(gomock.Any(), mockReq).Return(nil, ecode.CreativeAccServiceErr)
err = d.IdentifyInfo(c, mid, ip)
convey.So(err, convey.ShouldNotBeNil)
}))
convey.Convey("2", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
mid = int64(2089809)
ip = "127.0.0.1"
err error
)
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.MidReq{
Mid: mid,
}
rpcRes := &accapi.ProfileReply{
Profile: &accapi.Profile{
Identification: 0,
TelStatus: 2,
},
}
mock.EXPECT().Profile3(gomock.Any(), mockReq).Return(rpcRes, nil)
err = d.IdentifyInfo(c, mid, ip)
convey.So(err, convey.ShouldNotBeNil)
}))
}
func TestIsFollow(t *testing.T) {
convey.Convey("1", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
mid = int64(2089809)
assistMid = int64(11)
err error
follow bool
)
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.RelationReq{
Mid: assistMid,
Owner: mid,
}
mock.EXPECT().Relation3(gomock.Any(), mockReq).Return(nil, ecode.CreativeAccServiceErr)
follow, err = d.IsFollow(c, mid, assistMid)
convey.So(err, convey.ShouldNotBeNil)
convey.So(follow, convey.ShouldBeFalse)
}))
}
func TestCard(t *testing.T) {
convey.Convey("TestCard", t, WithMock(t, func(mockCtrl *gomock.Controller) {
var (
c = context.Background()
mid = int64(2089809)
err error
res *accapi.Card
)
mock := accapi.NewMockAccountClient(mockCtrl)
d.acc = mock
mockReq := &accapi.MidReq{
Mid: mid,
}
mock.EXPECT().Card3(gomock.Any(), mockReq).Return(nil, ecode.CreativeAccServiceErr)
res, err = d.Card(c, mid, "")
convey.So(err, convey.ShouldNotBeNil)
convey.So(res, convey.ShouldBeNil)
}))
}

View File

@@ -0,0 +1,66 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = [
"assist_redis_test.go",
"assist_test.go",
"dao_test.go",
"log_test.go",
"mc_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/assist/conf:go_default_library",
"//app/service/main/assist/model/assist:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"assist.go",
"assist_redis.go",
"dao.go",
"log.go",
"mc.go",
],
importpath = "go-common/app/service/main/assist/dao/assist",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/assist/conf:go_default_library",
"//app/service/main/assist/model/assist: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/time:go_default_library",
"//library/xstr: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,125 @@
package assist
import (
"context"
"go-common/app/service/main/assist/model/assist"
"go-common/library/database/sql"
"go-common/library/log"
)
const (
// insert
_inAssSQL = "INSERT INTO assist (mid,assist_mid) VALUE (?,?) ON DUPLICATE KEY UPDATE state=0"
// update
_delAssSQL = "UPDATE assist SET state=1 WHERE mid=? AND assist_mid=?"
// select
_assSQL = "SELECT mid,assist_mid,ctime,mtime FROM assist WHERE mid=? AND assist_mid=? AND state=0"
_asssSQL = "SELECT mid,assist_mid,ctime,mtime FROM assist WHERE mid=? AND state=0"
_assCntSQL = "SELECT count(*) FROM assist WHERE mid=? AND state=0"
_assUpsSQL = "SELECT mid, ctime FROM assist WHERE assist_mid=? AND state=0 limit ?,?"
_assUpsCntSQL = "SELECT count(*) as total FROM assist WHERE assist_mid=? AND state=0"
)
// AddAssist add assist
func (d *Dao) AddAssist(c context.Context, mid, assistMid int64) (id int64, err error) {
res, err := d.db.Exec(c, _inAssSQL, mid, assistMid)
if err != nil {
log.Error("d.inAss.Exec error(%v)", err)
return
}
id, err = res.LastInsertId()
return
}
// DelAssist del assist
func (d *Dao) DelAssist(c context.Context, mid, assistMid int64) (row int64, err error) {
res, err := d.db.Exec(c, _delAssSQL, mid, assistMid)
if err != nil {
log.Error("d.delAss.Exec error(%v)", err)
return
}
row, err = res.RowsAffected()
return
}
// Assist get one Assist from assist database.
func (d *Dao) Assist(c context.Context, mid, assistMid int64) (a *assist.Assist, err error) {
row := d.db.QueryRow(c, _assSQL, mid, assistMid)
a = &assist.Assist{}
if err = row.Scan(&a.Mid, &a.AssistMid, &a.CTime, &a.MTime); err != nil {
if err == sql.ErrNoRows {
a = nil
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// Assists get all Assists from assist database.
func (d *Dao) Assists(c context.Context, mid int64) (as []*assist.Assist, err error) {
as = make([]*assist.Assist, 0)
rows, err := d.db.Query(c, _asssSQL, mid)
if err != nil {
log.Error("db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
a := &assist.Assist{}
if err = rows.Scan(&a.Mid, &a.AssistMid, &a.CTime, &a.MTime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
as = append(as, a)
}
return
}
// AssistCnt get assist count.
func (d *Dao) AssistCnt(c context.Context, mid int64) (count int, err error) {
row := d.db.QueryRow(c, _assCntSQL, mid)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
count = 0
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// Ups get ups who already sign me as assist.
func (d *Dao) Ups(c context.Context, assistMid, pn, ps int64) (mids []int64, ups map[int64]*assist.Up, total int64, err error) {
mids = make([]int64, 0)
ups = make(map[int64]*assist.Up, ps)
// default is empty json array
rows, err := d.db.Query(c, _assUpsSQL, assistMid, (pn-1)*ps, pn*ps)
if err != nil {
log.Error("db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
up := &assist.Up{}
if err = rows.Scan(&up.Mid, &up.CTime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
ups[up.Mid] = up
mids = append(mids, up.Mid)
}
row := d.db.QueryRow(c, _assUpsCntSQL, assistMid)
if err = row.Scan(&total); err != nil {
if err == sql.ErrNoRows {
total = 0
err = nil
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}

View File

@@ -0,0 +1,261 @@
package assist
import (
"context"
"go-common/app/service/main/assist/model/assist"
"go-common/library/cache/redis"
"go-common/library/log"
xtime "go-common/library/time"
"strconv"
"time"
)
func (d *Dao) logCountKey(mid, assistMid int64) string {
datetime := time.Now().Format("20060102")
return datetime + strconv.FormatInt(mid, 10) + "_" + strconv.FormatInt(assistMid, 10)
}
func (d *Dao) assTotalKey(mid int64) string {
datetime := time.Now().Format("20060102")
return "ass_" + datetime + "_" + strconv.FormatInt(mid, 10)
}
func (d *Dao) assSameKey(mid int64) string {
datetime := time.Now().Format("20060102")
return "assSame_" + datetime + "_" + strconv.FormatInt(mid, 10)
}
func (d *Dao) assUpKey(assistMid int64) string {
datetime := time.Now().Format("20060102")
return "assUps_" + datetime + "_" + strconv.FormatInt(assistMid, 10)
}
// DailyLogCount get daily count by type
func (d *Dao) DailyLogCount(c context.Context, mid, assistMid, tp int64) (count int64, err error) {
var (
conn = d.redis.Get(c)
key = d.logCountKey(mid, assistMid)
field = strconv.FormatInt(tp, 10)
)
defer conn.Close()
if err = conn.Send("HGET", key, field); err != nil {
log.Error("conn.Send HGET (%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
count, err = redis.Int64(conn.Receive())
if err != nil {
if err == redis.ErrNil {
err = nil
count = 0
log.Info("conn.Receive(HGET, %d) error(%v)", mid, err)
} else {
log.Error("conn.Receive(HGET, %d) error(%v)", mid, err)
}
return
}
return
}
// IncrLogCount incr daily count
func (d *Dao) IncrLogCount(c context.Context, mid, assistMid, tp int64) (err error) {
var (
conn = d.redis.Get(c)
key = d.logCountKey(mid, assistMid)
field = strconv.FormatInt(tp, 10)
)
defer conn.Close()
_ = conn.Send("EXPIRE", key, d.redisExpire)
if err = conn.Send("HINCRBY", key, field, 1); err != nil {
log.Error("conn.Send HINCRBY (%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
return
}
// TotalAssCnt get daily total add count
func (d *Dao) TotalAssCnt(c context.Context, mid int64) (count int64, err error) {
var (
conn = d.redis.Get(c)
key = d.assTotalKey(mid)
field = strconv.FormatInt(mid, 10)
)
defer conn.Close()
if err = conn.Send("HGET", key, field); err != nil {
log.Error("conn.Send HGET (%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
count, err = redis.Int64(conn.Receive())
if err != nil {
if err == redis.ErrNil {
err = nil
count = 0
log.Info("conn.Receive(HGET, %d) error(%v)", mid, err)
} else {
log.Error("conn.Receive(HGET, %d) error(%v)", mid, err)
}
return
}
return
}
// SameAssCnt get add same user count
func (d *Dao) SameAssCnt(c context.Context, mid, assistMid int64) (count int64, err error) {
var (
conn = d.redis.Get(c)
key = d.assSameKey(mid)
field = strconv.FormatInt(assistMid, 10)
)
defer conn.Close()
if err = conn.Send("HGET", key, field); err != nil {
log.Error("conn.Send HGET (%s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
count, err = redis.Int64(conn.Receive())
if err != nil {
if err == redis.ErrNil {
err = nil
count = 0
log.Info("conn.Receive(HGET, %d) error(%v)", mid, err)
} else {
log.Error("conn.Receive(HGET, %d) error(%v)", mid, err)
}
return
}
return
}
// IncrAssCnt called when assis added, incr both same and total count
func (d *Dao) IncrAssCnt(c context.Context, mid, assistMid int64) (err error) {
var (
conn = d.redis.Get(c)
keyAll = d.assTotalKey(mid)
fieldAll = strconv.FormatInt(mid, 10)
keySame = d.assSameKey(mid)
fieldSame = strconv.FormatInt(assistMid, 10)
)
defer conn.Close()
_ = conn.Send("EXPIRE", keyAll, d.redisExpire)
if err = conn.Send("HINCRBY", keyAll, fieldAll, 1); err != nil {
log.Error("conn.Send HINCRBY (%s) error(%v)", keyAll, err)
return
}
_ = conn.Send("EXPIRE", keySame, d.redisExpire)
if err = conn.Send("HINCRBY", keySame, fieldSame, 1); err != nil {
log.Error("conn.Send HINCRBY (%s) error(%v)", keySame, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
return
}
// DelAssUpAllCache del AssUpAllCache when delete assist relation
func (d *Dao) DelAssUpAllCache(c context.Context, assistMid int64) (err error) {
var (
key = d.assUpKey(assistMid)
conn = d.redis.Get(c)
)
defer conn.Close()
if _, err = conn.Do("DEL", key); err != nil {
log.Error("conn.Do(ZERM, %s, %d) error(%v)", key, assistMid, err)
return
}
return
}
// AddAssUpAllCache add AssUpAllCache when add assist relation
func (d *Dao) AddAssUpAllCache(c context.Context, assistMid int64, ups map[int64]*assist.Up) (err error) {
var (
key = d.assUpKey(assistMid)
conn = d.redis.Get(c)
)
defer conn.Close()
for _, up := range ups {
if err = conn.Send("ZADD", key, up.CTime, up.Mid); err != nil {
log.Error("conn.Send(ZADD, %s, %v, %d) error(%v)", key, up.CTime, up.Mid, err)
return
}
}
if err = conn.Send("EXPIRE", key, -1); err != nil {
log.Error("conn.Send(Expire, %s, %d) error(%v)", key, 0, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
for i := 0; i < len(ups); i++ {
if _, err = conn.Receive(); err != nil {
log.Error("conn.Receive error(%v)", err)
return
}
}
return
}
// AssUpCacheWithScore get uppers passed mids from cache with scores
func (d *Dao) AssUpCacheWithScore(c context.Context, assistMid int64, start, end int64) (mids []int64, ups map[int64]*assist.Up, total int64, err error) {
conn := d.redis.Get(c)
defer conn.Close()
ups = make(map[int64]*assist.Up, end-start)
key := d.assUpKey(assistMid)
if err = conn.Send("ZREVRANGE", key, start, end, "WITHSCORES"); err != nil {
log.Error("conn.Send(ZREVRANGE, %s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
upsWithScore, err := redis.Int64s(conn.Receive())
if err != nil {
log.Error("conn.Do(GET, %d, %d, %d) error(%v)", assistMid, start, end, err)
}
for i := 0; i < len(upsWithScore); i += 2 {
mids = append(mids, upsWithScore[i])
var t xtime.Time
t.Scan(strconv.FormatInt(upsWithScore[i+1], 10))
up := &assist.Up{
Mid: upsWithScore[i],
CTime: t,
}
ups[upsWithScore[i]] = up
}
if err = conn.Send("ZLEXCOUNT", key, "-", "+"); err != nil {
log.Error("conn.Send(ZLEXCOUNT, %s) error(%v)", key, err)
return
}
if err = conn.Flush(); err != nil {
log.Error("conn.Flush error(%v)", err)
return
}
total, err = redis.Int64(conn.Receive())
if err != nil {
if err == redis.ErrNil {
err = nil
log.Info("conn.Receive(ZLEXCOUNT, %d) error(%v)", assistMid, err)
} else {
log.Error("conn.Receive(ZLEXCOUNT, %d) error(%v)", assistMid, err)
}
return
}
return
}

View File

@@ -0,0 +1,174 @@
package assist
import (
"context"
"go-common/app/service/main/assist/model/assist"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAssistlogCountKey(t *testing.T) {
var (
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("logCountKey", t, func(ctx convey.C) {
p1 := d.logCountKey(mid, assistMid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAssistassTotalKey(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("assTotalKey", t, func(ctx convey.C) {
p1 := d.assTotalKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAssistassSameKey(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("assSameKey", t, func(ctx convey.C) {
p1 := d.assSameKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAssistassUpKey(t *testing.T) {
var (
assistMid = int64(0)
)
convey.Convey("assUpKey", t, func(ctx convey.C) {
p1 := d.assUpKey(assistMid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAssistDailyLogCount(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
tp = int64(0)
)
convey.Convey("DailyLogCount", t, func(ctx convey.C) {
count, err := d.DailyLogCount(c, mid, assistMid, tp)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistIncrLogCount(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
tp = int64(0)
)
convey.Convey("IncrLogCount", t, func(ctx convey.C) {
err := d.IncrLogCount(c, mid, assistMid, tp)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistTotalAssCnt(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("TotalAssCnt", t, func(ctx convey.C) {
count, err := d.TotalAssCnt(c, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistSameAssCnt(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("SameAssCnt", t, func(ctx convey.C) {
count, err := d.SameAssCnt(c, mid, assistMid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistIncrAssCnt(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("IncrAssCnt", t, func(ctx convey.C) {
err := d.IncrAssCnt(c, mid, assistMid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistDelAssUpAllCache(t *testing.T) {
var (
c = context.Background()
assistMid = int64(0)
)
convey.Convey("DelAssUpAllCache", t, func(ctx convey.C) {
err := d.DelAssUpAllCache(c, assistMid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistAddAssUpAllCache(t *testing.T) {
var (
c = context.Background()
assistMid = int64(0)
ups map[int64]*assist.Up
)
convey.Convey("AddAssUpAllCache", t, func(ctx convey.C) {
err := d.AddAssUpAllCache(c, assistMid, ups)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistAssUpCacheWithScore(t *testing.T) {
var (
c = context.Background()
assistMid = int64(0)
start = int64(0)
end = int64(0)
)
convey.Convey("AssUpCacheWithScore", t, func(ctx convey.C) {
_, _, _, err := d.AssUpCacheWithScore(c, assistMid, start, end)
ctx.Convey("Then err should be nil.mids,ups,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,99 @@
package assist
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAssistAddAssist(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("AddAssist", t, func(ctx convey.C) {
id, err := d.AddAssist(c, mid, assistMid)
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 TestAssistDelAssist(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("DelAssist", t, func(ctx convey.C) {
row, err := d.DelAssist(c, mid, assistMid)
ctx.Convey("Then err should be nil.row should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(row, convey.ShouldNotBeNil)
})
})
}
func TestAssistAssist(t *testing.T) {
var (
c = context.Background()
mid = int64(27515409)
assistMid = int64(27515235)
err error
)
convey.Convey("Assist", t, func(ctx convey.C) {
_, err = d.Assist(c, mid, assistMid)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistAssists(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("Assists", t, func(ctx convey.C) {
as, err := d.Assists(c, mid)
ctx.Convey("Then err should be nil.as should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(as, convey.ShouldNotBeNil)
})
})
}
func TestAssistAssistCnt(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("AssistCnt", t, func(ctx convey.C) {
count, err := d.AssistCnt(c, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistUps(t *testing.T) {
var (
c = context.Background()
assistMid = int64(0)
pn = int64(0)
ps = int64(0)
)
convey.Convey("Ups", t, func(ctx convey.C) {
mids, ups, total, err := d.Ups(c, assistMid, pn, ps)
ctx.Convey("Then err should be nil.mids,ups,total should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(total, convey.ShouldNotBeNil)
ctx.So(ups, convey.ShouldNotBeNil)
ctx.So(mids, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,64 @@
package assist
import (
"context"
"time"
"go-common/app/service/main/assist/conf"
"go-common/library/cache/memcache"
"go-common/library/cache/redis"
"go-common/library/database/sql"
)
// Dao is assist dao.
type Dao struct {
// config
c *conf.Config
// db
db *sql.DB
// mc
mc *memcache.Pool
mcSubExp int32
// redis
redis *redis.Pool
redisExpire int32
}
// New init api url
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
db: sql.NewMySQL(c.DB.Assist),
mc: memcache.NewPool(c.Memcache.Assist.Config),
mcSubExp: int32(time.Duration(c.Memcache.Assist.SubmitExpire) / time.Second),
// redis
redis: redis.NewPool(c.Redis.Assist.Config),
redisExpire: int32(time.Duration(c.Redis.Assist.Expire) / time.Second),
}
return
}
// Ping include db, mc, redis
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.db.Ping(c); err != nil {
return
}
if err = d.pingMemcache(c); err != nil {
return
}
return
}
// Close include db, mc, redis
func (d *Dao) Close() (err error) {
if d.db != nil {
d.db.Close()
}
if d.mc != nil {
d.mc.Close()
}
if d.redis != nil {
d.redis.Close()
}
return
}

View File

@@ -0,0 +1,35 @@
package assist
import (
"flag"
"go-common/app/service/main/assist/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.assist-service")
flag.Set("conf_token", "6e0dae2c95d90ff8d0da53460ef11ae8")
flag.Set("tree_id", "2084")
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/assist-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,293 @@
package assist
import (
"context"
"database/sql"
"fmt"
"time"
"go-common/app/service/main/assist/model/assist"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/xstr"
)
const (
// insert
_inLogSQL = "INSERT IGNORE INTO assist_log (mid,assist_mid,type,action,subject_id,object_id,detail) VALUES (?,?,?,?,?,?,?)"
// update
_cancelLogSQL = "UPDATE assist_log SET state=1 WHERE id=? AND mid=? AND assist_mid=?"
// info
_logInfoSQL = "SELECT id,mid,assist_mid,type,action,subject_id,object_id,detail,state,ctime,mtime FROM assist_log WHERE id=? AND mid=? AND assist_mid=?"
// obj
_logObjSQL = "SELECT id,mid,assist_mid,type,action,subject_id,object_id,detail,state,ctime,mtime FROM assist_log WHERE mid=? AND object_id=? AND type=? AND action=? limit 1"
// select
_logsSQL = "SELECT id,mid,assist_mid,type,action,subject_id,object_id,detail,state,ctime,mtime FROM assist_log WHERE mid=? ORDER BY id DESC LIMIT ?,?"
_logsByAssSQL = "SELECT id,mid,assist_mid,type,action,subject_id,object_id,detail,state,ctime,mtime FROM assist_log WHERE mid=? AND assist_mid=? ORDER BY id DESC LIMIT ?,?"
_logsByCtimeSQL = "SELECT id,mid,assist_mid,type,action,subject_id,object_id,detail,state,ctime,mtime FROM assist_log WHERE mid=? AND ctime>=? AND ctime<=? ORDER BY id DESC LIMIT ?,?"
_logsByAssCtimeSQL = "SELECT id,mid,assist_mid,type,action,subject_id,object_id,detail,state,ctime,mtime FROM assist_log WHERE mid=? AND assist_mid=? AND ctime>=? AND ctime<=? ORDER BY id DESC LIMIT ?,?"
_logCntGroupBySQL = "SELECT assist_mid,type,action,count(*) FROM assist_log WHERE mid=? GROUP BY assist_mid,type,action"
_logAssMidCntGroupBySQL = "SELECT assist_mid,type,action,count(*) FROM assist_log WHERE mid=%d and assist_mid IN (%s) GROUP BY assist_mid,type,action"
// LogCntBy*SQL
_logCntSQL = "SELECT count(*) FROM assist_log WHERE mid=?"
_logCntByAssSQL = "SELECT count(*) FROM assist_log WHERE mid=? AND assist_mid=?"
_logCntByCtimeSQL = "SELECT count(*) FROM assist_log WHERE mid=? AND ctime>=? AND ctime<=?"
_logCntByAssCtimeSQL = "SELECT count(*) FROM assist_log WHERE mid=? AND assist_mid=? AND ctime>=? AND ctime<=?"
)
// AddLog add one assist log.
func (d *Dao) AddLog(c context.Context, mid, assistMid, tp, act, subID int64, objIDStr string, detail string) (id int64, err error) {
res, err := d.db.Exec(c, _inLogSQL, mid, assistMid, tp, act, subID, objIDStr, detail)
if err != nil {
log.Error("d.inLog error(%v)|(%d,%d,%d,%d,%d,%s,%d)", err, mid, assistMid, tp, act, subID, objIDStr, detail)
return
}
id, err = res.LastInsertId()
return
}
// CancelLog cancel assist oper log.
func (d *Dao) CancelLog(c context.Context, logID, mid, assistMid int64) (rows int64, err error) {
res, err := d.db.Exec(c, _cancelLogSQL, logID, mid, assistMid)
if err != nil {
log.Error("d.db.Exec error(%v)", err)
return
}
rows, err = res.RowsAffected()
return
}
// LogInfo log Info
func (d *Dao) LogInfo(c context.Context, id, mid, assistMid int64) (a *assist.Log, err error) {
row := d.db.QueryRow(c, _logInfoSQL, id, mid, assistMid)
a = &assist.Log{}
if err = row.Scan(&a.ID, &a.Mid, &a.AssistMid, &a.Type, &a.Action, &a.SubjectID, &a.ObjectID, &a.Detail, &a.State, &a.CTime, &a.MTime); err != nil {
if err == sql.ErrNoRows {
a = nil
err = ecode.AssistLogNotExist
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// Logs get logs from assist db.
func (d *Dao) Logs(c context.Context, mid int64, start, offset int) (logs []*assist.Log, err error) {
logs = make([]*assist.Log, 0)
rows, err := d.db.Query(c, _logsSQL, mid, start, offset)
if err != nil {
log.Error("db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
lg := &assist.Log{}
if err = rows.Scan(&lg.ID, &lg.Mid, &lg.AssistMid, &lg.Type, &lg.Action, &lg.SubjectID, &lg.ObjectID, &lg.Detail, &lg.State, &lg.CTime, &lg.MTime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
logs = append(logs, lg)
}
return
}
// LogsByAssist get logs from assist db by assist mid.
func (d *Dao) LogsByAssist(c context.Context, mid, assistMid int64, start, offset int) (logs []*assist.Log, err error) {
logs = make([]*assist.Log, 0)
rows, err := d.db.Query(c, _logsByAssSQL, mid, assistMid, start, offset)
if err != nil {
log.Error("db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
lg := &assist.Log{}
if err = rows.Scan(&lg.ID, &lg.Mid, &lg.AssistMid, &lg.Type, &lg.Action, &lg.SubjectID, &lg.ObjectID, &lg.Detail, &lg.State, &lg.CTime, &lg.MTime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
logs = append(logs, lg)
}
return
}
// LogsByCtime get logs from assist db by ctime.
func (d *Dao) LogsByCtime(c context.Context, mid int64, stime, etime time.Time, start, offset int) (logs []*assist.Log, err error) {
logs = make([]*assist.Log, 0)
rows, err := d.db.Query(c, _logsByCtimeSQL, mid, stime, etime, start, offset)
if err != nil {
log.Error("db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
lg := &assist.Log{}
if err = rows.Scan(&lg.ID, &lg.Mid, &lg.AssistMid, &lg.Type, &lg.Action, &lg.SubjectID, &lg.ObjectID, &lg.Detail, &lg.State, &lg.CTime, &lg.MTime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
logs = append(logs, lg)
}
return
}
// LogsByAssistCtime get logs from assist db by assist oper ctime.
func (d *Dao) LogsByAssistCtime(c context.Context, mid, assistMid int64, stime, etime time.Time, start, offset int) (logs []*assist.Log, err error) {
logs = make([]*assist.Log, 0)
rows, err := d.db.Query(c, _logsByAssCtimeSQL, mid, assistMid, stime, etime, start, offset)
if err != nil {
log.Error("db.Query error(%v)", err)
return
}
defer rows.Close()
for rows.Next() {
lg := &assist.Log{}
if err = rows.Scan(&lg.ID, &lg.Mid, &lg.AssistMid, &lg.Type, &lg.Action, &lg.SubjectID, &lg.ObjectID, &lg.Detail, &lg.State, &lg.CTime, &lg.MTime); err != nil {
log.Error("row.Scan error(%v)", err)
return
}
logs = append(logs, lg)
}
return
}
// LogCount count by group from db.
func (d *Dao) LogCount(c context.Context, mid int64) (totalm map[int64]map[int8]map[int8]int, err error) {
rows, err := d.db.Query(c, _logCntGroupBySQL, mid)
if err != nil {
log.Error("db.Query err(%v)", err)
return
}
defer rows.Close()
totalm = map[int64]map[int8]map[int8]int{}
for rows.Next() {
var (
assMid int64
tp, act int8
cnt int
)
if err = rows.Scan(&assMid, &tp, &act, &cnt); err != nil {
log.Error("row.Scan err(%v)", err)
return
}
if tassMap, ok := totalm[assMid]; !ok {
totalm[assMid] = map[int8]map[int8]int{
tp: {act: cnt},
}
} else {
if tpMap, ok := tassMap[tp]; !ok {
tassMap[tp] = map[int8]int{act: cnt}
} else {
tpMap[act] = cnt
}
}
}
return
}
// LogCnt fn
func (d *Dao) LogCnt(c context.Context, mid int64) (count int64, err error) {
row := d.db.QueryRow(c, _logCntSQL, mid)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
count = 0
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// LogCntAssist fn
func (d *Dao) LogCntAssist(c context.Context, mid, assistMid int64) (count int64, err error) {
row := d.db.QueryRow(c, _logCntByAssSQL, mid, assistMid)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
count = 0
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// LogCntCtime fn
func (d *Dao) LogCntCtime(c context.Context, mid int64, stime, etime time.Time) (count int64, err error) {
row := d.db.QueryRow(c, _logCntByCtimeSQL, mid, stime, etime)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
count = 0
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// LogCntAssistCtime fn
func (d *Dao) LogCntAssistCtime(c context.Context, mid, assistMid int64, stime, etime time.Time) (count int64, err error) {
row := d.db.QueryRow(c, _logCntByAssCtimeSQL, mid, assistMid, stime, etime)
if err = row.Scan(&count); err != nil {
if err == sql.ErrNoRows {
err = nil
count = 0
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}
// AssistsMidsTotal get all Assists from assist database.
func (d *Dao) AssistsMidsTotal(c context.Context, mid int64, assmids []int64) (totalm map[int64]map[int8]map[int8]int, err error) {
query := fmt.Sprintf(_logAssMidCntGroupBySQL, mid, xstr.JoinInts(assmids))
rows, err := d.db.Query(c, query)
if err != nil {
log.Error("db.Query err(%v)", err)
return
}
defer rows.Close()
totalm = map[int64]map[int8]map[int8]int{}
for rows.Next() {
var (
assMid int64
tp, act int8
cnt int
)
if err = rows.Scan(&assMid, &tp, &act, &cnt); err != nil {
log.Error("row.Scan err(%v)", err)
return
}
if tassMap, ok := totalm[assMid]; !ok {
totalm[assMid] = map[int8]map[int8]int{
tp: {act: cnt},
}
} else {
if tpMap, ok := tassMap[tp]; !ok {
tassMap[tp] = map[int8]int{act: cnt}
} else {
tpMap[act] = cnt
}
}
}
return
}
// LogObj log Obj
func (d *Dao) LogObj(c context.Context, mid, objID, tp, act int64) (a *assist.Log, err error) {
row := d.db.QueryRow(c, _logObjSQL, mid, objID, tp, act)
a = &assist.Log{}
if err = row.Scan(&a.ID, &a.Mid, &a.AssistMid, &a.Type, &a.Action, &a.SubjectID, &a.ObjectID, &a.Detail, &a.State, &a.CTime, &a.MTime); err != nil {
if err == sql.ErrNoRows {
a = nil
err = ecode.AssistLogNotExist
} else {
log.Error("row.Scan error(%v)", err)
}
}
return
}

View File

@@ -0,0 +1,240 @@
package assist
import (
"context"
"go-common/library/ecode"
"testing"
"time"
"github.com/smartystreets/goconvey/convey"
)
func TestAssistAddLog(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
tp = int64(0)
act = int64(0)
subID = int64(0)
objIDStr = ""
detail = ""
)
convey.Convey("AddLog", t, func(ctx convey.C) {
id, err := d.AddLog(c, mid, assistMid, tp, act, subID, objIDStr, detail)
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 TestAssistCancelLog(t *testing.T) {
var (
c = context.Background()
logID = int64(0)
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("CancelLog", t, func(ctx convey.C) {
rows, err := d.CancelLog(c, logID, mid, assistMid)
ctx.Convey("Then err should be nil.rows should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(rows, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogInfo(t *testing.T) {
var (
c = context.Background()
id = int64(1)
mid = int64(27515256)
assistMid = int64(27515243)
)
convey.Convey("LogInfo", t, func(ctx convey.C) {
a, err := d.LogInfo(c, id, mid, assistMid)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldNotBeNil)
ctx.So(err, convey.ShouldEqual, ecode.AssistLogNotExist)
ctx.So(a, convey.ShouldBeNil)
})
})
}
func TestAssistLogs(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
start = int(0)
offset = int(0)
)
convey.Convey("Logs", t, func(ctx convey.C) {
logs, err := d.Logs(c, mid, start, offset)
ctx.Convey("Then err should be nil.logs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(logs, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogsByAssist(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
start = int(0)
offset = int(0)
)
convey.Convey("LogsByAssist", t, func(ctx convey.C) {
logs, err := d.LogsByAssist(c, mid, assistMid, start, offset)
ctx.Convey("Then err should be nil.logs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(logs, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogsByCtime(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
stime = time.Now()
etime = time.Now()
start = int(0)
offset = int(0)
)
convey.Convey("LogsByCtime", t, func(ctx convey.C) {
logs, err := d.LogsByCtime(c, mid, stime, etime, start, offset)
ctx.Convey("Then err should be nil.logs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(logs, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogsByAssistCtime(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
stime = time.Now()
etime = time.Now()
start = int(0)
offset = int(0)
)
convey.Convey("LogsByAssistCtime", t, func(ctx convey.C) {
logs, err := d.LogsByAssistCtime(c, mid, assistMid, stime, etime, start, offset)
ctx.Convey("Then err should be nil.logs should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(logs, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogCount(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("LogCount", t, func(ctx convey.C) {
totalm, err := d.LogCount(c, mid)
ctx.Convey("Then err should be nil.totalm should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(totalm, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogCnt(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("LogCnt", t, func(ctx convey.C) {
count, err := d.LogCnt(c, mid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogCntAssist(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
)
convey.Convey("LogCntAssist", t, func(ctx convey.C) {
count, err := d.LogCntAssist(c, mid, assistMid)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogCntCtime(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
stime = time.Now()
etime = time.Now()
)
convey.Convey("LogCntCtime", t, func(ctx convey.C) {
count, err := d.LogCntCtime(c, mid, stime, etime)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistLogCntAssistCtime(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMid = int64(0)
stime = time.Now()
etime = time.Now()
)
convey.Convey("LogCntAssistCtime", t, func(ctx convey.C) {
count, err := d.LogCntAssistCtime(c, mid, assistMid, stime, etime)
ctx.Convey("Then err should be nil.count should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(count, convey.ShouldNotBeNil)
})
})
}
func TestAssistAssistsMidsTotal(t *testing.T) {
var (
c = context.Background()
mid = int64(27515409)
assmids = []int64{27515235, 27515233}
)
convey.Convey("AssistsMidsTotal", t, func(ctx convey.C) {
_, err := d.AssistsMidsTotal(c, mid, assmids)
ctx.Convey("Then err should be nil.totalm should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistLogObj(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
objID = int64(0)
tp = int64(0)
act = int64(0)
)
convey.Convey("LogObj", t, func(ctx convey.C) {
a, err := d.LogObj(c, mid, objID, tp, act)
ctx.Convey("Then err should be nil.a should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(a, convey.ShouldNotBeNil)
})
})
}

View File

@@ -0,0 +1,75 @@
package assist
import (
"context"
"go-common/library/cache/memcache"
"go-common/library/log"
"strconv"
)
func assistKey(mid int64) string {
return "assist_relation_mid_" + strconv.FormatInt(mid, 10)
}
// SetCacheAss fn
func (d *Dao) SetCacheAss(c context.Context, mid int64, assistMids []int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := assistKey(mid)
if err = conn.Set(&memcache.Item{Key: key, Object: assistMids, Flags: memcache.FlagJSON, Expiration: 0}); err != nil {
log.Error("conn.Store error(%v) | key(%s) mid(%d) assistMids(%s)", err, key, mid, assistMids)
}
conn.Close()
return
}
// GetCacheAss GetCacheAss
func (d *Dao) GetCacheAss(c context.Context, mid int64) (assistMids []int64, err error) {
var (
key = assistKey(mid)
rp *memcache.Item
conn = d.mc.Get(c)
)
defer conn.Close()
rp, err = conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
log.Info("memcache.Get(%s) ErrNotFound(%v)", key, err)
err = nil
} else {
log.Error("conn.Get error(%v) | key(%s)", err, key)
}
return
}
if err = conn.Scan(rp, &assistMids); err != nil {
log.Error("json.Unmarshal(%s) error(%v)", rp.Value, err)
assistMids = nil
}
return
}
// DelCacheAss fn
func (d *Dao) DelCacheAss(c context.Context, mid int64) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
key := assistKey(mid)
if err = conn.Delete(key); err != nil {
if err == memcache.ErrNotFound {
log.Warn("DelCacheAss memcache.ErrNotFound key(%s)|(%+v)", key, err)
err = nil
} else {
log.Error("DelCacheAss key(%s)|err(%+v)", key, err)
}
}
return
}
func (d *Dao) pingMemcache(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Set(&memcache.Item{Key: "ping", Value: []byte("pong"), Expiration: 0}); err != nil {
log.Error("mc.ping.Store error(%v)", err)
return
}
return
}

View File

@@ -0,0 +1,73 @@
package assist
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestAssistassistKey(t *testing.T) {
var (
mid = int64(0)
)
convey.Convey("assistKey", t, func(ctx convey.C) {
p1 := assistKey(mid)
ctx.Convey("Then p1 should not be nil.", func(ctx convey.C) {
ctx.So(p1, convey.ShouldNotBeNil)
})
})
}
func TestAssistSetCacheAss(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
assistMids = []int64{}
)
convey.Convey("SetCacheAss", t, func(ctx convey.C) {
err := d.SetCacheAss(c, mid, assistMids)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistGetCacheAss(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("GetCacheAss", t, func(ctx convey.C) {
assistMids, err := d.GetCacheAss(c, mid)
ctx.Convey("Then err should be nil.assistMids should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
ctx.So(assistMids, convey.ShouldNotBeNil)
})
})
}
func TestAssistDelCacheAss(t *testing.T) {
var (
c = context.Background()
mid = int64(0)
)
convey.Convey("DelCacheAss", t, func(ctx convey.C) {
err := d.DelCacheAss(c, mid)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestAssistpingMemcache(t *testing.T) {
var (
c = context.Background()
)
convey.Convey("pingMemcache", t, func(ctx convey.C) {
err := d.pingMemcache(c)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,43 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["dao_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = ["//app/service/main/assist/conf:go_default_library"],
)
go_library(
name = "go_default_library",
srcs = ["dao.go"],
importpath = "go-common/app/service/main/assist/dao/message",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/assist/conf:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster: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,57 @@
package message
import (
"context"
"fmt"
"go-common/app/service/main/assist/conf"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"net/url"
"strconv"
)
const (
_messageURI = "/api/notify/send.user.notify.do"
)
// Dao is message dao.
type Dao struct {
c *conf.Config
client *bm.Client
uri string
}
// New new a message dao.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
client: bm.NewClient(c.HTTPClient.Slow),
uri: c.Host.Message + _messageURI,
}
return d
}
// Send send message form uper to assistMid.
func (d *Dao) Send(c context.Context, mc, title, msg string, mid int64) (err error) {
params := url.Values{}
params.Set("type", "json")
params.Set("source", "1")
params.Set("data_type", "4")
params.Set("mc", mc)
params.Set("title", title)
params.Set("context", msg)
params.Set("mid_list", strconv.FormatInt(mid, 10))
var res struct {
Code int `json:"code"`
}
if err = d.client.Post(c, d.uri, "", params, &res); err != nil {
log.Error("message url(%s) error(%v)", d.uri+"?"+params.Encode(), err)
return
}
log.Info("SendSysNotify url: (%s)", d.uri+"?"+params.Encode())
if res.Code != 0 {
log.Error("message url(%s) error(%v)", d.uri+"?"+params.Encode(), res.Code)
err = fmt.Errorf("message send failed")
}
return
}

View File

@@ -0,0 +1,35 @@
package message
import (
"flag"
"go-common/app/service/main/assist/conf"
"os"
"testing"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "" {
flag.Set("app_id", "main.archive.assist-service")
flag.Set("conf_token", "6e0dae2c95d90ff8d0da53460ef11ae8")
flag.Set("tree_id", "2084")
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/assist-service.toml")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
m.Run()
os.Exit(0)
}