Initial commit

This commit is contained in:
Donny
2019-04-22 20:46:32 +08:00
commit 49ab8aadd1
25441 changed files with 4055000 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
package(default_visibility = ["//visibility:public"])
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/service/main/identify-game/api/grpc/v1:all-srcs",
"//app/service/main/identify-game/cmd:all-srcs",
"//app/service/main/identify-game/conf:all-srcs",
"//app/service/main/identify-game/dao:all-srcs",
"//app/service/main/identify-game/model:all-srcs",
"//app/service/main/identify-game/rpc/client:all-srcs",
"//app/service/main/identify-game/rpc/server:all-srcs",
"//app/service/main/identify-game/server/grpc:all-srcs",
"//app/service/main/identify-game/server/http:all-srcs",
"//app/service/main/identify-game/service:all-srcs",
],
tags = ["automanaged"],
)

View File

@@ -0,0 +1,27 @@
### identify game
### Version 1.6.0
> 1.add grpc
> 2.增加通过token生成cookie接口
#### Version 1.5.2
> 1.add ut
#### Version 1.4.0
> 1.use bm start()
> 2.use meatadata instead of bm context remote ip
#### Version 1.3.0
> 1.use bm
> 1.move to main
#### Version 1.2.0
> 1.增加register接口
#### Version 1.1.0
> 1.add dispatcher error prom stats
> 2.change conf dispatcher.renew to dispatcher.renewToken
#### Version 1.0.0
> 1.提供根据accesskey自动路由请求后端服务
> 2.为回源的token设置缓存

View File

@@ -0,0 +1,11 @@
# Owner
wanghuan01
# Author
wanghuan01
# Reviewer
wanghuan01
wucongyou
wutao
linmiao

View File

@@ -0,0 +1,15 @@
# See the OWNERS docs at https://go.k8s.io/owners
approvers:
- wanghuan01
labels:
- main
- service
- service/main/identify-game
options:
no_parent_owners: true
reviewers:
- linmiao
- wanghuan01
- wucongyou
- wutao

View File

@@ -0,0 +1,9 @@
#### identify-game-service
`identify-game-service`主要是为游戏提供鉴权接口
* 根据accesskey判断请求路由
##### 依赖环境
Go 1.8.0或更高版本
##### API文档
TODO example code api

View File

@@ -0,0 +1,69 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
proto_library(
name = "v1_proto",
srcs = ["api.proto"],
tags = ["automanaged"],
deps = ["@gogo_special_proto//github.com/gogo/protobuf/gogoproto"],
)
go_proto_library(
name = "v1_go_proto",
compilers = ["@io_bazel_rules_go//proto:gogofast_grpc"],
importpath = "go-common/app/service/main/identify-game/api/grpc/v1",
proto = ":v1_proto",
tags = ["automanaged"],
deps = ["@com_github_gogo_protobuf//gogoproto:go_default_library"],
)
go_test(
name = "go_default_test",
srcs = ["client_test.go"],
embed = [":go_default_library"],
tags = ["automanaged"],
deps = [
"//library/net/rpc/warden:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["client.go"],
embed = [":v1_go_proto"],
importpath = "go-common/app/service/main/identify-game/api/grpc/v1",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//library/net/rpc/warden:go_default_library",
"@com_github_gogo_protobuf//gogoproto:go_default_library",
"@com_github_gogo_protobuf//proto:go_default_library",
"@org_golang_google_grpc//:go_default_library",
"@org_golang_x_net//context: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"],
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
syntax = "proto3";
package main.service.identify.game.v1;
option go_package = "v1";
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
// DelCacheReq request param for rpc DelCache
message DelCacheReq {
string token = 1;
}
// DelCacheReply del cache reply
message DelCacheReply {
}
//
service IdentifyGame {
// CookieInfo identify info by cookie.
rpc DelCache (DelCacheReq) returns (DelCacheReply);
rpc GetCookieByToken(CreateCookieReq) returns (CreateCookieReply);
}
message CreateCookieReq {
string Token = 1 [(gogoproto.jsontag) = "token",(gogoproto.moretags) = "form:\"access_key\" validate:\"required\""];
string From = 2 [(gogoproto.jsontag) = "from",(gogoproto.moretags) = "form:\"from\""];
}
message CreateCookieReply {
CookieInfo BiliCookies = 1 [(gogoproto.jsontag) = "cookie_info"];
repeated string SSO = 2 [(gogoproto.jsontag) = "sso"];
}
message CookieInfo{
repeated Cookie Cookies = 1 [(gogoproto.jsontag) = "cookies"];
repeated string Domains = 2 [(gogoproto.jsontag) = "domains"];
}
message Cookie{
string Name = 1 [(gogoproto.jsontag) = "name"];
string Value = 2 [(gogoproto.jsontag) = "value"];
int64 HttpOnly = 3 [(gogoproto.jsontag) = "http_only"];
int64 Expires = 4 [(gogoproto.jsontag) = "expires"];
}

View File

@@ -0,0 +1,22 @@
package v1
import (
"context"
"go-common/library/net/rpc/warden"
"google.golang.org/grpc"
)
// AppID unique app id for service discovery
const AppID = "identify.service.game"
// NewClient new identify grpc client
func NewClient(cfg *warden.ClientConfig, opts ...grpc.DialOption) (IdentifyGameClient, error) {
client := warden.NewClient(cfg, opts...)
conn, err := client.Dial(context.Background(), "discovery://default/"+AppID)
if err != nil {
return nil, err
}
return NewIdentifyGameClient(conn), nil
}

View File

@@ -0,0 +1,31 @@
package v1
import (
"context"
"testing"
"go-common/library/net/rpc/warden"
. "github.com/smartystreets/goconvey/convey"
)
func TestClients_Post(t *testing.T) {
var (
ctx = context.Background()
err error
res *DelCacheReply
cookies *CreateCookieReply
)
Convey("test delete cache", t, func() {
client, _ := NewClient(&warden.ClientConfig{})
res, err = client.DelCache(ctx, &DelCacheReq{Token: "24325defrf"})
So(err, ShouldBeNil)
So(res, ShouldNotBeNil)
})
Convey("test get cookie by token", t, func() {
client, _ := NewClient(&warden.ClientConfig{})
cookies, err = client.GetCookieByToken(ctx, &CreateCookieReq{Token: "24325defrf"})
So(err, ShouldNotBeNil)
So(cookies, ShouldBeNil)
})
}

View File

@@ -0,0 +1,43 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_binary",
)
go_library(
name = "go_default_library",
srcs = ["main.go"],
data = ["identify-game-service.toml"],
importpath = "go-common/app/service/main/identify-game/cmd",
tags = ["automanaged"],
visibility = ["//visibility:private"],
deps = [
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/rpc/server:go_default_library",
"//app/service/main/identify-game/server/grpc:go_default_library",
"//app/service/main/identify-game/server/http:go_default_library",
"//app/service/main/identify-game/service:go_default_library",
"//library/log:go_default_library",
"//library/net/trace:go_default_library",
],
)
go_binary(
name = "cmd",
embed = [":go_default_library"],
visibility = ["//visibility:public"],
)
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,63 @@
# This is a TOML document. Boom.
[bm]
addr = "0.0.0.0:7391"
timeout = "1s"
[rpcServer]
proto = "tcp"
addr = "0.0.0.0:7399"
timeout = "30s"
[passport]
[passport.host]
auth = "http://passport.bilibili.co"
[HTTPClient]
key = "7d9f6f6fe2a898e8"
secret = "4de2ccdbd9db69be0c2c6437bfe6eb69"
dial = "50ms"
timeout = "200ms"
keepAlive = "60s"
[HTTPClient.breaker]
window ="1s"
sleep ="10ms"
bucket = 10
ratio = 0.5
request = 100
[memcache]
name = "identify-game-service"
proto = "tcp"
addr = "172.18.33.61:11235"
idle = 5
active = 10
dialTimeout = "1s"
readTimeout = "1s"
writeTimeout = "1s"
idleTimeout = "10s"
expire = "10h"
[dispatcher]
name = "origin"
[dispatcher.oauth]
"origin" = "http://passport.bilibili.com/api/oauth"
"t1" = "http://api.bilibili.com/x/passport-game/oauth"
"t2" = "http://t2-api.bilibili.com/x/passport-game/oauth"
[dispatcher.renewToken]
"origin" = "http://passport.bilibili.com/api/login/renewToken"
"t1" = "http://api.bilibili.com/x/passport-game/renewtoken"
"t2" = "http://t2-api.bilibili.com/x/passport-game/renewtoken"
[[dispatcher.regionInfos]]
region = "市北"
tokenSuffix = ""
[[dispatcher.regionInfos]]
region = "腾讯云1"
tokenSuffix = "t1"
[[dispatcher.regionInfos]]
region = "腾讯云2"
tokenSuffix = "t2"

View File

@@ -0,0 +1,58 @@
package main
import (
"context"
"flag"
"go-common/app/service/main/identify-game/server/grpc"
"os"
"os/signal"
"syscall"
"time"
"go-common/app/service/main/identify-game/conf"
rpc "go-common/app/service/main/identify-game/rpc/server"
"go-common/app/service/main/identify-game/server/http"
"go-common/app/service/main/identify-game/service"
"go-common/library/log"
"go-common/library/net/trace"
)
func main() {
flag.Parse()
// init conf,log,trace,stat,perf.
if err := conf.Init(); err != nil {
panic(err)
}
log.Init(conf.Conf.Xlog)
defer log.Close()
trace.Init(conf.Conf.Tracer)
defer trace.Close()
// service init
svr := service.New(conf.Conf)
rpcSvr := rpc.New(conf.Conf, svr)
http.Init(conf.Conf, svr)
// init warden server
ws := grpc.New(conf.Conf.WardenServer, svr)
// signal handler
log.Info("identify-game-service start")
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
for {
s := <-c
log.Info("identify-game-service get a signal %s", s.String())
switch s {
case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
rpcSvr.Close()
time.Sleep(time.Second * 2)
svr.Close()
ws.Shutdown(context.Background())
log.Info("identify-game-service exit")
return
case syscall.SIGHUP:
default:
return
}
}
}

View File

@@ -0,0 +1,40 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["conf.go"],
importpath = "go-common/app/service/main/identify-game/conf",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/conf:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/verify:go_default_library",
"//library/net/rpc:go_default_library",
"//library/net/rpc/warden:go_default_library",
"//library/net/trace:go_default_library",
"//vendor/github.com/BurntSushi/toml: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,111 @@
package conf
import (
"errors"
"flag"
"go-common/app/service/main/identify-game/model"
"go-common/library/cache/memcache"
"go-common/library/conf"
"go-common/library/log"
"go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/verify"
"go-common/library/net/rpc"
"go-common/library/net/rpc/warden"
"go-common/library/net/trace"
"github.com/BurntSushi/toml"
)
// Conf global variable.
var (
Conf = &Config{}
client *conf.Client
confPath string
)
// Config struct of conf.
type Config struct {
// base
// log
Xlog *log.Config
//Tracer *conf.Tracer
Tracer *trace.Config
// Verify
Verify *verify.Config
// BM
BM *blademaster.ServerConfig
// http client
HTTPClient *blademaster.ClientConfig
// memcache
Memcache *memcache.Config
// url router map
Dispatcher *Dispatcher
// RPCServer rpc server
RPCServer *rpc.ServerConfig
// grpc server
WardenServer *warden.ServerConfig
// passport
Passport *PassportConfig
}
// Dispatcher router map
type Dispatcher struct {
Name string
Oauth map[string]string
RenewToken map[string]string
RegionInfos []*model.RegionInfo
}
// PassportConfig identify config
type PassportConfig struct {
Host map[string]string
}
func local() (err error) {
_, err = toml.DecodeFile(confPath, &Conf)
return
}
func remote() (err error) {
if client, err = conf.New(); err != nil {
return
}
if err = load(); err != nil {
return
}
go func() {
for range client.Event() {
log.Info("config event")
}
}()
return
}
func load() (err error) {
var (
s string
ok bool
tmpConf *Config
)
if s, ok = client.Toml2(); !ok {
return errors.New("load config center error")
}
if _, err = toml.Decode(s, &tmpConf); err != nil {
return errors.New("could not decode config")
}
*Conf = *tmpConf
return
}
func init() {
flag.StringVar(&confPath, "conf", "", "default config path")
}
// Init int config
func Init() error {
if confPath != "" {
return local()
}
return remote()
}

View File

@@ -0,0 +1,62 @@
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",
"memcache_test.go",
"passport_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/model:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
"//vendor/gopkg.in/h2non/gock.v1:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"dao.go",
"memcache.go",
"passport.go",
],
importpath = "go-common/app/service/main/identify-game/dao",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/api/grpc/v1:go_default_library",
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/model:go_default_library",
"//library/cache/memcache:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/metadata:go_default_library",
"//library/stat/prom: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,61 @@
package dao
import (
"context"
"go-common/app/service/main/identify-game/conf"
"go-common/library/cache/memcache"
httpx "go-common/library/net/http/blademaster"
"go-common/library/stat/prom"
)
var (
errorsCount = prom.BusinessErrCount
cachedCount = prom.CacheHit
missedCount = prom.CacheMiss
)
// PromError prom error
func PromError(name string) {
errorsCount.Incr(name)
}
// Dao struct info of Dao
type Dao struct {
c *conf.Config
mc *memcache.Pool
client *httpx.Client
}
// New new a Dao and return.
func New(c *conf.Config) (d *Dao) {
d = &Dao{
c: c,
mc: memcache.NewPool(c.Memcache),
client: httpx.NewClient(c.HTTPClient),
}
return
}
// Close close connections of mc, redis, db.
func (d *Dao) Close() error {
return d.mc.Close()
}
// Ping ping health.
func (d *Dao) Ping(c context.Context) (err error) {
if err = d.pingMC(c); err != nil {
PromError("mc:Ping")
}
return
}
// pingMc ping memcache
func (d *Dao) pingMC(c context.Context) (err error) {
conn := d.mc.Get(c)
defer conn.Close()
item := memcache.Item{Key: "ping", Value: []byte{1}, Expiration: 100}
err = conn.Set(&item)
return
}

View File

@@ -0,0 +1,43 @@
package dao
import (
"flag"
"go-common/app/service/main/identify-game/conf"
"os"
"testing"
"gopkg.in/h2non/gock.v1"
)
var (
d *Dao
)
func TestMain(m *testing.M) {
if os.Getenv("DEPLOY_ENV") != "dev" {
flag.Set("app_id", "main.account.identify-game")
flag.Set("conf_token", "ba87634784874cad05e941bcabd55512")
flag.Set("tree_id", "identify-game")
flag.Set("tree_id", "11799")
flag.Set("conf_version", "server-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")
}
flag.Parse()
if err := conf.Init(); err != nil {
panic(err)
}
d = New(conf.Conf)
d.client.SetTransport(gock.DefaultTransport)
m.Run()
os.Exit(0)
}
//func httpMock(method, url string) *gock.Request {
// r := gock.New(url)
// r.Method = strings.ToUpper(method)
// return r
//}

View File

@@ -0,0 +1,62 @@
package dao
import (
"context"
"go-common/app/service/main/identify-game/model"
"go-common/library/cache/memcache"
"go-common/library/log"
)
// SetAccessCache .
func (d *Dao) SetAccessCache(c context.Context, key string, res *model.AccessInfo) (err error) {
if res.Expires < 0 {
log.Error("identify-game expire error(expires:%d)", res.Expires)
return
}
item := &memcache.Item{Key: key, Object: res, Flags: memcache.FlagProtobuf, Expiration: int32(res.Expires)}
conn := d.mc.Get(c)
defer conn.Close()
if err = conn.Set(item); err != nil {
log.Error("identify-game set error(%s,%d,%v)", key, res.Expires, err)
}
return
}
// AccessCache .
func (d *Dao) AccessCache(c context.Context, key string) (res *model.AccessInfo, err error) {
conn := d.mc.Get(c)
defer conn.Close()
r, err := conn.Get(key)
if err != nil {
if err == memcache.ErrNotFound {
missedCount.Incr("access_cache")
err = nil
return
}
log.Error("conn.Get(%s) error(%v)", key, err)
return
}
res = &model.AccessInfo{}
if err = conn.Scan(r, res); err != nil {
PromError("mc:json解析失败")
log.Error("conn.Scan(%v) error(%v)", string(r.Value), err)
return
}
cachedCount.Incr("access_cache")
return
}
// DelAccessCache del cache.
func (d *Dao) DelAccessCache(c context.Context, key string) (err error) {
conn := d.mc.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,58 @@
package dao
import (
"context"
"go-common/app/service/main/identify-game/model"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoSetAccessCache(t *testing.T) {
var (
c = context.Background()
key = "123456"
res = &model.AccessInfo{Mid: 1, AppID: 1, Token: "ashiba", CreateAt: 123, UserID: "12", Name: "mdzz", Expires: 1577811661, Permission: "all"}
)
convey.Convey("SetAccessCache", t, func(ctx convey.C) {
err := d.SetAccessCache(c, key, res)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
res.Expires = -1
convey.Convey("SetAccessCacheExpires", t, func(ctx convey.C) {
err := d.SetAccessCache(c, key, res)
ctx.Convey("Then err should be error.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}
func TestDaoAccessCache(t *testing.T) {
var (
c = context.Background()
key = "123456"
)
convey.Convey("AccessCache", t, func(ctx convey.C) {
res, err := d.AccessCache(c, key)
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 TestDaoDelAccessCache(t *testing.T) {
var (
c = context.Background()
key = "123456"
)
convey.Convey("DelAccessCache", t, func(ctx convey.C) {
err := d.DelAccessCache(c, key)
ctx.Convey("Then err should be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldBeNil)
})
})
}

View File

@@ -0,0 +1,128 @@
package dao
import (
"context"
"fmt"
"net/url"
"strconv"
"go-common/app/service/main/identify-game/api/grpc/v1"
"go-common/app/service/main/identify-game/model"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
)
const (
_createCookieURI = "/intranet/auth/createCookie/byMid"
)
// AccessToken .
func (d *Dao) AccessToken(c context.Context, accesskey, target string) (token *model.AccessInfo, err error) {
params := url.Values{}
params.Set("access_key", accesskey)
var res struct {
Code int `json:"code"`
Token *struct {
Mid string `json:"mid"`
AppID int64 `json:"appid"`
Token string `json:"access_key"`
CreateAt int64 `json:"create_at"`
UserID string `json:"userid"`
Name string `json:"uname"`
Expires string `json:"expires"`
Permission string `json:"permission"`
} `json:"access_info,omitempty"`
Data *model.AccessInfo `json:"data,omitempty"`
}
tokenURL := d.c.Dispatcher.Oauth[target]
if err = d.client.Get(c, tokenURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("oauth for region %s, url(%s) error(%v)", target, tokenURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
err = ecode.Int(res.Code)
log.Error("oauth for region %s, url(%s) error(%v)", target, tokenURL+"?"+params.Encode(), err)
return
}
if res.Token != nil {
t := res.Token
var mid int64
if mid, err = strconv.ParseInt(t.Mid, 10, 64); err != nil {
log.Error("strconv.ParseInt(%s, 10, 64) error(%v)", t.Mid, err)
return
}
var expires int64
if expires, err = strconv.ParseInt(t.Expires, 10, 64); err != nil {
log.Error("strconv.ParseInt(%s, 10, 64) error(%v)", t.Expires, err)
return
}
token = &model.AccessInfo{
Mid: mid,
AppID: t.AppID,
Token: t.Token,
CreateAt: t.CreateAt,
UserID: t.UserID,
Name: t.Name,
Expires: expires,
Permission: t.Permission,
}
} else {
token = res.Data
}
return
}
// RenewToken request passport renewToken .
func (d *Dao) RenewToken(c context.Context, accesskey, target string) (renewToken *model.RenewInfo, err error) {
params := url.Values{}
params.Set("access_key", accesskey)
var res struct {
Code int `json:"code"`
Expires int64 `json:"expires"`
Data struct {
Expires int64 `json:"expires"`
}
}
renewURL := d.c.Dispatcher.RenewToken[target]
if err = d.client.Get(c, renewURL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("renewtoken for region %s, url(%s) error(%v)", target, renewURL+"?"+params.Encode(), err)
return
}
if res.Code != 0 {
err = ecode.Int(res.Code)
log.Error("renewtoken for region %s, url(%s) error(%v)", target, renewURL+"?"+params.Encode(), err)
return
}
expires := res.Expires
if expires == 0 {
expires = res.Data.Expires
}
renewToken = &model.RenewInfo{
Expires: expires,
}
return
}
// GetCookieByMid get cookie by mid
func (d *Dao) GetCookieByMid(c context.Context, mid int64) (cookies *v1.CreateCookieReply, err error) {
params := url.Values{}
params.Set("mid", fmt.Sprintf("%d", mid))
URL := d.c.Passport.Host["auth"] + _createCookieURI
var res struct {
Code int `json:"code"`
Data *v1.CreateCookieReply `json:"data,omitempty"`
}
if err = d.client.Get(c, URL, metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
log.Error("get cookies by mid(%d) from url(%s) error(%v)", mid, URL, err)
return
}
if res.Code != 0 {
err = ecode.Int(res.Code)
log.Error("get cookies error, mid(%d), error(%v)", mid, err)
return
}
cookies = res.Data
return
}

View File

@@ -0,0 +1,50 @@
package dao
import (
"context"
"testing"
"github.com/smartystreets/goconvey/convey"
)
func TestDaoAccessToken(t *testing.T) {
var (
c = context.Background()
accesskey = "accessKey"
target = "origin"
)
convey.Convey("AccessToken", t, func(ctx convey.C) {
token, err := d.AccessToken(c, accesskey, target)
ctx.Convey("Then err should be nil.token should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, -101)
ctx.So(token, convey.ShouldBeNil)
})
})
}
func TestDaoRenewToken(t *testing.T) {
var (
c = context.Background()
accesskey = "accessKey"
target = "origin"
)
convey.Convey("RenewToken", t, func(ctx convey.C) {
renewToken, err := d.RenewToken(c, accesskey, target)
ctx.Convey("Then err should be nil.renewToken should not be nil.", func(ctx convey.C) {
ctx.So(err, convey.ShouldEqual, -101)
ctx.So(renewToken, convey.ShouldBeNil)
})
})
}
func TestGetCookieByMid(t *testing.T) {
var (
c = context.Background()
mid = int64(234112334566723432)
)
convey.Convey("GetCookieByMid", t, func(ctx convey.C) {
cookies, err := d.GetCookieByMid(c, mid)
convey.So(err, convey.ShouldNotBeNil)
convey.So(cookies, convey.ShouldBeNil)
})
}

View File

@@ -0,0 +1,56 @@
load(
"@io_bazel_rules_go//proto:def.bzl",
"go_proto_library",
)
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"cloud.go",
"rpc.go",
],
embed = [":model_go_proto"],
importpath = "go-common/app/service/main/identify-game/model",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"@com_github_gogo_protobuf//gogoproto:go_default_library",
"@com_github_gogo_protobuf//proto: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"],
)
proto_library(
name = "model_proto",
srcs = ["token.proto"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["@gogo_special_proto//github.com/gogo/protobuf/gogoproto"],
)
go_proto_library(
name = "model_go_proto",
compilers = ["@io_bazel_rules_go//proto:gogofast_proto"],
importpath = "go-common/app/service/main/identify-game/model",
proto = ":model_proto",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = ["@com_github_gogo_protobuf//gogoproto:go_default_library"],
)

View File

@@ -0,0 +1,7 @@
package model
// RegionInfo region info.
type RegionInfo struct {
Region string `json:"region"`
TokenSuffix string `json:"token_suffix"`
}

View File

@@ -0,0 +1,7 @@
package model
// CleanCacheArgs del cache rpc client arguments.
type CleanCacheArgs struct {
Token string
Mid int64
}

View File

@@ -0,0 +1,793 @@
// Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: app/service/main/identify-game/model/token.proto
package model
import proto "github.com/gogo/protobuf/proto"
import fmt "fmt"
import math "math"
import _ "github.com/gogo/protobuf/gogoproto"
import io "io"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package
// result of http access info.
type AccessInfo struct {
Mid int64 `protobuf:"varint,1,opt,name=Mid,proto3" json:"mid"`
AppID int64 `protobuf:"varint,2,opt,name=AppID,proto3" json:"appid"`
Token string `protobuf:"bytes,3,opt,name=Token,proto3" json:"access_key"`
CreateAt int64 `protobuf:"varint,4,opt,name=CreateAt,proto3" json:"create_at"`
UserID string `protobuf:"bytes,5,opt,name=UserID,proto3" json:"userid"`
Name string `protobuf:"bytes,6,opt,name=Name,proto3" json:"uname"`
Expires int64 `protobuf:"varint,7,opt,name=Expires,proto3" json:"expires"`
Permission string `protobuf:"bytes,8,opt,name=Permission,proto3" json:"permission"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *AccessInfo) Reset() { *m = AccessInfo{} }
func (m *AccessInfo) String() string { return proto.CompactTextString(m) }
func (*AccessInfo) ProtoMessage() {}
func (*AccessInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_token_a3d7e52fbb774120, []int{0}
}
func (m *AccessInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *AccessInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_AccessInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (dst *AccessInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_AccessInfo.Merge(dst, src)
}
func (m *AccessInfo) XXX_Size() int {
return m.Size()
}
func (m *AccessInfo) XXX_DiscardUnknown() {
xxx_messageInfo_AccessInfo.DiscardUnknown(m)
}
var xxx_messageInfo_AccessInfo proto.InternalMessageInfo
func (m *AccessInfo) GetMid() int64 {
if m != nil {
return m.Mid
}
return 0
}
func (m *AccessInfo) GetAppID() int64 {
if m != nil {
return m.AppID
}
return 0
}
func (m *AccessInfo) GetToken() string {
if m != nil {
return m.Token
}
return ""
}
func (m *AccessInfo) GetCreateAt() int64 {
if m != nil {
return m.CreateAt
}
return 0
}
func (m *AccessInfo) GetUserID() string {
if m != nil {
return m.UserID
}
return ""
}
func (m *AccessInfo) GetName() string {
if m != nil {
return m.Name
}
return ""
}
func (m *AccessInfo) GetExpires() int64 {
if m != nil {
return m.Expires
}
return 0
}
func (m *AccessInfo) GetPermission() string {
if m != nil {
return m.Permission
}
return ""
}
type RenewInfo struct {
Expires int64 `protobuf:"varint,1,opt,name=Expires,proto3" json:"expires"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *RenewInfo) Reset() { *m = RenewInfo{} }
func (m *RenewInfo) String() string { return proto.CompactTextString(m) }
func (*RenewInfo) ProtoMessage() {}
func (*RenewInfo) Descriptor() ([]byte, []int) {
return fileDescriptor_token_a3d7e52fbb774120, []int{1}
}
func (m *RenewInfo) XXX_Unmarshal(b []byte) error {
return m.Unmarshal(b)
}
func (m *RenewInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
if deterministic {
return xxx_messageInfo_RenewInfo.Marshal(b, m, deterministic)
} else {
b = b[:cap(b)]
n, err := m.MarshalTo(b)
if err != nil {
return nil, err
}
return b[:n], nil
}
}
func (dst *RenewInfo) XXX_Merge(src proto.Message) {
xxx_messageInfo_RenewInfo.Merge(dst, src)
}
func (m *RenewInfo) XXX_Size() int {
return m.Size()
}
func (m *RenewInfo) XXX_DiscardUnknown() {
xxx_messageInfo_RenewInfo.DiscardUnknown(m)
}
var xxx_messageInfo_RenewInfo proto.InternalMessageInfo
func (m *RenewInfo) GetExpires() int64 {
if m != nil {
return m.Expires
}
return 0
}
func init() {
proto.RegisterType((*AccessInfo)(nil), "model.accessInfo")
proto.RegisterType((*RenewInfo)(nil), "model.renewInfo")
}
func (m *AccessInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *AccessInfo) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Mid != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintToken(dAtA, i, uint64(m.Mid))
}
if m.AppID != 0 {
dAtA[i] = 0x10
i++
i = encodeVarintToken(dAtA, i, uint64(m.AppID))
}
if len(m.Token) > 0 {
dAtA[i] = 0x1a
i++
i = encodeVarintToken(dAtA, i, uint64(len(m.Token)))
i += copy(dAtA[i:], m.Token)
}
if m.CreateAt != 0 {
dAtA[i] = 0x20
i++
i = encodeVarintToken(dAtA, i, uint64(m.CreateAt))
}
if len(m.UserID) > 0 {
dAtA[i] = 0x2a
i++
i = encodeVarintToken(dAtA, i, uint64(len(m.UserID)))
i += copy(dAtA[i:], m.UserID)
}
if len(m.Name) > 0 {
dAtA[i] = 0x32
i++
i = encodeVarintToken(dAtA, i, uint64(len(m.Name)))
i += copy(dAtA[i:], m.Name)
}
if m.Expires != 0 {
dAtA[i] = 0x38
i++
i = encodeVarintToken(dAtA, i, uint64(m.Expires))
}
if len(m.Permission) > 0 {
dAtA[i] = 0x42
i++
i = encodeVarintToken(dAtA, i, uint64(len(m.Permission)))
i += copy(dAtA[i:], m.Permission)
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func (m *RenewInfo) Marshal() (dAtA []byte, err error) {
size := m.Size()
dAtA = make([]byte, size)
n, err := m.MarshalTo(dAtA)
if err != nil {
return nil, err
}
return dAtA[:n], nil
}
func (m *RenewInfo) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if m.Expires != 0 {
dAtA[i] = 0x8
i++
i = encodeVarintToken(dAtA, i, uint64(m.Expires))
}
if m.XXX_unrecognized != nil {
i += copy(dAtA[i:], m.XXX_unrecognized)
}
return i, nil
}
func encodeVarintToken(dAtA []byte, offset int, v uint64) int {
for v >= 1<<7 {
dAtA[offset] = uint8(v&0x7f | 0x80)
v >>= 7
offset++
}
dAtA[offset] = uint8(v)
return offset + 1
}
func (m *AccessInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Mid != 0 {
n += 1 + sovToken(uint64(m.Mid))
}
if m.AppID != 0 {
n += 1 + sovToken(uint64(m.AppID))
}
l = len(m.Token)
if l > 0 {
n += 1 + l + sovToken(uint64(l))
}
if m.CreateAt != 0 {
n += 1 + sovToken(uint64(m.CreateAt))
}
l = len(m.UserID)
if l > 0 {
n += 1 + l + sovToken(uint64(l))
}
l = len(m.Name)
if l > 0 {
n += 1 + l + sovToken(uint64(l))
}
if m.Expires != 0 {
n += 1 + sovToken(uint64(m.Expires))
}
l = len(m.Permission)
if l > 0 {
n += 1 + l + sovToken(uint64(l))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func (m *RenewInfo) Size() (n int) {
if m == nil {
return 0
}
var l int
_ = l
if m.Expires != 0 {
n += 1 + sovToken(uint64(m.Expires))
}
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovToken(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozToken(x uint64) (n int) {
return sovToken(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *AccessInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: accessInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: accessInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Mid", wireType)
}
m.Mid = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Mid |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 2:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field AppID", wireType)
}
m.AppID = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.AppID |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 3:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Token", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthToken
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Token = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 4:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field CreateAt", wireType)
}
m.CreateAt = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.CreateAt |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 5:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field UserID", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthToken
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.UserID = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 6:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Name", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthToken
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Name = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 7:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Expires", wireType)
}
m.Expires = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Expires |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
case 8:
if wireType != 2 {
return fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType)
}
var stringLen uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
stringLen |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
intStringLen := int(stringLen)
if intStringLen < 0 {
return ErrInvalidLengthToken
}
postIndex := iNdEx + intStringLen
if postIndex > l {
return io.ErrUnexpectedEOF
}
m.Permission = string(dAtA[iNdEx:postIndex])
iNdEx = postIndex
default:
iNdEx = preIndex
skippy, err := skipToken(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthToken
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func (m *RenewInfo) Unmarshal(dAtA []byte) error {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
preIndex := iNdEx
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
fieldNum := int32(wire >> 3)
wireType := int(wire & 0x7)
if wireType == 4 {
return fmt.Errorf("proto: renewInfo: wiretype end group for non-group")
}
if fieldNum <= 0 {
return fmt.Errorf("proto: renewInfo: illegal tag %d (wire type %d)", fieldNum, wire)
}
switch fieldNum {
case 1:
if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Expires", wireType)
}
m.Expires = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowToken
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m.Expires |= (int64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
default:
iNdEx = preIndex
skippy, err := skipToken(dAtA[iNdEx:])
if err != nil {
return err
}
if skippy < 0 {
return ErrInvalidLengthToken
}
if (iNdEx + skippy) > l {
return io.ErrUnexpectedEOF
}
m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...)
iNdEx += skippy
}
}
if iNdEx > l {
return io.ErrUnexpectedEOF
}
return nil
}
func skipToken(dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowToken
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
wireType := int(wire & 0x7)
switch wireType {
case 0:
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowToken
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
iNdEx++
if dAtA[iNdEx-1] < 0x80 {
break
}
}
return iNdEx, nil
case 1:
iNdEx += 8
return iNdEx, nil
case 2:
var length int
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowToken
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
length |= (int(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
iNdEx += length
if length < 0 {
return 0, ErrInvalidLengthToken
}
return iNdEx, nil
case 3:
for {
var innerWire uint64
var start int = iNdEx
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowToken
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
innerWire |= (uint64(b) & 0x7F) << shift
if b < 0x80 {
break
}
}
innerWireType := int(innerWire & 0x7)
if innerWireType == 4 {
break
}
next, err := skipToken(dAtA[start:])
if err != nil {
return 0, err
}
iNdEx = start + next
}
return iNdEx, nil
case 4:
return iNdEx, nil
case 5:
iNdEx += 4
return iNdEx, nil
default:
return 0, fmt.Errorf("proto: illegal wireType %d", wireType)
}
}
panic("unreachable")
}
var (
ErrInvalidLengthToken = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowToken = fmt.Errorf("proto: integer overflow")
)
func init() {
proto.RegisterFile("app/service/main/identify-game/model/token.proto", fileDescriptor_token_a3d7e52fbb774120)
}
var fileDescriptor_token_a3d7e52fbb774120 = []byte{
// 348 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x90, 0x4f, 0x4e, 0xeb, 0x30,
0x10, 0x87, 0x95, 0xa6, 0x49, 0x1a, 0xbf, 0x3f, 0x0b, 0xaf, 0xfc, 0x9e, 0x44, 0x53, 0x55, 0x20,
0x95, 0x45, 0x1b, 0x04, 0x27, 0x68, 0x29, 0x8b, 0x2e, 0x40, 0xc8, 0x82, 0x75, 0xe5, 0x26, 0xd3,
0x60, 0x15, 0xc7, 0x96, 0x9d, 0x00, 0x3d, 0x17, 0x97, 0x60, 0xc9, 0x09, 0x22, 0xd4, 0x65, 0x4e,
0x81, 0xea, 0x94, 0xd2, 0x0d, 0x3b, 0xcf, 0xf7, 0x8d, 0x67, 0x7e, 0x1a, 0x74, 0xc6, 0x94, 0x8a,
0x0d, 0xe8, 0x27, 0x9e, 0x40, 0x2c, 0x18, 0xcf, 0x63, 0x9e, 0x42, 0x5e, 0xf0, 0xe5, 0x7a, 0x98,
0x31, 0x01, 0xb1, 0x90, 0x29, 0x3c, 0xc6, 0x85, 0x5c, 0x41, 0x3e, 0x52, 0x5a, 0x16, 0x12, 0x7b,
0x16, 0xfd, 0x1f, 0x66, 0xbc, 0x78, 0x28, 0x17, 0xa3, 0x44, 0x8a, 0x38, 0x93, 0x99, 0x8c, 0xad,
0x5d, 0x94, 0x4b, 0x5b, 0xd9, 0xc2, 0xbe, 0x9a, 0x5f, 0xfd, 0xd7, 0x16, 0x42, 0x2c, 0x49, 0xc0,
0x98, 0x59, 0xbe, 0x94, 0xf8, 0x1f, 0x72, 0xaf, 0x79, 0x4a, 0x9c, 0x9e, 0x33, 0x70, 0x27, 0x41,
0x5d, 0x45, 0xae, 0xe0, 0x29, 0xdd, 0x32, 0x1c, 0x21, 0x6f, 0xac, 0xd4, 0x6c, 0x4a, 0x5a, 0x56,
0x86, 0x75, 0x15, 0x79, 0x4c, 0x29, 0x9e, 0xd2, 0x86, 0xe3, 0x63, 0xe4, 0xdd, 0x6d, 0xf3, 0x10,
0xb7, 0xe7, 0x0c, 0xc2, 0xc9, 0xdf, 0xba, 0x8a, 0x76, 0xa3, 0xe7, 0x2b, 0x58, 0xd3, 0x46, 0xe2,
0x53, 0xd4, 0xb9, 0xd4, 0xc0, 0x0a, 0x18, 0x17, 0xa4, 0x6d, 0x27, 0xfd, 0xa9, 0xab, 0x28, 0x4c,
0x2c, 0x9b, 0xb3, 0x82, 0xee, 0x35, 0xee, 0x23, 0xff, 0xde, 0x80, 0x9e, 0x4d, 0x89, 0x67, 0x27,
0xa2, 0xba, 0x8a, 0xfc, 0xd2, 0x80, 0xe6, 0x29, 0xdd, 0x19, 0x7c, 0x84, 0xda, 0x37, 0x4c, 0x00,
0xf1, 0x6d, 0x87, 0x0d, 0x55, 0xe6, 0x4c, 0x00, 0xb5, 0x18, 0x9f, 0xa0, 0xe0, 0xea, 0x45, 0x71,
0x0d, 0x86, 0x04, 0x76, 0xd9, 0xaf, 0xba, 0x8a, 0x02, 0x68, 0x10, 0xfd, 0x72, 0x78, 0x84, 0xd0,
0x2d, 0x68, 0xc1, 0x8d, 0xe1, 0x32, 0x27, 0x9d, 0xef, 0xfc, 0x6a, 0x4f, 0xe9, 0x41, 0x47, 0xff,
0x1c, 0x85, 0x1a, 0x72, 0x78, 0xb6, 0x37, 0x3b, 0xd8, 0xe1, 0xfc, 0xbc, 0x63, 0xf2, 0xfb, 0x6d,
0xd3, 0x75, 0xde, 0x37, 0x5d, 0xe7, 0x63, 0xd3, 0x75, 0x16, 0xbe, 0x3d, 0xff, 0xc5, 0x67, 0x00,
0x00, 0x00, 0xff, 0xff, 0xe3, 0x2b, 0xe9, 0x37, 0xe8, 0x01, 0x00, 0x00,
}

View File

@@ -0,0 +1,20 @@
syntax = "proto3";
package model;
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
// result of http access info.
message accessInfo {
int64 Mid = 1 [(gogoproto.jsontag) = "mid"];
int64 AppID = 2 [(gogoproto.jsontag) = "appid"];
string Token = 3 [(gogoproto.jsontag) = "access_key"];
int64 CreateAt = 4 [(gogoproto.jsontag) = "create_at"];
string UserID = 5 [(gogoproto.jsontag) = "userid"];
string Name = 6 [(gogoproto.jsontag) = "uname"];
int64 Expires = 7 [(gogoproto.jsontag) = "expires"];
string Permission = 8 [(gogoproto.jsontag) = "permission"];
}
message renewInfo {
int64 Expires = 1 [(gogoproto.jsontag) = "expires"];
}

View File

@@ -0,0 +1,40 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = ["client.go"],
importpath = "go-common/app/service/main/identify-game/rpc/client",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/model:go_default_library",
"//library/net/rpc:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = ["client_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = ["//app/service/main/identify-game/model: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,36 @@
package client
import (
"context"
"go-common/app/service/main/identify-game/model"
"go-common/library/net/rpc"
)
const (
_delCache = "RPC.DelCache"
_appid = "identify.service.game"
)
var (
_noRes = &struct{}{}
)
// Client Request Client
type Client struct {
client *rpc.Client2
}
// New Request Client
func New(c *rpc.ClientConfig) (cli *Client) {
cli = &Client{
client: rpc.NewDiscoveryCli(_appid, c),
}
return
}
// DelCache del token cache.
func (cli *Client) DelCache(c context.Context, arg *model.CleanCacheArgs) (err error) {
err = cli.client.Call(c, _delCache, arg, _noRes)
return
}

View File

@@ -0,0 +1,25 @@
package client
import (
"context"
"testing"
"time"
"go-common/app/service/main/identify-game/model"
)
func TestNew(t *testing.T) {
cli := New(nil)
time.Sleep(2 * time.Second)
if err := cli.DelCache(context.Background(), &model.CleanCacheArgs{Token: "1234567890123456789012"}); err != nil {
t.FailNow()
}
testDelCache(t, cli)
}
func testDelCache(t *testing.T, cli *Client) {
if err := cli.DelCache(context.Background(), &model.CleanCacheArgs{Token: "1234567890123456789012"}); err != nil {
t.Errorf("%v\n", err)
}
}

View File

@@ -0,0 +1,36 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"identify.go",
"rpc.go",
],
importpath = "go-common/app/service/main/identify-game/rpc/server",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/model:go_default_library",
"//app/service/main/identify-game/service:go_default_library",
"//library/net/rpc:go_default_library",
"//library/net/rpc/context: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,12 @@
package server
import (
"go-common/app/service/main/identify-game/model"
"go-common/library/net/rpc/context"
)
// DelCache del token cache.
func (r *RPC) DelCache(c context.Context, arg *model.CleanCacheArgs, res *struct{}) (err error) {
err = r.s.DelCache(c, arg.Token)
return
}

View File

@@ -0,0 +1,28 @@
package server
import (
"go-common/app/service/main/identify-game/conf"
"go-common/app/service/main/identify-game/service"
"go-common/library/net/rpc"
"go-common/library/net/rpc/context"
)
// RPC define rpc.
type RPC struct {
s *service.Service
}
// New new rpc server.
func New(c *conf.Config, s *service.Service) (svr *rpc.Server) {
r := &RPC{s: s}
svr = rpc.NewServer(c.RPCServer)
if err := svr.Register(r); err != nil {
panic(err)
}
return
}
// Ping check connection success.
func (r *RPC) Ping(c context.Context, arg *struct{}, res *struct{}) (err error) {
return
}

View File

@@ -0,0 +1,33 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = ["service.go"],
importpath = "go-common/app/service/main/identify-game/server/grpc",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/api/grpc/v1:go_default_library",
"//app/service/main/identify-game/service:go_default_library",
"//library/net/rpc/warden: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,36 @@
package grpc
import (
"context"
"go-common/app/service/main/identify-game/api/grpc/v1"
"go-common/app/service/main/identify-game/service"
"go-common/library/net/rpc/warden"
)
// New identify game warden rpc server
func New(cfg *warden.ServerConfig, s *service.Service) *warden.Server {
w := warden.NewServer(cfg)
v1.RegisterIdentifyGameServer(w.Server(), &server{s})
ws, err := w.Start()
if err != nil {
panic(err)
}
return ws
}
type server struct {
svr *service.Service
}
var _ v1.IdentifyGameServer = &server{}
func (s *server) DelCache(ctx context.Context, req *v1.DelCacheReq) (*v1.DelCacheReply, error) {
err := s.svr.DelCache(ctx, req.Token)
return &v1.DelCacheReply{}, err
}
func (s *server) GetCookieByToken(ctx context.Context, req *v1.CreateCookieReq) (*v1.CreateCookieReply, error) {
cookies, err := s.svr.GetCookieByToken(ctx, req.Token, req.From)
return cookies, err
}

View File

@@ -0,0 +1,40 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
go_library(
name = "go_default_library",
srcs = [
"cloud.go",
"http.go",
"identify.go",
],
importpath = "go-common/app/service/main/identify-game/server/http",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/api/grpc/v1:go_default_library",
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/model:go_default_library",
"//app/service/main/identify-game/service:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/http/blademaster:go_default_library",
"//library/net/http/blademaster/middleware/verify: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,9 @@
package http
import (
bm "go-common/library/net/http/blademaster"
)
func regions(c *bm.Context) {
c.JSON(srv.Regions, nil)
}

View File

@@ -0,0 +1,55 @@
package http
import (
"net/http"
"go-common/app/service/main/identify-game/conf"
"go-common/app/service/main/identify-game/service"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
"go-common/library/net/http/blademaster/middleware/verify"
)
var (
srv *service.Service
vfy *verify.Verify
)
// Init init
func Init(c *conf.Config, s *service.Service) {
srv = s
vfy = verify.New(c.Verify)
// engine
engine := bm.DefaultServer(c.BM)
innerRouter(engine)
// init inner server
if err := engine.Start(); err != nil {
log.Error("engine.Start error(%v)", err)
panic(err)
}
}
func innerRouter(e *bm.Engine) {
e.Ping(ping)
e.Register(register)
group := e.Group("/x/internal/identify-game", vfy.Verify)
{
group.GET("/oauth", oauth)
group.GET("/renewtoken", renewToken)
group.GET("/regions", regions)
group.GET("/cookies", getCookieByToken)
}
}
// ping check server ok.
func ping(c *bm.Context) {
if err := srv.Ping(c); err != nil {
log.Error("ping error(%v)", err)
c.AbortWithStatus(http.StatusServiceUnavailable)
}
}
// register support discovery.
func register(c *bm.Context) {
c.JSON(map[string]struct{}{}, nil)
}

View File

@@ -0,0 +1,74 @@
package http
import (
"go-common/app/service/main/identify-game/api/grpc/v1"
"go-common/app/service/main/identify-game/model"
"go-common/app/service/main/identify-game/service"
"go-common/library/ecode"
"go-common/library/log"
bm "go-common/library/net/http/blademaster"
)
func oauth(c *bm.Context) {
var (
data *model.AccessInfo
err error
)
req := c.Request
accesskey := req.Form.Get("access_key")
if accesskey == "" {
c.JSON(nil, ecode.RequestErr)
return
}
from := req.Form.Get("from")
if data, err = srv.Oauth(c, accesskey, from); err != nil {
if err == service.ErrDispatcherError {
c.JSONMap(map[string]interface{}{"message": err.Error()}, err)
return
}
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}
func renewToken(c *bm.Context) {
var (
data *model.RenewInfo
err error
)
req := c.Request
accesskey := req.Form.Get("access_key")
if accesskey == "" {
c.JSON(nil, ecode.RequestErr)
return
}
from := req.Form.Get("from")
if data, err = srv.RenewToken(c, accesskey, from); err != nil {
if err == service.ErrDispatcherError {
c.JSONMap(map[string]interface{}{"message": err.Error()}, err)
return
}
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}
func getCookieByToken(c *bm.Context) {
var (
data *v1.CreateCookieReply
err error
)
p := new(v1.CreateCookieReq)
if err = c.Bind(p); err != nil {
log.Error("c.Bind err(%+v)", err)
return
}
data, err = srv.GetCookieByToken(c, p.Token, p.From)
if err != nil {
c.JSON(nil, err)
return
}
c.JSON(data, nil)
}

View File

@@ -0,0 +1,58 @@
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
"go_test",
)
go_library(
name = "go_default_library",
srcs = [
"cloud.go",
"identify.go",
"service.go",
],
importpath = "go-common/app/service/main/identify-game/service",
tags = ["automanaged"],
visibility = ["//visibility:public"],
deps = [
"//app/service/main/identify-game/api/grpc/v1:go_default_library",
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/dao:go_default_library",
"//app/service/main/identify-game/model:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/stat:go_default_library",
"//library/stat/prom:go_default_library",
],
)
go_test(
name = "go_default_test",
srcs = [
"cloud_test.go",
"identify_test.go",
],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/service/main/identify-game/conf:go_default_library",
"//app/service/main/identify-game/model:go_default_library",
"//library/ecode:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey: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,12 @@
package service
import (
"context"
"go-common/app/service/main/identify-game/model"
)
// Regions get region list.
func (s *Service) Regions(c context.Context) (res []*model.RegionInfo) {
return s.regionInfos
}

View File

@@ -0,0 +1,19 @@
package service
import (
"context"
"encoding/json"
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestService_Region(t *testing.T) {
once.Do(startService)
Convey("regions", t, func() {
m := s.Regions(context.TODO())
So(len(m), ShouldBeGreaterThan, 0)
res, _ := json.Marshal(m)
t.Logf("res: %s", res)
})
}

View File

@@ -0,0 +1,107 @@
package service
import (
"context"
"errors"
"strings"
"go-common/app/service/main/identify-game/api/grpc/v1"
"go-common/app/service/main/identify-game/model"
"go-common/library/ecode"
"go-common/library/log"
)
const (
_segmentation = "_"
)
var (
_noLogin = &model.AccessInfo{
Mid: -1,
Expires: 60,
}
// ErrDispatcherError dispatcher error
ErrDispatcherError = errors.New("dispatcher route map is error")
)
// Oauth verify user info by accesskey.
func (s *Service) Oauth(c context.Context, accesskey, from string) (res *model.AccessInfo, err error) {
cache := true
if len(accesskey) > 32 {
cache = false
}
if cache {
if res, err = s.d.AccessCache(c, accesskey); err != nil {
cache = false
}
}
if res != nil {
if res.Mid == _noLogin.Mid {
err = ecode.NoLogin
}
return
}
target := s.target(accesskey)
if from != "" && target != s.c.Dispatcher.Name {
s.dispatcherErrStats.Incr("dispatcher_error")
err = ErrDispatcherError
log.Error("Oauth dispatcher routMap is error. token:%s, from:%s", accesskey, from)
return
}
if res, err = s.d.AccessToken(c, accesskey, target); err != nil {
ec := ecode.Cause(err)
if ec != ecode.NoLogin && ec != ecode.AccessKeyErr {
return
}
if cache {
s.addCache(func() {
s.d.SetAccessCache(context.TODO(), accesskey, _noLogin)
})
}
return
}
if cache && res != nil {
s.addCache(func() {
s.d.SetAccessCache(context.TODO(), accesskey, res)
})
}
return
}
// RenewToken prolong user accesskey.
func (s *Service) RenewToken(c context.Context, accesskey, from string) (res *model.RenewInfo, err error) {
target := s.target(accesskey)
if from != "" && target != s.c.Dispatcher.Name {
s.dispatcherErrStats.Incr("dispatcher_error")
err = ErrDispatcherError
log.Error("RenewToken dispatcher routMap is error. token:%s, from:%s", accesskey, from)
return
}
return s.d.RenewToken(c, accesskey, target)
}
func (s *Service) target(accesskey string) (res string) {
index := strings.Index(accesskey, _segmentation)
if index < 0 {
res = s.c.Dispatcher.Name
return
}
res = accesskey[index+1:]
return
}
// DelCache for clean cache
func (s *Service) DelCache(c context.Context, accesskey string) error {
return s.d.DelAccessCache(c, accesskey)
}
// GetCookieByToken get mid by token, get cookie by Cookie
func (s *Service) GetCookieByToken(c context.Context, accesskey, from string) (cookies *v1.CreateCookieReply, err error) {
accInfo, err := s.Oauth(c, accesskey, from)
if err != nil {
return
}
cookies, err = s.d.GetCookieByMid(c, accInfo.Mid)
return
}

View File

@@ -0,0 +1,110 @@
package service
import (
"context"
"sync"
"testing"
"time"
"go-common/app/service/main/identify-game/conf"
"go-common/app/service/main/identify-game/model"
"go-common/library/ecode"
. "github.com/smartystreets/goconvey/convey"
)
var (
once sync.Once
s *Service
// 35位
errKey = "123456789012345678901234567890123451"
// 32位
rightKey = "12345678901234567890123456789013"
)
func startService() {
conf.Init()
s = New(conf.Conf)
time.Sleep(time.Second * 2)
}
func Test_AccessToken(t *testing.T) {
once.Do(startService)
Convey("access token", t, func() {
obj := &model.AccessInfo{
Mid: 41862641,
Token: "xxxxxxxxxxxxxxxxxxxxx",
Expires: 60,
}
err := s.d.SetAccessCache(context.Background(), obj.Token, obj)
So(err, ShouldBeNil)
_, err = s.Oauth(context.Background(), obj.Token, "origin")
So(err, ShouldBeNil)
_, err = s.Oauth(context.Background(), errKey, "origin")
So(err, ShouldEqual, ecode.NoLogin)
r, err := s.d.AccessCache(context.Background(), errKey)
So(err, ShouldBeNil)
So(r, ShouldBeNil)
_, err = s.Oauth(context.Background(), rightKey, "origin")
So(err, ShouldEqual, ecode.NoLogin)
time.Sleep(time.Millisecond * 10)
r, err = s.d.AccessCache(context.Background(), rightKey)
So(err, ShouldBeNil)
So(r, ShouldNotBeNil)
So(r.Mid, ShouldEqual, _noLogin.Mid)
})
}
func Test_RenewToken(t *testing.T) {
once.Do(startService)
if r, err := s.d.RenewToken(context.Background(), rightKey, "origin"); err != ecode.NoLogin {
t.Errorf("Test_RenewToken fail. %v, %v", r, err)
t.FailNow()
}
if r, err := s.d.RenewToken(context.Background(), errKey, "origin"); err != ecode.NoLogin {
t.Errorf("Test_RenewToken fail. %v, %v", r, err)
t.FailNow()
}
}
func Test_Target(t *testing.T) {
once.Do(startService)
Convey("target parse", t, func() {
Convey("situation 1", func() {
res := s.target(rightKey + "_tx")
So(res, ShouldEqual, "tx")
})
Convey("situation 2", func() {
res := s.target(rightKey + "_")
So(res, ShouldEqual, "")
})
Convey("situation 3", func() {
res := s.target(rightKey)
So(res, ShouldEqual, "origin")
})
})
}
func Test_DelCache(t *testing.T) {
once.Do(startService)
Convey("test delete cache", t, func() {
err := s.DelCache(context.Background(), "def32243")
So(err, ShouldBeNil)
})
}
func Test_GetCookies(t *testing.T) {
once.Do(startService)
Convey("test get cookies by token", t, func() {
cookies, err := s.GetCookieByToken(context.Background(), "def32243111", "")
So(err, ShouldNotBeNil)
So(cookies, ShouldBeNil)
})
}

View File

@@ -0,0 +1,60 @@
package service
import (
"context"
"go-common/app/service/main/identify-game/conf"
"go-common/app/service/main/identify-game/dao"
"go-common/app/service/main/identify-game/model"
"go-common/library/log"
"go-common/library/stat"
"go-common/library/stat/prom"
)
// Service is a identify service.
type Service struct {
c *conf.Config
d *dao.Dao
missch chan func()
regionInfos []*model.RegionInfo
dispatcherErrStats stat.Stat
}
// New new a identify service.
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
d: dao.New(c),
missch: make(chan func(), 10240),
regionInfos: c.Dispatcher.RegionInfos,
dispatcherErrStats: prom.BusinessErrCount,
}
go s.cacheproc()
return
}
// Close dao.
func (s *Service) Close() error {
return s.d.Close()
}
// Ping check server ok.
func (s *Service) Ping(c context.Context) (err error) {
return s.d.Ping(c)
}
func (s *Service) addCache(f func()) {
select {
case s.missch <- f:
default:
log.Warn("cacheproc chan full")
}
}
// cacheproc is a routine for executing closure.
func (s *Service) cacheproc() {
for {
f := <-s.missch
f()
}
}