Compare commits
250 Commits
kd-live
...
626819209f
| Author | SHA1 | Date | |
|---|---|---|---|
| 626819209f | |||
| 8e691a4174 | |||
| 887a28aef5 | |||
| 4aae3704e7 | |||
| 7e929189e1 | |||
| 962ed0cf71 | |||
| bb3a7fc957 | |||
| d00aaae839 | |||
| 40baa86bd6 | |||
| c24d387761 | |||
| c0ab2afcf4 | |||
| d26b3b9295 | |||
| c449bae5ef | |||
| 1f9eb75e41 | |||
| 77397bd6bc | |||
| 54cb3e818f | |||
| 38a3da271a | |||
| fb3f038506 | |||
| e4e0d49ace | |||
| b801be6aca | |||
| 49f2bd077d | |||
| 3f2ce41c2a | |||
| d74ece6596 | |||
| d77fa2108a | |||
| 219e627539 | |||
| 1885e675b2 | |||
| b6e187a0a7 | |||
| 5c7e4e4df2 | |||
| 1170be24c0 | |||
| e53963d51e | |||
| f93d789905 | |||
| 4dfc070891 | |||
| d5fa86b378 | |||
| 6d8d2e3078 | |||
| 5b3ad3a40c | |||
| 9b1d250cd7 | |||
| 13124b7903 | |||
| 86fac6bbc0 | |||
| 70d3b2507c | |||
| ca5632031c | |||
| 38c5e05d4c | |||
| 7928e69c60 | |||
| 899bae335e | |||
| 8e3d6c28f0 | |||
| ae98abe61d | |||
| 013c89e58d | |||
| dd4928c822 | |||
| 2dafadf949 | |||
| f0a97c4701 | |||
| ffa3cc881e | |||
| 3e46293efc | |||
| 8cda1aa4c7 | |||
| 17d31f35f3 | |||
| 64d341e307 | |||
| 554bb22f53 | |||
| fa3b0c070a | |||
| 18d284a4ea | |||
| a2ef22d41a | |||
| eaae5a5ccd | |||
| 5352e6ba59 | |||
| f4e6f8a415 | |||
| 324a7225ec | |||
| b549ad06d5 | |||
| 22b63af7fa | |||
| f470966d30 | |||
| 6608784709 | |||
| 6a98802e24 | |||
| 40d025ad4d | |||
| 49553a0e7e | |||
| 60c95c2e0e | |||
| 0a65c6009e | |||
| fba613f83c | |||
| 4aa071441b | |||
| 564827dd9c | |||
| c7ad1301c1 | |||
| dff2bfca76 | |||
| 08238b22d2 | |||
| 0ca764d6be | |||
| 0c5ddac9f5 | |||
| c08a3abf83 | |||
| eb3926e575 | |||
| 16b43ec31d | |||
| bef684b3fe | |||
| d8156a96ee | |||
| e0ab399a9c | |||
| ce86e0bf72 | |||
| 163f52a5c1 | |||
| 2fef6d4064 | |||
| c71a74762d | |||
| d2f94b502b | |||
| b100148f54 | |||
| 7e8afcd2a9 | |||
| 9ebfdfd049 | |||
| 4bd537bd96 | |||
| 2439c0ef68 | |||
| e03bf6e199 | |||
| e919473fa2 | |||
| 4098812556 | |||
| fdb9830fed | |||
| 45883436c5 | |||
| d1e892d449 | |||
| e42c1969a2 | |||
| 29dcca9725 | |||
| 46f7d358ed | |||
| 08802176cb | |||
| 00f4cab992 | |||
| b2ee40249a | |||
| a7d0384413 | |||
| 99346fe7b2 | |||
| 51b2a48894 | |||
| c9ac5980a5 | |||
| 17593f74c6 | |||
| 43d3e8cbff | |||
| ef75de4f55 | |||
| 3e1febab56 | |||
| 1fd3e86ed3 | |||
| 137dbac273 | |||
| 0182ea7b01 | |||
| 51a1e352bc | |||
| 188d310b42 | |||
| 2260de6adb | |||
| 9b8757acda | |||
| 4089ac0bc1 | |||
| 5787a384f9 | |||
| e5a5240f96 | |||
| d33fada0a1 | |||
| 9fba5d239d | |||
| 2c02116781 | |||
| 92711de4a1 | |||
| 7e7d023252 | |||
| f7ff7ae13b | |||
| 59b0a975f7 | |||
| d672b5dd90 | |||
| 8adef2adb8 | |||
| 9688731b3e | |||
| 64dece4f7e | |||
| 343754ba7f | |||
| 6ad727c728 | |||
| 49dabb35f0 | |||
| aa7a9661b9 | |||
| c34cb485bd | |||
| a5d9809db7 | |||
| 6c5a82cc9b | |||
| 72a62b678f | |||
| 770356d830 | |||
| 81ce0dd9b6 | |||
| 2e48ff0ca4 | |||
| 60d0c19256 | |||
| ebd1a89a58 | |||
| 4fd7d303bf | |||
| 0f30243725 | |||
| 0fb806bfda | |||
| 9c3d761d97 | |||
| 06ca411e03 | |||
| dc54082a42 | |||
| 3f29e0be86 | |||
| 2cec794483 | |||
| 49a3722a7e | |||
| 1af5d72819 | |||
| 23231dc6d7 | |||
| 46ce5f0989 | |||
| 3603c0386b | |||
| 6cbf32c386 | |||
| eb54fa2e3a | |||
| a7ff64fdbd | |||
| db3b0c8d08 | |||
| 25fef67c07 | |||
| 7951814f12 | |||
| 3a3839a461 | |||
| 7489fa657a | |||
| 0762d9311b | |||
| 57464c6cf0 | |||
| 8877bf88c0 | |||
| def9494dd3 | |||
| 5117847740 | |||
| 84f56dfc50 | |||
| 821dc5c639 | |||
| 0eefb438a6 | |||
| d396a35713 | |||
| 26e968f7c9 | |||
| 68e40d580f | |||
| 9e9d91b5a3 | |||
| 90502c3029 | |||
| a011588509 | |||
| 319dbf5a54 | |||
| 888abef7c0 | |||
| 58de9a3f0c | |||
| 57b518562e | |||
| cde46e6a5f | |||
| e88df26ed7 | |||
| 021f183157 | |||
| 66a191f494 | |||
| d8458662fd | |||
| a5d66a0249 | |||
| e4527aa5b3 | |||
| 6bae78a282 | |||
| 400c7f6443 | |||
| c34045e215 | |||
| 2addec5adf | |||
| 81d069cddf | |||
| a5b7e11964 | |||
| 4e69b5b9fb | |||
| 05478f54ae | |||
| b88bcff389 | |||
| a57de9715c | |||
| e4ac505928 | |||
| b32858cb88 | |||
| 11aabe0216 | |||
| 0f1aeccde0 | |||
| bdfc8082a2 | |||
| 1a7df89c47 | |||
| 6f9f791f02 | |||
| d6738b2b70 | |||
| 165d75a21f | |||
| f6441a9b4c | |||
| b501160efc | |||
| 1dff16a86e | |||
| 8ea2a698ce | |||
| 854084d819 | |||
| 112e037f4d | |||
| e0e911f9e7 | |||
| 269fa0f870 | |||
| 522bd4a597 | |||
| d48d4c0f21 | |||
| 74829b93ac | |||
| 4acb81a20d | |||
| 9fd0dd00cb | |||
| d7b26608df | |||
| a42eb2888e | |||
| 3bb985d0b6 | |||
| a842845685 | |||
| 8598d59ab4 | |||
| 1f668586f2 | |||
| bfebc67eb7 | |||
| b5a72aad05 | |||
| c859aeb75f | |||
| 27a3f2f08c | |||
| 98efbc2875 | |||
| e912c88993 | |||
| 550374ef6f | |||
| b85d271efe | |||
| ba746d03fa | |||
| 20803c67ed | |||
| 5dc9d4dca4 | |||
| 4bdd72152e | |||
| 8c94fc6e29 | |||
| 2b54d69b9e | |||
| 7ef3e68d16 | |||
| 822681bf74 | |||
| edd2f7aab5 |
@ -1,214 +0,0 @@
|
||||
package apicaller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
type ApiCaller interface {
|
||||
HasAuthority(authPath string) bool
|
||||
GetMyAuthority() []string
|
||||
}
|
||||
|
||||
type ApiCallerAuths interface {
|
||||
NewApiCaller(user string) ApiCaller
|
||||
NewApiCallerByServer() ApiCaller
|
||||
Update(newusers map[string]*map[string]bool) error
|
||||
Serialize() []byte
|
||||
}
|
||||
|
||||
type apiCallerAuths struct {
|
||||
sync.Mutex
|
||||
serialized unsafe.Pointer // *[]byte
|
||||
users map[string]*map[string]bool // email -> authoriries
|
||||
}
|
||||
|
||||
func (a *apiCallerAuths) Serialize() []byte {
|
||||
btptr := atomic.LoadPointer(&a.serialized)
|
||||
return *(*[]byte)(btptr)
|
||||
}
|
||||
|
||||
func (a *apiCallerAuths) getAuthority(email string) []string {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
|
||||
auths := a.users[email]
|
||||
if auths == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
var out []string
|
||||
for k, v := range *auths {
|
||||
if v {
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (a *apiCallerAuths) Update(newAuths map[string]*map[string]bool) error {
|
||||
src := map[string][]string{}
|
||||
for user, auths := range newAuths {
|
||||
for cat, has := range *auths {
|
||||
if has {
|
||||
arr := append(src[cat], user)
|
||||
src[cat] = arr
|
||||
} else if _, ok := src[cat]; !ok {
|
||||
src[cat] = []string{}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
|
||||
file, err := os.Create(userAuthsFileName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
enc := json.NewEncoder(file)
|
||||
err = enc.Encode(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
a.users = newAuths
|
||||
bt, _ := json.Marshal(newAuths)
|
||||
atomic.StorePointer(&a.serialized, unsafe.Pointer(&bt))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *apiCallerAuths) hasAuthority(email string, authPath string) bool {
|
||||
a.Lock()
|
||||
defer a.Unlock()
|
||||
|
||||
auths, ok := a.users[email]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
if (*auths)[authPath] {
|
||||
return true
|
||||
}
|
||||
|
||||
for k, v := range *auths {
|
||||
if strings.HasPrefix(k, authPath+"/") {
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
const userAuthsFileName = "userauths.json"
|
||||
|
||||
func NewApiCallerAuths() ApiCallerAuths {
|
||||
var out apiCallerAuths
|
||||
f, _ := os.Open(userAuthsFileName)
|
||||
if f == nil {
|
||||
emptyAuths := map[string][]string{
|
||||
"/admins": {"enter_first_admin_email@action2quare.com"},
|
||||
}
|
||||
newf, _ := os.Create(userAuthsFileName)
|
||||
if newf != nil {
|
||||
enc := json.NewEncoder(newf)
|
||||
enc.Encode(emptyAuths)
|
||||
newf.Close()
|
||||
|
||||
f, _ = os.Open(userAuthsFileName)
|
||||
}
|
||||
}
|
||||
|
||||
if f != nil {
|
||||
defer f.Close()
|
||||
|
||||
var src map[string][]string
|
||||
dec := json.NewDecoder(f)
|
||||
dec.Decode(&src)
|
||||
|
||||
compiled := make(map[string]*map[string]bool)
|
||||
|
||||
// 전체 유저 목록을 먼저 뽑고나서
|
||||
for _, users := range src {
|
||||
for _, user := range users {
|
||||
if _, ok := compiled[user]; !ok {
|
||||
compiled[user] = &map[string]bool{}
|
||||
}
|
||||
}
|
||||
}
|
||||
// 전체 유저한테 모든 카테고리를 설정한다.
|
||||
for _, auths := range compiled {
|
||||
for cat := range src {
|
||||
(*auths)[cat] = false
|
||||
}
|
||||
}
|
||||
// 이제 유저별 권한을 설정
|
||||
for category, users := range src {
|
||||
for _, user := range users {
|
||||
(*compiled[user])[category] = true
|
||||
}
|
||||
}
|
||||
|
||||
out = apiCallerAuths{
|
||||
users: compiled,
|
||||
}
|
||||
} else {
|
||||
|
||||
out = apiCallerAuths{
|
||||
users: map[string]*map[string]bool{},
|
||||
}
|
||||
}
|
||||
|
||||
marshaled, _ := json.Marshal(out.users)
|
||||
out.serialized = unsafe.Pointer(&marshaled)
|
||||
|
||||
return &out
|
||||
}
|
||||
|
||||
type apiCaller struct {
|
||||
userAuths *apiCallerAuths
|
||||
caller string
|
||||
}
|
||||
|
||||
func (a *apiCallerAuths) NewApiCaller(user string) ApiCaller {
|
||||
if len(user) == 0 {
|
||||
return nil
|
||||
}
|
||||
return &apiCaller{
|
||||
userAuths: a,
|
||||
caller: user,
|
||||
}
|
||||
}
|
||||
|
||||
func (a *apiCallerAuths) NewApiCallerByServer() ApiCaller {
|
||||
return &apiCaller{
|
||||
userAuths: a,
|
||||
caller: "",
|
||||
}
|
||||
}
|
||||
|
||||
func (ac apiCaller) callByServer() bool {
|
||||
return len(ac.caller) == 0
|
||||
}
|
||||
|
||||
func (ac apiCaller) HasAuthority(authPath string) bool {
|
||||
if ac.callByServer() {
|
||||
return true
|
||||
}
|
||||
|
||||
return ac.userAuths.hasAuthority(ac.caller, authPath)
|
||||
}
|
||||
|
||||
func (ac apiCaller) GetMyAuthority() []string {
|
||||
if !ac.callByServer() {
|
||||
return ac.userAuths.getAuthority(ac.caller)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@ -20,7 +20,6 @@ import (
|
||||
|
||||
type Authinfo struct {
|
||||
Accid primitive.ObjectID `bson:"_id,omitempty" json:"_id,omitempty"`
|
||||
ServiceCode string `bson:"code" json:"code"`
|
||||
Platform string
|
||||
Uid string
|
||||
Email string
|
||||
@ -30,7 +29,7 @@ type Authinfo struct {
|
||||
}
|
||||
|
||||
const (
|
||||
sessionSyncChannelName = "session-sync-channel2"
|
||||
sessionSyncChannelNamePrefix = "session-sync-channel2"
|
||||
)
|
||||
|
||||
type AuthinfoCell interface {
|
||||
@ -99,6 +98,8 @@ func (ac *redisAuthCell) ToBytes() []byte {
|
||||
func newAuthCollectionWithRedis(redisClient *redis.Client, subctx context.Context, maingateURL string, apiToken string) *AuthCollection {
|
||||
sessionTTL := int64(3600)
|
||||
ac := MakeAuthCollection(time.Duration(sessionTTL * int64(time.Second)))
|
||||
|
||||
sessionSyncChannelName := fmt.Sprintf("%s-%d", sessionSyncChannelNamePrefix, redisClient.Options().DB)
|
||||
pubsub := redisClient.Subscribe(subctx, sessionSyncChannelName)
|
||||
ctx, cancel := context.WithCancel(context.TODO())
|
||||
go func(ctx context.Context, sub *redis.PubSub, authCache *AuthCollection) {
|
||||
@ -205,7 +206,7 @@ func (acg *AuthCollectionGlobal) Reload(context context.Context) error {
|
||||
for r, url := range config.RegionStorage {
|
||||
if _, ok := oldval[r]; !ok {
|
||||
// 새로 생겼네
|
||||
redisClient, err := NewRedisClient(url.Redis.URL, url.Redis.Offset["session"])
|
||||
redisClient, err := NewRedisClient(url.Redis["session"])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -228,7 +229,7 @@ func NewAuthCollectionGlobal(context context.Context, apiToken string) (AuthColl
|
||||
|
||||
output := make(map[string]*AuthCollection)
|
||||
for region, url := range config.RegionStorage {
|
||||
redisClient, err := NewRedisClient(url.Redis.URL, url.Redis.Offset["session"])
|
||||
redisClient, err := NewRedisClient(url.Redis["session"])
|
||||
if err != nil {
|
||||
return AuthCollectionGlobal{}, err
|
||||
}
|
||||
|
||||
@ -18,8 +18,6 @@ import (
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/flagx"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
var linkupdate = flagx.String("updatelink", "", "")
|
||||
@ -239,17 +237,3 @@ func ReplyUpdateComplete() {
|
||||
|
||||
// return (uint32(b[0]) << 0) | (uint32(b[1]) << 8) | (uint32(b[2]) << 16) | (uint32(b[3]) << 24)
|
||||
// }
|
||||
|
||||
type BsonMarshaler[T any] struct {
|
||||
val T
|
||||
}
|
||||
|
||||
func NewBsonMarshaler[T any](val T) *BsonMarshaler[T] {
|
||||
return &BsonMarshaler[T]{
|
||||
val: val,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *BsonMarshaler[T]) MarshalBinary() (data []byte, err error) {
|
||||
return bson.Marshal(m.val)
|
||||
}
|
||||
|
||||
59
coupon/helper.go
Normal file
59
coupon/helper.go
Normal file
@ -0,0 +1,59 @@
|
||||
package coupon
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"math/rand"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func DisolveCouponCode(code string) (round string, key string) {
|
||||
var final []byte
|
||||
for _, n := range strings.Split(code, "-") {
|
||||
nb, err := hex.DecodeString(n)
|
||||
if err != nil {
|
||||
// 형식 오류
|
||||
return "", ""
|
||||
}
|
||||
final = append(final, nb...)
|
||||
}
|
||||
|
||||
if len(final) != 8 {
|
||||
// 형식 오류
|
||||
return "", ""
|
||||
}
|
||||
|
||||
uid := final[4:]
|
||||
left := binary.BigEndian.Uint16(uid[0:2])
|
||||
right := binary.BigEndian.Uint16(uid[2:4])
|
||||
|
||||
final = final[0:4]
|
||||
xor := binary.LittleEndian.Uint32(final)
|
||||
roundhashnum := xor ^ (uint32(left) * uint32(right))
|
||||
|
||||
roundhash := make([]byte, 4)
|
||||
binary.BigEndian.PutUint32(roundhash, roundhashnum)
|
||||
|
||||
round = hex.EncodeToString(roundhash)
|
||||
key = hex.EncodeToString(uid)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func MakeCouponRoundHash(name string) (hash string, roundNumber uint32) {
|
||||
m5 := md5.New()
|
||||
m5.Write([]byte(name))
|
||||
hashbt := m5.Sum(nil)
|
||||
|
||||
roundbt := make([]byte, 8)
|
||||
copy(roundbt, hashbt[:8])
|
||||
|
||||
roundseed := int64(binary.BigEndian.Uint64(roundbt))
|
||||
roundhash := make([]byte, 4)
|
||||
rand.New(rand.NewSource(roundseed)).Read(roundhash)
|
||||
roundNumber = binary.BigEndian.Uint32(roundhash)
|
||||
hash = hex.EncodeToString(roundhash)
|
||||
|
||||
return
|
||||
}
|
||||
45
go.mod
45
go.mod
@ -1,29 +1,62 @@
|
||||
module repositories.action2quare.com/ayo/gocommon
|
||||
|
||||
go 1.19
|
||||
go 1.22
|
||||
|
||||
replace repositories.action2quare.com/ayo/gocommon => ./
|
||||
toolchain go1.22.4
|
||||
|
||||
require (
|
||||
github.com/awa/go-iap v1.32.0
|
||||
github.com/go-redis/redis/v8 v8.11.5
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/gorilla/websocket v1.5.0
|
||||
github.com/pires/go-proxyproto v0.7.0
|
||||
github.com/prometheus/client_golang v1.17.0
|
||||
go.mongodb.org/mongo-driver v1.11.6
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d
|
||||
golang.org/x/text v0.3.7
|
||||
golang.org/x/crypto v0.18.0
|
||||
golang.org/x/text v0.14.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/cespare/xxhash/v2 v2.1.2 // indirect
|
||||
cloud.google.com/go/compute v1.23.3 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.2.3 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.2.0 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/go-logr/logr v1.3.0 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/golang-jwt/jwt/v4 v4.3.0 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/golang/snappy v0.0.1 // indirect
|
||||
github.com/google/s2a-go v0.1.7 // indirect
|
||||
github.com/google/uuid v1.5.0 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
|
||||
github.com/klauspost/compress v1.13.6 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe // indirect
|
||||
github.com/opensearch-project/opensearch-go/v4 v4.5.0 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 // indirect
|
||||
github.com/prometheus/common v0.44.0 // indirect
|
||||
github.com/prometheus/procfs v0.11.1 // indirect
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
|
||||
github.com/xdg-go/scram v1.1.1 // indirect
|
||||
github.com/xdg-go/stringprep v1.0.3 // indirect
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 // indirect
|
||||
go.opentelemetry.io/otel v1.21.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.21.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.21.0 // indirect
|
||||
golang.org/x/net v0.20.0 // indirect
|
||||
golang.org/x/oauth2 v0.16.0 // indirect
|
||||
golang.org/x/sync v0.6.0 // indirect
|
||||
golang.org/x/sys v0.16.0 // indirect
|
||||
google.golang.org/api v0.157.0 // indirect
|
||||
google.golang.org/appengine v1.6.8 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac // indirect
|
||||
google.golang.org/grpc v1.60.1 // indirect
|
||||
google.golang.org/protobuf v1.32.0 // indirect
|
||||
)
|
||||
|
||||
193
go.sum
193
go.sum
@ -1,42 +1,121 @@
|
||||
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
|
||||
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
cloud.google.com/go/compute v1.23.3 h1:6sVlXXBmbd7jNX0Ipq0trII3e4n1/MsADLK6a+aiVlk=
|
||||
cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI=
|
||||
cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
|
||||
cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/awa/go-iap v1.32.0 h1:1rm/iz/gqU5sOQTTEwCD8IV2dRnjxeqPt+4aKr31sVg=
|
||||
github.com/awa/go-iap v1.32.0/go.mod h1:roSGnO9xHwxg8BKKnDY2gsjO9XskLZVay6+0+RY59Lg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
|
||||
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY=
|
||||
github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
|
||||
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible h1:IfV12K8xAKAnZqdXVzCZ+TOjboZ2keLg81eXfW3O+oY=
|
||||
github.com/golang-jwt/jwt v3.2.2+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I=
|
||||
github.com/golang-jwt/jwt/v4 v4.3.0 h1:kHL1vqdqWNfATmA0FNMdmZNMyZI1U6O31X4rlIPoBog=
|
||||
github.com/golang-jwt/jwt/v4 v4.3.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
|
||||
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
|
||||
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
|
||||
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
|
||||
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
|
||||
github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4=
|
||||
github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
|
||||
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
|
||||
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
|
||||
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
|
||||
github.com/googleapis/gax-go/v2 v2.12.0 h1:A+gCJKdRfqXkr+BIRGtZLibNXf0m1f9E4HG56etFpas=
|
||||
github.com/googleapis/gax-go/v2 v2.12.0/go.mod h1:y+aIqrI5eb1YGMVJfuV3185Ts/D7qKpsEkdD5+I6QGU=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQxcgc=
|
||||
github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe h1:iruDEfMl2E6fbMZ9s0scYfZQ84/6SPL6zC8ACM2oIL0=
|
||||
github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=
|
||||
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
|
||||
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
|
||||
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
|
||||
github.com/opensearch-project/opensearch-go/v4 v4.5.0 h1:26XckmmF6MhlXt91Bu1yY6R51jy1Ns/C3XgIfvyeTRo=
|
||||
github.com/opensearch-project/opensearch-go/v4 v4.5.0/go.mod h1:VmFc7dqOEM3ZtLhrpleOzeq+cqUgNabqQG5gX0xId64=
|
||||
github.com/pires/go-proxyproto v0.7.0 h1:IukmRewDQFWC7kfnb66CSomk2q/seBuilHBYFwyq0Hs=
|
||||
github.com/pires/go-proxyproto v0.7.0/go.mod h1:Vz/1JPY/OACxWGQNIRY2BeyDmpoaWmEP40O9LbuiFR4=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.17.0 h1:rl2sfwZMtSthVU752MqfjQozy7blglC+1SOtjMAMh+Q=
|
||||
github.com/prometheus/client_golang v1.17.0/go.mod h1:VeL+gMmOAxkS2IqfCq0ZmHSL+LjWfWDUmp1mBz9JgUY=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16 h1:v7DLqVdK4VrYkVD5diGdl4sxJurKJEMnODWRJlxV9oM=
|
||||
github.com/prometheus/client_model v0.4.1-0.20230718164431-9a2bf3000d16/go.mod h1:oMQmHW1/JoDwqLtg57MGgP/Fb1CJEYF2imWWhWtMkYU=
|
||||
github.com/prometheus/common v0.44.0 h1:+5BrQJwiBB9xsMygAB3TNvpQKOwlkc25LbISbrdOOfY=
|
||||
github.com/prometheus/common v0.44.0/go.mod h1:ofAIvZbQ1e/nugmZGz4/qCb9Ap1VoSTIO7x0VV9VvuY=
|
||||
github.com/prometheus/procfs v0.11.1 h1:xRC8Iq1yyca5ypa9n1EZnWZkt7dwcoRPQwX/5gwaUuI=
|
||||
github.com/prometheus/procfs v0.11.1/go.mod h1:eesXgaPo1q7lBpVMoMy0ZOFTth9hBn4W/y0/p/ScXhY=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/tidwall/pretty v1.0.0 h1:HsD+QiTn7sK6flMKIvNmpqz1qrpP3Ps6jOKIKMooyg4=
|
||||
github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk=
|
||||
github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c=
|
||||
@ -47,25 +126,115 @@ github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCO
|
||||
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
|
||||
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
|
||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||
go.mongodb.org/mongo-driver v1.11.6 h1:XM7G6PjiGAO5betLF13BIa5TlLUUE3uJ/2Ox3Lz1K+o=
|
||||
go.mongodb.org/mongo-driver v1.11.6/go.mod h1:G9TgswdsWjX4tmDA5zfs2+6AEPpYJwqblyjsfuh8oXY=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY=
|
||||
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1 h1:aFJWCqJMNjENlcleuuOkGAPH82y0yULBScfXcIEdS24=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.46.1/go.mod h1:sEGXWArGqc3tVa+ekntsN65DmVbVeW+7lTKTjZF3/Fo=
|
||||
go.opentelemetry.io/otel v1.21.0 h1:hzLeKBZEL7Okw2mGzZ0cc4k/A7Fta0uoPgaJCr8fsFc=
|
||||
go.opentelemetry.io/otel v1.21.0/go.mod h1:QZzNPQPm1zLX4gZK4cMi+71eaorMSGT3A4znnUvNNEo=
|
||||
go.opentelemetry.io/otel/metric v1.21.0 h1:tlYWfeo+Bocx5kLEloTjbcDwBuELRrIFxwdQ36PlJu4=
|
||||
go.opentelemetry.io/otel/metric v1.21.0/go.mod h1:o1p3CA8nNHW8j5yuQLdc1eeqEaPfzug24uvsyIEJRWM=
|
||||
go.opentelemetry.io/otel/trace v1.21.0 h1:WD9i5gzvoUPuXIXH24ZNBudiarZDKuekPqi/E8fpfLc=
|
||||
go.opentelemetry.io/otel/trace v1.21.0/go.mod h1:LGbsEB0f9LGjN+OZaQQ26sohbOmiMR+BaslueVtS/qQ=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE=
|
||||
golang.org/x/crypto v0.18.0 h1:PGVlW0xEltQnzFZ55hkuX5+KLyrMYhHld1YHO4AKcdc=
|
||||
golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ=
|
||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||
golang.org/x/net v0.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo=
|
||||
golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/oauth2 v0.16.0 h1:aDkGMBSYxElaoP81NpoUoz2oo2R2wHdZpGToUxfyQrQ=
|
||||
golang.org/x/oauth2 v0.16.0/go.mod h1:hqZ+0LWXsiVoZpeld6jVt06P3adbS2Uu911W1SsJv2o=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
|
||||
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM=
|
||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU=
|
||||
golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/api v0.157.0 h1:ORAeqmbrrozeyw5NjnMxh7peHO0UzV4wWYSwZeCUb20=
|
||||
google.golang.org/api v0.157.0/go.mod h1:+z4v4ufbZ1WEpld6yMGHyggs+PmAHiaLNj5ytP3N01g=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/appengine v1.6.8 h1:IhEN5q69dyKagZPYMSdIjS2HqprW324FRQZJcGqPAsM=
|
||||
google.golang.org/appengine v1.6.8/go.mod h1:1jJ3jBArFh5pcgW8gCtRJnepW8FzD1V44FJffLiz/Ds=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
|
||||
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
|
||||
google.golang.org/genproto v0.0.0-20240102182953-50ed04b92917 h1:nz5NESFLZbJGPFxDT/HCn+V1mZ8JGNoY4nUpmW/Y2eg=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20240102182953-50ed04b92917 h1:rcS6EyEaoCO52hQDupoSfrxI3R6C2Tq741is7X8OvnM=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac h1:nUQEQmH/csSvFECKYRv6HWEyypysidKl2I6Qpsglq/0=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240116215550-a9fa1716bcac/go.mod h1:daQN87bsDqDoe316QbbvX60nMoJQa4r6Ds0ZuoAe5yA=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
|
||||
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
|
||||
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
|
||||
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
|
||||
google.golang.org/grpc v1.60.1 h1:26+wFr+cNqSGFcOXcabYC0lUVJVRa2Sb2ortSK7VrEU=
|
||||
google.golang.org/grpc v1.60.1/go.mod h1:OlCHIeLYqSSsLi6i49B5QGdzaMZK9+M7LXN2FKz4eGM=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
|
||||
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
|
||||
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
|
||||
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
|
||||
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
|
||||
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
|
||||
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
|
||||
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
@ -73,3 +242,5 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
||||
110
iap/galaxystore.go
Normal file
110
iap/galaxystore.go
Normal file
@ -0,0 +1,110 @@
|
||||
package iap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type GalaxyStoreIAPVerifier struct {
|
||||
ItemId string `json:"itemId"`
|
||||
PaymentId string `json:"paymentId"`
|
||||
OrderId string `json:"orderId"`
|
||||
PackageName string `json:"packageName"`
|
||||
ItemName string `json:"itemName"`
|
||||
ItemDesc string `json:"itemDesc"`
|
||||
PurchaseDate string `json:"purchaseDate"`
|
||||
PaymentAmount string `json:"paymentAmount"`
|
||||
Status string `json:"status"`
|
||||
PaymentMethod string `json:"paymentMethod"`
|
||||
Mode string `json:"mode"`
|
||||
ConsumeYN string `json:"consumeYN"`
|
||||
ConsumeDate string `json:"consumeDate"`
|
||||
ConsumeDeviceModel string `json:"consumeDeviceModel"`
|
||||
PassThroughParam string `json:"passThroughParam"`
|
||||
CurrencyCode string `json:"currencyCode"`
|
||||
CurrencyUnit string `json:"currencyUnit"`
|
||||
VerificationLog string
|
||||
}
|
||||
|
||||
func (verifer *GalaxyStoreIAPVerifier) Verify(purchaseId string, paymentId string, developerPayload string, itemId string, packageName string) (bool, error) {
|
||||
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("GET", "https://iap.samsungapps.com/iap/v6/receipt?purchaseID="+purchaseId, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
json.Unmarshal(body, verifer)
|
||||
|
||||
verifer.VerificationLog = string(body)
|
||||
|
||||
if verifer.Status != "success" {
|
||||
return false, errors.New("Status is wrong:" + verifer.Status)
|
||||
}
|
||||
|
||||
if verifer.ItemId != itemId {
|
||||
return false, errors.New("itemId is different")
|
||||
}
|
||||
|
||||
if verifer.PackageName != packageName {
|
||||
return false, errors.New("packageName is different")
|
||||
}
|
||||
|
||||
if !strings.EqualFold(verifer.PassThroughParam, developerPayload) {
|
||||
return false, errors.New("developerPayload is different : " + verifer.PassThroughParam + "/" + developerPayload)
|
||||
}
|
||||
|
||||
if verifer.PaymentId != paymentId {
|
||||
return false, errors.New("paymentId is different")
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Owned Item - mItemId: kd_currency_gold_75
|
||||
// Owned Item - mItemName: Gold x75
|
||||
// Owned Item - mItemPrice: 1300.000000
|
||||
// Owned Item - mItemPriceString: ₩1,300
|
||||
// Owned Item - mCurrencyUnit: ₩
|
||||
// Owned Item - mCurrencyCode: KRW
|
||||
// Owned Item - mItemDesc: 75 Gold
|
||||
// Owned Item - mPaymentId: TPMTID20240208KR32371566
|
||||
// Owned Item - mPurchaseId: 34c50c9677e8e837e7b7a6eaac37a385fb7e4b36437820825bc7d824647c6aa7
|
||||
// Owned Item - mPurchaseDate: -2147483648
|
||||
// Owned Item - mPassThroughParam: testpayload
|
||||
|
||||
// {
|
||||
// "itemId": "kd_currency_gold_75",
|
||||
// "paymentId": "TPMTID20240208KR32367386",
|
||||
// "orderId": "P20240208KR32367386",
|
||||
// "packageName": "com.yjmgames.kingdom.gal",
|
||||
// "itemName": "Gold x75",
|
||||
// "itemDesc": "75 Gold",
|
||||
// "purchaseDate": "2024-02-08 02:33:24",
|
||||
// "paymentAmount": "1300.0",
|
||||
// "status": "success",
|
||||
// "paymentMethod": "Credit Card",
|
||||
// "mode": "TEST",
|
||||
// "consumeYN": "Y",
|
||||
// "consumeDate": "2024-02-08 02:52:10",
|
||||
// "consumeDeviceModel": "SM-S918N",
|
||||
// "passThroughParam": "testpayload",
|
||||
// "currencyCode": "KRW",
|
||||
// "currencyUnit": "₩"
|
||||
// }
|
||||
173
iap/iap.go
Normal file
173
iap/iap.go
Normal file
@ -0,0 +1,173 @@
|
||||
package iap
|
||||
|
||||
import (
|
||||
"context"
|
||||
b64 "encoding/base64"
|
||||
"encoding/json"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
|
||||
"github.com/awa/go-iap/appstore/api"
|
||||
"github.com/awa/go-iap/playstore"
|
||||
)
|
||||
|
||||
var PlayStorePublicKey string
|
||||
var PlayStorePackageName string
|
||||
var PlayStoreClient *playstore.Client
|
||||
|
||||
type PlayStoreReceiptInfo struct {
|
||||
OrderId string `json:"orderId"`
|
||||
PackageName string `json:"packageName"`
|
||||
ProductId string `json:"productId"`
|
||||
PurchaseTime int `json:"purchaseTime"`
|
||||
PurchaseState int `json:"purchaseState"`
|
||||
PurchaseToken string `json:"purchaseToken"`
|
||||
Quantity int `json:"quantity"`
|
||||
Acknowledged bool `json:"acknowledged"`
|
||||
}
|
||||
|
||||
func PlayStoreInit(packageName string, publickey string) {
|
||||
jsonKey, err := ioutil.ReadFile("playstore-iap-kingdom.json")
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
return
|
||||
}
|
||||
|
||||
PlayStoreClient, err = playstore.New(jsonKey)
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
return
|
||||
}
|
||||
|
||||
PlayStorePublicKey = publickey
|
||||
PlayStorePackageName = packageName
|
||||
}
|
||||
|
||||
func PlayStoreVerifyReceipt(receptData string, signature string) (isVerified bool, receiptInfo PlayStoreReceiptInfo) {
|
||||
var info PlayStoreReceiptInfo
|
||||
uDec, _ := b64.URLEncoding.DecodeString(receptData)
|
||||
|
||||
bOk, err := playstore.VerifySignature(PlayStorePublicKey, []byte(uDec), signature)
|
||||
if bOk == false || err != nil {
|
||||
logger.Println("playstore - VerifySignature fail :" + err.Error())
|
||||
return bOk, info
|
||||
}
|
||||
json.Unmarshal(uDec, &info)
|
||||
return bOk, info
|
||||
}
|
||||
|
||||
func PlayStoreVerifyProduct(info PlayStoreReceiptInfo) (bool, int, int) {
|
||||
|
||||
productPurchases, err := PlayStoreClient.VerifyProduct(context.Background(), PlayStorePackageName, info.ProductId, info.PurchaseToken)
|
||||
if err != nil {
|
||||
logger.Println("playstore - PlayStoreVerifyProduct fail :" + err.Error())
|
||||
return false, -1, -1
|
||||
}
|
||||
// fmt.Println(productPurchases)
|
||||
// fmt.Println("================")
|
||||
// fmt.Println(productPurchases.PurchaseState)
|
||||
// fmt.Println(productPurchases.ConsumptionState)
|
||||
// fmt.Println("================")
|
||||
return true, int(productPurchases.PurchaseState), int(productPurchases.ConsumptionState)
|
||||
}
|
||||
|
||||
func PlayStoreConsumeProduct(info PlayStoreReceiptInfo) bool {
|
||||
|
||||
err := PlayStoreClient.ConsumeProduct(context.Background(), PlayStorePackageName, info.ProductId, info.PurchaseToken)
|
||||
if err != nil {
|
||||
logger.Error("playstore - PlayStoreConsumeProduct fail :" + err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var AppStoreClient *api.StoreClient
|
||||
|
||||
func AppStoreInit(keyPath string, configFilePath string) {
|
||||
keyContentBytes, err := os.ReadFile(keyPath)
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
return
|
||||
}
|
||||
configBytes, err := os.ReadFile(configFilePath)
|
||||
if err != nil {
|
||||
logger.Fatal(err)
|
||||
return
|
||||
}
|
||||
|
||||
var configMap map[string]any
|
||||
err = json.Unmarshal(configBytes, &configMap)
|
||||
|
||||
config := &api.StoreConfig{
|
||||
KeyContent: keyContentBytes,
|
||||
KeyID: configMap["KeyID"].(string),
|
||||
BundleID: configMap["BundleID"].(string),
|
||||
Issuer: configMap["Issuer"].(string),
|
||||
Sandbox: configMap["Sandbox"].(bool),
|
||||
}
|
||||
|
||||
AppStoreClient = api.NewStoreClient(config)
|
||||
|
||||
if config.Sandbox {
|
||||
logger.Println("IPA - Appstore : Use Sandbox")
|
||||
} else {
|
||||
logger.Println("IPA - Appstore : Normal")
|
||||
}
|
||||
}
|
||||
|
||||
func AppStoreVerifyReceipt(transactionId string) (bool, *api.JWSTransaction) {
|
||||
res, err := AppStoreClient.GetTransactionInfo(context.Background(), transactionId)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
transaction, err := AppStoreClient.ParseSignedTransaction(res.SignedTransactionInfo)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if transaction.TransactionID != transactionId {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if len(transaction.OriginalTransactionId) == 0 {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return true, transaction
|
||||
}
|
||||
|
||||
func AppStoreConsumeProduct(transaction *api.JWSTransaction) bool {
|
||||
//https://developer.apple.com/documentation/appstoreserverapi/consumptionrequest
|
||||
consumeReqBody := api.ConsumptionRequestBody{
|
||||
AccountTenure: 0,
|
||||
AppAccountToken: transaction.AppAccountToken,
|
||||
ConsumptionStatus: 3,
|
||||
CustomerConsented: true,
|
||||
DeliveryStatus: 0,
|
||||
LifetimeDollarsPurchased: 0,
|
||||
LifetimeDollarsRefunded: 0,
|
||||
Platform: 1,
|
||||
PlayTime: 0,
|
||||
SampleContentProvided: false,
|
||||
UserStatus: 1,
|
||||
}
|
||||
statusCode, err := AppStoreClient.SendConsumptionInfo(context.Background(), transaction.OriginalTransactionId, consumeReqBody)
|
||||
|
||||
if statusCode != http.StatusAccepted {
|
||||
return false
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
250
iap/onestore.go
Normal file
250
iap/onestore.go
Normal file
@ -0,0 +1,250 @@
|
||||
package iap
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
// Ref https://onestore-dev.gitbook.io/dev/tools/tools/v21/06.-api-api-v7#accesstoken
|
||||
const shouldGenerateAccessTokenSec = 600
|
||||
|
||||
type OneStoreIAPVerificationInfo struct {
|
||||
ConsumptionState int `json:"consumptionState"`
|
||||
DeveloperPayload string `json:"developerPayload"`
|
||||
PurchaseState int `json:"purchaseState"`
|
||||
PurchaseTime int64 `json:"purchaseTime"`
|
||||
PurchaseId string `json:"purchaseId"`
|
||||
AcknowledgeState int `json:"acknowledgeState"`
|
||||
Quantity int `json:"quantity"`
|
||||
}
|
||||
|
||||
type OneStoreIAPClientPurcharinfo struct {
|
||||
OrderId string `json:"orderId"`
|
||||
PackageName string `json:"packageName"`
|
||||
ProductId string `json:"productId"`
|
||||
PurchaseTime int64 `json:"purchaseTime"`
|
||||
PurchaseId string `json:"purchaseId"`
|
||||
PurchaseToken string `json:"purchaseToken"`
|
||||
DeveloperPayload string `json:"developerPayload"`
|
||||
Quantity int `json:"quantity"`
|
||||
}
|
||||
|
||||
type OneStoreConfig struct {
|
||||
OneClientID string
|
||||
OneClientSecret string
|
||||
}
|
||||
|
||||
type OneStoreTokenData struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
TokenType string `json:"token_type,omitempty"`
|
||||
ClientId string `json:"client_id,omitempty"`
|
||||
ExpiresIn int `json:"expires_in,omitempty"`
|
||||
Scope string `json:"scope,omitempty"`
|
||||
Expiry time.Time
|
||||
}
|
||||
|
||||
func (s *OnestoreAccessToken) HostURL() string {
|
||||
if s.isSandBox {
|
||||
//-- Sandbox
|
||||
return "https://sbpp.onestore.co.kr"
|
||||
|
||||
} else {
|
||||
//-- RealURL
|
||||
return "https://iap-apis.onestore.net"
|
||||
}
|
||||
}
|
||||
|
||||
func (s *OnestoreAccessToken) GenerateNewToken() error {
|
||||
var newToken OneStoreTokenData
|
||||
|
||||
//==
|
||||
HostURL := s.HostURL()
|
||||
data := []byte("grant_type=client_credentials&client_id=" + s.config.OneClientID + "&client_secret=" + s.config.OneClientSecret)
|
||||
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("POST", HostURL+"/v7/oauth/token", bytes.NewBuffer(data))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Add("x-market-code", s.marketCode)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
json.Unmarshal(body, &newToken)
|
||||
|
||||
newExpiredSec := (newToken.ExpiresIn - shouldGenerateAccessTokenSec)
|
||||
if newExpiredSec < 0 {
|
||||
newExpiredSec = 0
|
||||
}
|
||||
newToken.Expiry = time.Now().Round(0).Add(time.Duration(newExpiredSec) * time.Second)
|
||||
s.data = &newToken
|
||||
logger.Println("IAP - OneStore : Generate Access Token :", s.data)
|
||||
return nil
|
||||
}
|
||||
|
||||
type OnestoreAccessToken struct {
|
||||
mu sync.Mutex // guards t
|
||||
data *OneStoreTokenData
|
||||
|
||||
marketCode string
|
||||
isSandBox bool
|
||||
config *OneStoreConfig
|
||||
}
|
||||
|
||||
func (t *OnestoreAccessToken) Valid() bool {
|
||||
return t != nil && t.data != nil && t.data.AccessToken != "" && !t.expired()
|
||||
}
|
||||
|
||||
func (t *OnestoreAccessToken) expired() bool {
|
||||
return t.data.Expiry.Before(time.Now())
|
||||
}
|
||||
|
||||
func (s *OnestoreAccessToken) Token() (string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.Valid() {
|
||||
return s.data.AccessToken, nil
|
||||
}
|
||||
//== Expire 되면 새로 얻어 오자..
|
||||
err := s.GenerateNewToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.data.AccessToken, nil
|
||||
}
|
||||
|
||||
type OnestoreIAPVerifier struct {
|
||||
config OneStoreConfig
|
||||
SandBox_OnestoreAccessToken_MKT_ONE OnestoreAccessToken
|
||||
SandBox_OnestoreAccessToken_MKT_GLB OnestoreAccessToken
|
||||
Live_OnestoreAccessToken_MKT_ONE OnestoreAccessToken
|
||||
Live_OnestoreAccessToken_MKT_GLB OnestoreAccessToken
|
||||
}
|
||||
|
||||
func (s *OnestoreIAPVerifier) Init(clientId string, clientSecret string) {
|
||||
s.config.OneClientID = clientId
|
||||
s.config.OneClientSecret = clientSecret
|
||||
s.SandBox_OnestoreAccessToken_MKT_ONE.marketCode = "MKT_ONE"
|
||||
s.SandBox_OnestoreAccessToken_MKT_GLB.marketCode = "MKT_GLB"
|
||||
s.Live_OnestoreAccessToken_MKT_ONE.marketCode = "MKT_ONE"
|
||||
s.Live_OnestoreAccessToken_MKT_GLB.marketCode = "MKT_GLB"
|
||||
s.SandBox_OnestoreAccessToken_MKT_ONE.isSandBox = true
|
||||
s.SandBox_OnestoreAccessToken_MKT_GLB.isSandBox = true
|
||||
s.Live_OnestoreAccessToken_MKT_ONE.isSandBox = false
|
||||
s.Live_OnestoreAccessToken_MKT_GLB.isSandBox = false
|
||||
s.SandBox_OnestoreAccessToken_MKT_ONE.config = &s.config
|
||||
s.SandBox_OnestoreAccessToken_MKT_GLB.config = &s.config
|
||||
s.Live_OnestoreAccessToken_MKT_ONE.config = &s.config
|
||||
s.Live_OnestoreAccessToken_MKT_GLB.config = &s.config
|
||||
}
|
||||
|
||||
func (s *OnestoreIAPVerifier) Verify(marketCode string, isSandBox bool, packageName string, clientInfo OneStoreIAPClientPurcharinfo) (bool, error) {
|
||||
var accesstoken string
|
||||
|
||||
if marketCode != "MKT_ONE" && marketCode != "MKT_GLB" {
|
||||
return false, errors.New("marketCode is wrong")
|
||||
}
|
||||
|
||||
if clientInfo.ProductId == "" {
|
||||
return false, errors.New("productId is empty")
|
||||
}
|
||||
|
||||
if clientInfo.PurchaseToken == "" {
|
||||
return false, errors.New("purchaseToken is empty")
|
||||
}
|
||||
|
||||
if packageName != clientInfo.PackageName {
|
||||
return false, errors.New("packageName is wrong")
|
||||
}
|
||||
|
||||
var err error
|
||||
var HostURL string
|
||||
if marketCode == "MKT_ONE" {
|
||||
if isSandBox {
|
||||
accesstoken, err = s.SandBox_OnestoreAccessToken_MKT_ONE.Token()
|
||||
HostURL = s.SandBox_OnestoreAccessToken_MKT_ONE.HostURL()
|
||||
} else {
|
||||
accesstoken, err = s.Live_OnestoreAccessToken_MKT_ONE.Token()
|
||||
HostURL = s.Live_OnestoreAccessToken_MKT_ONE.HostURL()
|
||||
}
|
||||
} else {
|
||||
if isSandBox {
|
||||
accesstoken, err = s.SandBox_OnestoreAccessToken_MKT_GLB.Token()
|
||||
HostURL = s.SandBox_OnestoreAccessToken_MKT_GLB.HostURL()
|
||||
} else {
|
||||
accesstoken, err = s.Live_OnestoreAccessToken_MKT_GLB.Token()
|
||||
HostURL = s.Live_OnestoreAccessToken_MKT_GLB.HostURL()
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("GET", HostURL+"/v7/apps/"+s.config.OneClientID+"/purchases/inapp/products/"+clientInfo.ProductId+"/"+clientInfo.PurchaseToken, nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
req.Header.Add("Authorization", "Bearer "+accesstoken)
|
||||
req.Header.Add("Content-Type", "application/json")
|
||||
req.Header.Add("x-market-code", marketCode)
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
var verificatioinfo OneStoreIAPVerificationInfo
|
||||
json.Unmarshal(body, &verificatioinfo)
|
||||
|
||||
// fmt.Println("================")
|
||||
// fmt.Println(string(body))
|
||||
// fmt.Println("================")
|
||||
|
||||
if verificatioinfo.PurchaseState != 0 {
|
||||
return false, errors.New("canceled payment")
|
||||
}
|
||||
|
||||
if !strings.EqualFold(clientInfo.DeveloperPayload, verificatioinfo.DeveloperPayload) {
|
||||
return false, errors.New("developerPayload is wrong :" + clientInfo.DeveloperPayload + "/" + verificatioinfo.DeveloperPayload)
|
||||
}
|
||||
|
||||
if clientInfo.PurchaseId != verificatioinfo.PurchaseId {
|
||||
return false, errors.New("purchaseId is wrong")
|
||||
}
|
||||
|
||||
if clientInfo.PurchaseTime != verificatioinfo.PurchaseTime {
|
||||
return false, errors.New("purchaseTime is wrong")
|
||||
}
|
||||
|
||||
if clientInfo.Quantity != verificatioinfo.Quantity {
|
||||
return false, errors.New("quantity is wrong")
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
@ -16,7 +16,7 @@ var txSetArgs redis.SetArgs = redis.SetArgs{
|
||||
}
|
||||
|
||||
type LockerWithRedis struct {
|
||||
key string
|
||||
locked_key string
|
||||
}
|
||||
|
||||
var ErrTransactionLocked = errors.New("transaction is already locked")
|
||||
@ -34,10 +34,10 @@ func (locker *LockerWithRedis) Lock(rc *redis.Client, key string) error {
|
||||
return ErrTransactionLocked
|
||||
}
|
||||
|
||||
locker.key = key
|
||||
locker.locked_key = key
|
||||
return nil
|
||||
}
|
||||
|
||||
func (locker *LockerWithRedis) Unlock(rc *redis.Client) {
|
||||
rc.Del(context.Background(), locker.key).Result()
|
||||
rc.Del(context.Background(), locker.locked_key).Result()
|
||||
}
|
||||
|
||||
144
logger/logger.go
144
logger/logger.go
@ -1,56 +1,41 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/flagx"
|
||||
)
|
||||
|
||||
var stdlogger *log.Logger
|
||||
var errlogger *log.Logger
|
||||
var _ = flag.Bool("logfile", false, "")
|
||||
var _ = flagx.Int("logprefix", 3, "0 : no_prefix, 1 : date, 2 : time, 3 : datetime")
|
||||
|
||||
func init() {
|
||||
binpath, _ := os.Executable()
|
||||
binname := path.Base(strings.ReplaceAll(binpath, "\\", "/"))
|
||||
|
||||
var outWriter io.Writer
|
||||
var errWriter io.Writer
|
||||
outWriter = os.Stdout
|
||||
errWriter = os.Stderr
|
||||
outWriter := os.Stdout
|
||||
|
||||
args := os.Args
|
||||
useLogFile := false
|
||||
logprefix := 3
|
||||
for _, arg := range args {
|
||||
if arg == "-logfile" {
|
||||
useLogFile = true
|
||||
if strings.HasPrefix(arg, "-logprefix=") {
|
||||
logprefix, _ = strconv.Atoi(arg[11:])
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if useLogFile {
|
||||
ext := path.Ext(binname)
|
||||
if len(ext) > 0 {
|
||||
binname = binname[:len(binname)-len(ext)]
|
||||
}
|
||||
pid := fmt.Sprintf("[%d]", os.Getpid())
|
||||
outWriter.Write([]byte(strings.Join(append([]string{pid, binpath}, args...), " ")))
|
||||
|
||||
logFile, err := os.Create(fmt.Sprintf("%s.log", binname))
|
||||
if err != nil {
|
||||
os.Stdout.Write([]byte(err.Error()))
|
||||
panic(err)
|
||||
}
|
||||
|
||||
outWriter = io.MultiWriter(outWriter, logFile)
|
||||
errWriter = io.MultiWriter(errWriter, logFile)
|
||||
if logprefix < 4 {
|
||||
stdlogger = log.New(outWriter, "", logprefix)
|
||||
} else {
|
||||
stdlogger = log.New(outWriter, "", log.LstdFlags)
|
||||
}
|
||||
|
||||
stdlogger = log.New(outWriter, "", log.LstdFlags)
|
||||
errlogger = log.New(errWriter, "", log.LstdFlags)
|
||||
}
|
||||
|
||||
func Println(v ...interface{}) {
|
||||
@ -62,42 +47,113 @@ func Printf(format string, v ...interface{}) {
|
||||
}
|
||||
|
||||
func Error(v ...interface{}) {
|
||||
errlogger.Output(2, fmt.Sprintln(v...))
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, fmt.Sprintln(v...))
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
}
|
||||
|
||||
func Errorf(format string, v ...interface{}) {
|
||||
errlogger.Output(2, fmt.Sprintf(format, v...))
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, fmt.Sprintf(format, v...))
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
}
|
||||
|
||||
func Fatal(v ...interface{}) {
|
||||
errlogger.Output(2, fmt.Sprint(v...))
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, fmt.Sprint(v...))
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
os.Exit(1)
|
||||
}
|
||||
func Fatalln(v ...interface{}) {
|
||||
errlogger.Output(2, fmt.Sprintln(v...))
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, fmt.Sprintln(v...))
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
os.Exit(1)
|
||||
}
|
||||
func Panic(v ...interface{}) {
|
||||
s := fmt.Sprint(v...)
|
||||
errlogger.Output(2, s)
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, s)
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
panic(s)
|
||||
}
|
||||
|
||||
func Panicf(format string, v ...interface{}) {
|
||||
s := fmt.Sprintf(format, v...)
|
||||
errlogger.Output(2, s)
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, s)
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
panic(s)
|
||||
}
|
||||
|
||||
func Panicln(v ...interface{}) {
|
||||
s := fmt.Sprintln(v...)
|
||||
errlogger.Output(2, s)
|
||||
errlogger.Output(2, string(debug.Stack()))
|
||||
stdlogger.Output(2, s)
|
||||
stdlogger.Output(2, string(debug.Stack()))
|
||||
panic(s)
|
||||
}
|
||||
|
||||
type errWithCallstack struct {
|
||||
inner error
|
||||
frames []*runtime.Frame
|
||||
}
|
||||
|
||||
func (ecs *errWithCallstack) Error() string {
|
||||
if ecs.frames == nil {
|
||||
return ecs.inner.Error()
|
||||
}
|
||||
|
||||
out := make([]string, 0, len(ecs.frames)+1)
|
||||
out = append(out, ecs.inner.Error())
|
||||
for i := len(ecs.frames) - 1; i >= 0; i-- {
|
||||
frame := ecs.frames[i]
|
||||
out = append(out, fmt.Sprintf("%s\n\t%s:%d", frame.Function, frame.File, frame.Line))
|
||||
}
|
||||
|
||||
return strings.Join(out, "\n")
|
||||
}
|
||||
|
||||
func ErrorWithCallStack(err error) error {
|
||||
var frames []*runtime.Frame
|
||||
|
||||
if recur, ok := err.(*errWithCallstack); ok {
|
||||
err = recur.inner
|
||||
frames = recur.frames
|
||||
}
|
||||
|
||||
pc, _, _, ok := runtime.Caller(1)
|
||||
if ok {
|
||||
curframes := runtime.CallersFrames([]uintptr{pc})
|
||||
f, _ := curframes.Next()
|
||||
frames = append(frames, &f)
|
||||
}
|
||||
|
||||
return &errWithCallstack{
|
||||
inner: err,
|
||||
frames: frames,
|
||||
}
|
||||
}
|
||||
|
||||
func ErrorSmallStack() {
|
||||
buf := make([]byte, 1024)
|
||||
n := runtime.Stack(buf, false)
|
||||
if n < len(buf) {
|
||||
buf = buf[:n]
|
||||
}
|
||||
|
||||
Error(string(buf))
|
||||
}
|
||||
|
||||
func RecoverAndErrorSmallStack(r any) any {
|
||||
if r != nil {
|
||||
pc := make([]uintptr, 10)
|
||||
runtime.Callers(1, pc)
|
||||
curframes := runtime.CallersFrames(pc)
|
||||
var out []string
|
||||
for {
|
||||
frame, more := curframes.Next()
|
||||
out = append(out, fmt.Sprintf("%s\n\t%s:%d", frame.Function, frame.File, frame.Line))
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
Error(strings.Join(out, "\n"))
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
174
metric/common.go
Normal file
174
metric/common.go
Normal file
@ -0,0 +1,174 @@
|
||||
package metric
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
type MetricDescription struct {
|
||||
Key string
|
||||
Type MetricType
|
||||
Name string `json:",omitempty"`
|
||||
Help string `json:",omitempty"`
|
||||
ConstLabels map[string]string `json:",omitempty"`
|
||||
}
|
||||
|
||||
type Exporter interface {
|
||||
RegisterMetric(*MetricDescription)
|
||||
UpdateMetric(string, float64)
|
||||
}
|
||||
|
||||
type MetricPipe struct {
|
||||
pipe *os.File
|
||||
}
|
||||
|
||||
func (mp MetricPipe) Close() {
|
||||
if mp.pipe != nil {
|
||||
mp.pipe.Close()
|
||||
mp.pipe = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (mp MetricPipe) writeLine(line string) {
|
||||
mp.pipe.WriteString(line + "\n")
|
||||
}
|
||||
|
||||
func NewMetricPipe(pipeName string) MetricPipe {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
pipeName = "/tmp/" + pipeName
|
||||
case "windows":
|
||||
pipeName = `\\.\pipe\` + pipeName
|
||||
}
|
||||
|
||||
f, _ := os.Open(pipeName)
|
||||
return MetricPipe{
|
||||
pipe: f,
|
||||
}
|
||||
}
|
||||
|
||||
type MetricWriter interface {
|
||||
Add(int64)
|
||||
Set(int64)
|
||||
}
|
||||
|
||||
type metric_empty struct{}
|
||||
|
||||
func (mw *metric_empty) Set(int64) {}
|
||||
func (mw *metric_empty) Add(int64) {}
|
||||
|
||||
var MetricWriterNil = MetricWriter(&metric_empty{})
|
||||
|
||||
type metric_int64 struct {
|
||||
key string
|
||||
valptr *int64
|
||||
pipe MetricPipe
|
||||
}
|
||||
|
||||
func (mw *metric_int64) printOut() {
|
||||
loaded := atomic.LoadInt64(mw.valptr)
|
||||
mw.pipe.writeLine(fmt.Sprintf("%s:%d", mw.key, loaded))
|
||||
}
|
||||
|
||||
func (mw *metric_int64) Set(newval int64) {
|
||||
atomic.StoreInt64(mw.valptr, newval)
|
||||
mw.printOut()
|
||||
}
|
||||
|
||||
func (mw *metric_int64) Add(inc int64) {
|
||||
atomic.AddInt64(mw.valptr, inc)
|
||||
mw.printOut()
|
||||
}
|
||||
|
||||
func NewMetric(pipe MetricPipe, mt MetricType, name string, help string, constLabels map[string]string) (writer MetricWriter) {
|
||||
if !metricEnabled {
|
||||
return MetricWriterNil
|
||||
}
|
||||
|
||||
if constLabels == nil {
|
||||
constLabels = map[string]string{}
|
||||
}
|
||||
|
||||
constLabels["pid"] = fmt.Sprintf("%d", os.Getpid())
|
||||
var disorder []struct {
|
||||
k string
|
||||
v string
|
||||
}
|
||||
for k, v := range constLabels {
|
||||
disorder = append(disorder, struct {
|
||||
k string
|
||||
v string
|
||||
}{k: strings.ToLower(k), v: strings.ToLower(v)})
|
||||
}
|
||||
|
||||
sort.Slice(disorder, func(i, j int) bool {
|
||||
return disorder[i].k < disorder[j].k
|
||||
})
|
||||
|
||||
hash := md5.New()
|
||||
hash.Write([]byte(strings.ToLower(name)))
|
||||
for _, d := range disorder {
|
||||
hash.Write([]byte(d.k))
|
||||
hash.Write([]byte(d.v))
|
||||
}
|
||||
|
||||
key := hex.EncodeToString(hash.Sum(nil))[:metric_key_size]
|
||||
temp, _ := json.Marshal(MetricDescription{
|
||||
Key: key,
|
||||
Type: mt,
|
||||
Name: name,
|
||||
Help: help,
|
||||
ConstLabels: constLabels,
|
||||
})
|
||||
|
||||
impl := &metric_int64{
|
||||
key: key,
|
||||
valptr: new(int64),
|
||||
pipe: pipe,
|
||||
}
|
||||
|
||||
pipe.writeLine(string(temp))
|
||||
// writer
|
||||
|
||||
return impl
|
||||
}
|
||||
|
||||
var metricEnabled = false
|
||||
|
||||
func init() {
|
||||
if path.Base(os.Args[0]) == "houston" {
|
||||
logger.Println("metrics are going to be generated for myself(houston)")
|
||||
metricEnabled = true
|
||||
return
|
||||
}
|
||||
|
||||
ppid := os.Getppid()
|
||||
if parent, _ := os.FindProcess(ppid); parent != nil {
|
||||
filename := fmt.Sprintf(`/proc/%d/stat`, os.Getppid())
|
||||
if fn, err := os.ReadFile(filename); err == nil {
|
||||
stats := strings.SplitN(string(fn), " ", 3)
|
||||
parentname := strings.Trim(stats[1], "()")
|
||||
|
||||
if path.Base(parentname) == "houston" {
|
||||
logger.Println("metrics are going to be generated for houston")
|
||||
metricEnabled = true
|
||||
} else {
|
||||
logger.Println("metrics are NOT going to be generated. parent is not houston :", filename, string(fn))
|
||||
}
|
||||
} else {
|
||||
logger.Println("metrics are NOT going to be generated. ppid proc is missing :", filename)
|
||||
}
|
||||
} else {
|
||||
logger.Println("metrics are NOT going to be generated. parent process is missing. ppid :", ppid)
|
||||
}
|
||||
}
|
||||
108
metric/prometheus.go
Normal file
108
metric/prometheus.go
Normal file
@ -0,0 +1,108 @@
|
||||
package metric
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"math"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
METRIC_HEAD_INLINE = byte(14)
|
||||
METRIC_TAIL_INLINE = byte(15)
|
||||
)
|
||||
|
||||
type MetricType int
|
||||
|
||||
const (
|
||||
MetricCounter = MetricType(1)
|
||||
MetricGuage = MetricType(2)
|
||||
metric_key_size = 8
|
||||
)
|
||||
|
||||
func convertValueType(in MetricType) prometheus.ValueType {
|
||||
switch in {
|
||||
case MetricCounter:
|
||||
return prometheus.CounterValue
|
||||
|
||||
case MetricGuage:
|
||||
return prometheus.GaugeValue
|
||||
}
|
||||
|
||||
return prometheus.UntypedValue
|
||||
}
|
||||
|
||||
type prometheusMetricDesc struct {
|
||||
*prometheus.Desc
|
||||
valueType prometheus.ValueType
|
||||
valptr *uint64
|
||||
key string
|
||||
}
|
||||
|
||||
type PrometheusCollector struct {
|
||||
namespace string
|
||||
metrics map[string]*prometheusMetricDesc
|
||||
registry *prometheus.Registry
|
||||
}
|
||||
|
||||
func (pc *PrometheusCollector) Describe(ch chan<- *prometheus.Desc) {
|
||||
for _, v := range pc.metrics {
|
||||
logger.Println("collector describe :", v.Desc.String())
|
||||
ch <- v.Desc
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PrometheusCollector) Collect(ch chan<- prometheus.Metric) {
|
||||
for _, v := range pc.metrics {
|
||||
value := atomic.LoadUint64(v.valptr)
|
||||
cm, err := prometheus.NewConstMetric(v.Desc, v.valueType, math.Float64frombits(value))
|
||||
if err == nil {
|
||||
ch <- cm
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PrometheusCollector) RegisterMetric(md *MetricDescription) *PrometheusCollector {
|
||||
nm := &prometheusMetricDesc{
|
||||
Desc: prometheus.NewDesc(prometheus.BuildFQName("ou", "", md.Name), md.Help, nil, md.ConstLabels),
|
||||
valueType: convertValueType(md.Type),
|
||||
valptr: new(uint64),
|
||||
key: md.Key,
|
||||
}
|
||||
|
||||
next := NewPrometheusCollector(pc.namespace, pc.registry)
|
||||
maps.Copy(next.metrics, pc.metrics)
|
||||
next.metrics[nm.key] = nm
|
||||
|
||||
pc.registry.Unregister(pc)
|
||||
pc.registry.Register(next)
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
func (pc *PrometheusCollector) UpdateMetric(key string, val float64) {
|
||||
if m := pc.metrics[key]; m != nil {
|
||||
atomic.StoreUint64(m.valptr, math.Float64bits(val))
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PrometheusCollector) UnregisterMetric(key string) *PrometheusCollector {
|
||||
next := NewPrometheusCollector(pc.namespace, pc.registry)
|
||||
maps.Copy(next.metrics, pc.metrics)
|
||||
delete(next.metrics, key)
|
||||
|
||||
pc.registry.Unregister(pc)
|
||||
pc.registry.Register(next)
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
func NewPrometheusCollector(namespace string, registry *prometheus.Registry) *PrometheusCollector {
|
||||
return &PrometheusCollector{
|
||||
namespace: namespace,
|
||||
metrics: make(map[string]*prometheusMetricDesc),
|
||||
registry: registry,
|
||||
}
|
||||
}
|
||||
120
misc.go
120
misc.go
@ -20,8 +20,14 @@ var devflag = flagx.Bool("dev", false, "")
|
||||
|
||||
var sequenceStart = rand.Uint32()
|
||||
|
||||
func MakeHttpHandlerPattern(n ...string) string {
|
||||
r := "/" + path.Join(n...)
|
||||
func MakeHttpHandlerPattern(n ...string) (r string) {
|
||||
r = "/" + path.Join(n...)
|
||||
defer func() {
|
||||
for strings.Contains(r, "//") {
|
||||
r = strings.ReplaceAll(r, "//", "/")
|
||||
}
|
||||
}()
|
||||
|
||||
if strings.HasSuffix(n[len(n)-1], "/") {
|
||||
return r + "/"
|
||||
}
|
||||
@ -103,3 +109,113 @@ func SerializeInterface(w io.Writer, val interface{}) (err error) {
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func ShrinkSliceAt[T any](in []T, from int) []T {
|
||||
if len(in) == 0 {
|
||||
return in
|
||||
}
|
||||
|
||||
cursor := from
|
||||
for i := from + 1; i < len(in); i++ {
|
||||
in[cursor] = in[i]
|
||||
cursor++
|
||||
}
|
||||
return in[:len(in)-1]
|
||||
}
|
||||
|
||||
func ShrinkSlice[T any](in []T, compare func(elem T) bool) []T {
|
||||
if len(in) == 0 {
|
||||
return in
|
||||
}
|
||||
|
||||
cursor := 0
|
||||
for i := 0; i < len(in); i++ {
|
||||
if compare(in[i]) {
|
||||
continue
|
||||
}
|
||||
in[cursor] = in[i]
|
||||
cursor++
|
||||
}
|
||||
return in[:cursor]
|
||||
}
|
||||
|
||||
func FindOneInSlice[T any](in []T, compare func(elem *T) bool) (int, bool) {
|
||||
for i, e := range in {
|
||||
if compare(&e) {
|
||||
return i, true
|
||||
}
|
||||
}
|
||||
return -1, false
|
||||
}
|
||||
|
||||
// RotateRight rotates the bits in the byte array to the right by n positions
|
||||
func rotateBitsRight(data []byte, n int) {
|
||||
// Normalize n to avoid unnecessary rotations
|
||||
n = n % (len(data) * 8)
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// To hold the final rotated result
|
||||
inlen := len(data)
|
||||
for k := 0; k < n/8; k++ {
|
||||
last := data[inlen-1]
|
||||
for i := 0; i < inlen-1; i++ {
|
||||
data[inlen-1-i] = data[inlen-2-i]
|
||||
}
|
||||
data[0] = last
|
||||
}
|
||||
|
||||
n = n % 8
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
mask := byte(1<<n) - 1
|
||||
carry := data[0] & mask
|
||||
for i := 1; i < inlen; i++ {
|
||||
nextcarry := data[i] & mask
|
||||
data[i] = (data[i] >> n) | (carry << (8 - n))
|
||||
carry = nextcarry
|
||||
}
|
||||
data[0] = (data[0] >> n) | (carry << (8 - n))
|
||||
}
|
||||
|
||||
func rotateBitsLeft(data []byte, n int) {
|
||||
// Normalize n to avoid unnecessary rotations
|
||||
n = n % (len(data) * 8)
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// To hold the final rotated result
|
||||
inlen := len(data)
|
||||
for k := 0; k < n/8; k++ {
|
||||
last := data[0]
|
||||
for i := 0; i < inlen-1; i++ {
|
||||
data[i] = data[i+1]
|
||||
}
|
||||
data[inlen-1] = last
|
||||
}
|
||||
|
||||
n = n % 8
|
||||
if n == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
mask := (byte(1<<n) - 1) << (8 - n)
|
||||
carry := data[0] & mask
|
||||
for i := inlen - 1; i >= 0; i-- {
|
||||
nextcarry := data[i] & mask
|
||||
data[i] = (data[i] << n) | (carry >> (8 - n))
|
||||
carry = nextcarry
|
||||
}
|
||||
}
|
||||
|
||||
func RotateBits(data []byte, n int) {
|
||||
if n > 0 {
|
||||
rotateBitsRight(data, n)
|
||||
} else {
|
||||
rotateBitsLeft(data, -n)
|
||||
}
|
||||
}
|
||||
|
||||
219
mongo.go
219
mongo.go
@ -15,11 +15,13 @@ import (
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"go.mongodb.org/mongo-driver/mongo/readpref"
|
||||
"go.mongodb.org/mongo-driver/x/mongo/driver/connstring"
|
||||
)
|
||||
|
||||
type MongoClient struct {
|
||||
db *mongo.Database
|
||||
c *mongo.Client
|
||||
db *mongo.Database
|
||||
c *mongo.Client
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
type ConnectionInfo struct {
|
||||
@ -60,8 +62,19 @@ func (ci *ConnectionInfo) SetDatabase(dbname string) *ConnectionInfo {
|
||||
return ci
|
||||
}
|
||||
|
||||
func NewMongoClient(ctx context.Context, url string, dbname string) (MongoClient, error) {
|
||||
return newMongoClient(ctx, NewMongoConnectionInfo(url, dbname))
|
||||
var errNoDatabaseNameInMongoUri = errors.New("mongo uri has no database name")
|
||||
|
||||
func NewMongoClient(ctx context.Context, url string) (MongoClient, error) {
|
||||
connstr, err := connstring.ParseAndValidate(url)
|
||||
if err != nil {
|
||||
return MongoClient{}, err
|
||||
}
|
||||
|
||||
if len(connstr.Database) == 0 {
|
||||
return MongoClient{}, errNoDatabaseNameInMongoUri
|
||||
}
|
||||
|
||||
return newMongoClient(ctx, NewMongoConnectionInfo(url, connstr.Database))
|
||||
}
|
||||
|
||||
func newMongoClient(ctx context.Context, ci *ConnectionInfo) (MongoClient, error) {
|
||||
@ -94,55 +107,97 @@ func newMongoClient(ctx context.Context, ci *ConnectionInfo) (MongoClient, error
|
||||
return MongoClient{}, err
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
if err := client.Ping(ctx, nil); err != nil {
|
||||
logger.Error("mongo client ping err :", err)
|
||||
}
|
||||
// go func() {
|
||||
// for {
|
||||
// if err := client.Ping(ctx, nil); err != nil {
|
||||
// logger.Error("mongo client ping err :", err)
|
||||
// }
|
||||
|
||||
select {
|
||||
case <-time.After(10 * time.Second):
|
||||
continue
|
||||
// select {
|
||||
// case <-time.After(10 * time.Second):
|
||||
// continue
|
||||
|
||||
case <-ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
// case <-ctx.Done():
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
// }()
|
||||
|
||||
mdb := client.Database(ci.Database, nil)
|
||||
return MongoClient{c: client, db: mdb}, nil
|
||||
return MongoClient{c: client, db: mdb, ctx: ctx}, nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) Connected() bool {
|
||||
func (mc *MongoClient) Connected() bool {
|
||||
return mc.db != nil && mc.c != nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) Close() {
|
||||
func (mc *MongoClient) Close() {
|
||||
if mc.c != nil {
|
||||
mc.c.Disconnect(context.Background())
|
||||
mc.c.Disconnect(mc.ctx)
|
||||
}
|
||||
}
|
||||
|
||||
func (mc MongoClient) Watch(coll CollectionName, pipeline mongo.Pipeline, opts ...*options.ChangeStreamOptions) (*mongo.ChangeStream, error) {
|
||||
func (mc *MongoClient) Drop() error {
|
||||
return mc.db.Drop(mc.ctx)
|
||||
}
|
||||
|
||||
func (mc *MongoClient) DropIndex(coll CollectionName, name string) error {
|
||||
matchcoll := mc.Collection(coll)
|
||||
_, err := matchcoll.Indexes().DropOne(mc.ctx, name)
|
||||
if commanderr, ok := err.(mongo.CommandError); ok {
|
||||
if commanderr.Code == 27 {
|
||||
// 인덱스가 없는 것이므로 그냥 성공
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (mc *MongoClient) Watch(coll CollectionName, pipeline mongo.Pipeline, opts ...*options.ChangeStreamOptions) (*mongo.ChangeStream, error) {
|
||||
// mc.db.RunCommand()
|
||||
if len(opts) == 0 {
|
||||
opts = []*options.ChangeStreamOptions{options.ChangeStream().SetFullDocument(options.UpdateLookup).SetMaxAwaitTime(0)}
|
||||
}
|
||||
return mc.Collection(coll).Watch(context.Background(), pipeline, opts...)
|
||||
|
||||
stream, err := mc.Collection(coll).Watch(mc.ctx, pipeline, opts...)
|
||||
if err != nil {
|
||||
if mongoErr, ok := err.(mongo.CommandError); ok {
|
||||
logger.Println("MongoClient Watch return err code :", mongoErr, mongoErr.Code)
|
||||
if mongoErr.Code == 40573 {
|
||||
adminDb := mc.db.Client().Database("admin")
|
||||
result := adminDb.RunCommand(mc.ctx, bson.D{
|
||||
{Key: "modifyChangeStreams", Value: 1},
|
||||
{Key: "database", Value: mc.db.Name()},
|
||||
{Key: "collection", Value: coll},
|
||||
{Key: "enable", Value: true},
|
||||
})
|
||||
|
||||
if result.Err() != nil {
|
||||
logger.Println("mc.db.RunCommand failed :", result.Err(), mc.db.Name(), coll)
|
||||
} else {
|
||||
return mc.Collection(coll).Watch(mc.ctx, pipeline, opts...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.Fatal(err)
|
||||
}
|
||||
|
||||
return stream, err
|
||||
}
|
||||
|
||||
func (mc MongoClient) Collection(collname CollectionName) *mongo.Collection {
|
||||
func (mc *MongoClient) Collection(collname CollectionName) *mongo.Collection {
|
||||
return mc.db.Collection(string(collname))
|
||||
}
|
||||
|
||||
func (mc MongoClient) AllAs(coll CollectionName, output any, opts ...*options.FindOptions) error {
|
||||
cursor, err := mc.Collection(coll).Find(context.Background(), bson.D{}, opts...)
|
||||
func (mc *MongoClient) AllAs(coll CollectionName, output any, opts ...*options.FindOptions) error {
|
||||
cursor, err := mc.Collection(coll).Find(mc.ctx, bson.D{}, opts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
defer cursor.Close(mc.ctx)
|
||||
|
||||
err = cursor.All(context.Background(), output)
|
||||
err = cursor.All(mc.ctx, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -150,14 +205,14 @@ func (mc MongoClient) AllAs(coll CollectionName, output any, opts ...*options.Fi
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) All(coll CollectionName, opts ...*options.FindOptions) ([]bson.M, error) {
|
||||
func (mc *MongoClient) All(coll CollectionName, opts ...*options.FindOptions) ([]bson.M, error) {
|
||||
var all []bson.M
|
||||
err := mc.AllAs(coll, &all, opts...)
|
||||
return all, err
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindOneAndDelete(coll CollectionName, filter bson.M, opts ...*options.FindOneAndDeleteOptions) (bson.M, error) {
|
||||
result := mc.Collection(coll).FindOneAndDelete(context.Background(), filter, opts...)
|
||||
func (mc *MongoClient) FindOneAndDelete(coll CollectionName, filter bson.M, opts ...*options.FindOneAndDeleteOptions) (bson.M, error) {
|
||||
result := mc.Collection(coll).FindOneAndDelete(mc.ctx, filter, opts...)
|
||||
err := result.Err()
|
||||
if err != nil {
|
||||
if err == mongo.ErrNoDocuments {
|
||||
@ -175,8 +230,8 @@ func (mc MongoClient) FindOneAndDelete(coll CollectionName, filter bson.M, opts
|
||||
return bson.M(tmp), nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) Delete(coll CollectionName, filter bson.M, opts ...*options.DeleteOptions) (bool, error) {
|
||||
r, err := mc.Collection(coll).DeleteOne(context.Background(), filter, opts...)
|
||||
func (mc *MongoClient) Delete(coll CollectionName, filter bson.M, opts ...*options.DeleteOptions) (bool, error) {
|
||||
r, err := mc.Collection(coll).DeleteOne(mc.ctx, filter, opts...)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@ -184,20 +239,20 @@ func (mc MongoClient) Delete(coll CollectionName, filter bson.M, opts ...*option
|
||||
return r.DeletedCount > 0, nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) UnsetField(coll CollectionName, filter bson.M, doc bson.M) error {
|
||||
_, err := mc.Collection(coll).UpdateOne(context.Background(), filter, bson.M{
|
||||
func (mc *MongoClient) UnsetField(coll CollectionName, filter bson.M, doc bson.M) error {
|
||||
_, err := mc.Collection(coll).UpdateOne(mc.ctx, filter, bson.M{
|
||||
"$unset": doc,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (mc MongoClient) DeleteMany(coll CollectionName, filters bson.D, opts ...*options.DeleteOptions) (int, error) {
|
||||
func (mc *MongoClient) DeleteMany(coll CollectionName, filters bson.D, opts ...*options.DeleteOptions) (int, error) {
|
||||
if len(filters) == 0 {
|
||||
// 큰일난다
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
result, err := mc.Collection(coll).DeleteMany(context.Background(), filters, opts...)
|
||||
result, err := mc.Collection(coll).DeleteMany(mc.ctx, filters, opts...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@ -219,8 +274,8 @@ func (c *CommandInsertMany[T]) Exec(opts ...*options.InsertManyOptions) (int, er
|
||||
return c.InsertMany(c.Collection, conv, opts...)
|
||||
}
|
||||
|
||||
func (mc MongoClient) InsertMany(coll CollectionName, documents []interface{}, opts ...*options.InsertManyOptions) (int, error) {
|
||||
result, err := mc.Collection(coll).InsertMany(context.Background(), documents, opts...)
|
||||
func (mc *MongoClient) InsertMany(coll CollectionName, documents []interface{}, opts ...*options.InsertManyOptions) (int, error) {
|
||||
result, err := mc.Collection(coll).InsertMany(mc.ctx, documents, opts...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@ -228,8 +283,8 @@ func (mc MongoClient) InsertMany(coll CollectionName, documents []interface{}, o
|
||||
return len(result.InsertedIDs), nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) UpdateMany(coll CollectionName, filter bson.M, doc bson.M, opts ...*options.UpdateOptions) (count int, err error) {
|
||||
result, e := mc.Collection(coll).UpdateMany(context.Background(), filter, doc, opts...)
|
||||
func (mc *MongoClient) UpdateMany(coll CollectionName, filter bson.M, doc bson.M, opts ...*options.UpdateOptions) (count int, err error) {
|
||||
result, e := mc.Collection(coll).UpdateMany(mc.ctx, filter, doc, opts...)
|
||||
|
||||
if e != nil {
|
||||
return 0, e
|
||||
@ -252,8 +307,8 @@ func (m *JsonDefaultMashaller) MarshalBSON() ([]byte, error) {
|
||||
return json.Marshal(m.doc)
|
||||
}
|
||||
|
||||
func (mc MongoClient) Update(coll CollectionName, filter bson.M, doc interface{}, opts ...*options.UpdateOptions) (worked bool, newid interface{}, err error) {
|
||||
result, e := mc.Collection(coll).UpdateOne(context.Background(), filter, doc, opts...)
|
||||
func (mc *MongoClient) Update(coll CollectionName, filter bson.M, doc interface{}, opts ...*options.UpdateOptions) (worked bool, newid interface{}, err error) {
|
||||
result, e := mc.Collection(coll).UpdateOne(mc.ctx, filter, doc, opts...)
|
||||
|
||||
if e != nil {
|
||||
return false, "", e
|
||||
@ -265,7 +320,7 @@ func (mc MongoClient) Update(coll CollectionName, filter bson.M, doc interface{}
|
||||
return
|
||||
}
|
||||
|
||||
func (mc MongoClient) UpsertOne(coll CollectionName, filter bson.M, doc interface{}) (worked bool, newid interface{}, err error) {
|
||||
func (mc *MongoClient) UpsertOne(coll CollectionName, filter bson.M, doc interface{}) (worked bool, newid interface{}, err error) {
|
||||
return mc.Update(coll, filter, bson.M{
|
||||
"$set": doc,
|
||||
}, options.Update().SetUpsert(true))
|
||||
@ -275,16 +330,16 @@ func (mc MongoClient) UpsertOne(coll CollectionName, filter bson.M, doc interfac
|
||||
// }}, options.Update().SetUpsert(true))
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindOneAs(coll CollectionName, filter bson.M, out interface{}, opts ...*options.FindOneOptions) error {
|
||||
err := mc.Collection(coll).FindOne(context.Background(), filter, opts...).Decode(out)
|
||||
func (mc *MongoClient) FindOneAs(coll CollectionName, filter bson.M, out interface{}, opts ...*options.FindOneOptions) error {
|
||||
err := mc.Collection(coll).FindOne(mc.ctx, filter, opts...).Decode(out)
|
||||
if err == mongo.ErrNoDocuments {
|
||||
err = nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindOne(coll CollectionName, filter bson.M, opts ...*options.FindOneOptions) (doc bson.M, err error) {
|
||||
result := mc.Collection(coll).FindOne(context.Background(), filter, opts...)
|
||||
func (mc *MongoClient) FindOne(coll CollectionName, filter bson.M, opts ...*options.FindOneOptions) (doc bson.M, err error) {
|
||||
result := mc.Collection(coll).FindOne(mc.ctx, filter, opts...)
|
||||
tmp := make(map[string]interface{})
|
||||
err = result.Decode(&tmp)
|
||||
if err == nil {
|
||||
@ -296,8 +351,8 @@ func (mc MongoClient) FindOne(coll CollectionName, filter bson.M, opts ...*optio
|
||||
return
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindOneAndUpdateAs(coll CollectionName, filter bson.M, doc bson.M, out interface{}, opts ...*options.FindOneAndUpdateOptions) error {
|
||||
result := mc.Collection(coll).FindOneAndUpdate(context.Background(), filter, doc, opts...)
|
||||
func (mc *MongoClient) FindOneAndUpdateAs(coll CollectionName, filter bson.M, doc bson.M, out interface{}, opts ...*options.FindOneAndUpdateOptions) error {
|
||||
result := mc.Collection(coll).FindOneAndUpdate(mc.ctx, filter, doc, opts...)
|
||||
err := result.Decode(out)
|
||||
if err == nil {
|
||||
return nil
|
||||
@ -310,8 +365,8 @@ func (mc MongoClient) FindOneAndUpdateAs(coll CollectionName, filter bson.M, doc
|
||||
return err
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindOneAndUpdate(coll CollectionName, filter bson.M, doc bson.M, opts ...*options.FindOneAndUpdateOptions) (olddoc bson.M, err error) {
|
||||
result := mc.Collection(coll).FindOneAndUpdate(context.Background(), filter, doc, opts...)
|
||||
func (mc *MongoClient) FindOneAndUpdate(coll CollectionName, filter bson.M, doc bson.M, opts ...*options.FindOneAndUpdateOptions) (olddoc bson.M, err error) {
|
||||
result := mc.Collection(coll).FindOneAndUpdate(mc.ctx, filter, doc, opts...)
|
||||
tmp := make(map[string]interface{})
|
||||
err = result.Decode(&tmp)
|
||||
if err == nil {
|
||||
@ -323,23 +378,23 @@ func (mc MongoClient) FindOneAndUpdate(coll CollectionName, filter bson.M, doc b
|
||||
return
|
||||
}
|
||||
|
||||
func (mc MongoClient) Exists(coll CollectionName, filter bson.M) (bool, error) {
|
||||
cnt, err := mc.Collection(coll).CountDocuments(context.Background(), filter, options.Count().SetLimit(1))
|
||||
func (mc *MongoClient) Exists(coll CollectionName, filter bson.M) (bool, error) {
|
||||
cnt, err := mc.Collection(coll).CountDocuments(mc.ctx, filter, options.Count().SetLimit(1))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return cnt > 0, nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) SearchText(coll CollectionName, text string, opts ...*options.FindOptions) ([]bson.M, error) {
|
||||
cursor, err := mc.Collection(coll).Find(context.Background(), bson.M{"$text": bson.M{"$search": text}}, opts...)
|
||||
func (mc *MongoClient) SearchText(coll CollectionName, text string, opts ...*options.FindOptions) ([]bson.M, error) {
|
||||
cursor, err := mc.Collection(coll).Find(mc.ctx, bson.M{"$text": bson.M{"$search": text}}, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
defer cursor.Close(mc.ctx)
|
||||
|
||||
var output []bson.M
|
||||
err = cursor.All(context.Background(), &output)
|
||||
err = cursor.All(mc.ctx, &output)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -347,15 +402,15 @@ func (mc MongoClient) SearchText(coll CollectionName, text string, opts ...*opti
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindAll(coll CollectionName, filter bson.M, opts ...*options.FindOptions) ([]bson.M, error) {
|
||||
cursor, err := mc.Collection(coll).Find(context.Background(), filter, opts...)
|
||||
func (mc *MongoClient) FindAll(coll CollectionName, filter bson.M, opts ...*options.FindOptions) ([]bson.M, error) {
|
||||
cursor, err := mc.Collection(coll).Find(mc.ctx, filter, opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
defer cursor.Close(mc.ctx)
|
||||
|
||||
var output []bson.M
|
||||
err = cursor.All(context.Background(), &output)
|
||||
err = cursor.All(mc.ctx, &output)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@ -363,29 +418,29 @@ func (mc MongoClient) FindAll(coll CollectionName, filter bson.M, opts ...*optio
|
||||
return output, nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) FindAllAs(coll CollectionName, filter bson.M, output interface{}, opts ...*options.FindOptions) error {
|
||||
cursor, err := mc.Collection(coll).Find(context.Background(), filter, opts...)
|
||||
func (mc *MongoClient) FindAllAs(coll CollectionName, filter bson.M, output interface{}, opts ...*options.FindOptions) error {
|
||||
cursor, err := mc.Collection(coll).Find(mc.ctx, filter, opts...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
defer cursor.Close(mc.ctx)
|
||||
|
||||
err = cursor.All(context.Background(), output)
|
||||
err = cursor.All(mc.ctx, output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) MakeExpireIndex(coll CollectionName, expireSeconds int32) error {
|
||||
func (mc *MongoClient) MakeExpireIndex(coll CollectionName, expireSeconds int32) error {
|
||||
matchcoll := mc.Collection(coll)
|
||||
indices, err := matchcoll.Indexes().List(context.Background(), options.ListIndexes().SetMaxTime(time.Second))
|
||||
indices, err := matchcoll.Indexes().List(mc.ctx, options.ListIndexes().SetMaxTime(time.Second))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
allindices := make([]interface{}, 0)
|
||||
err = indices.All(context.Background(), &allindices)
|
||||
err = indices.All(mc.ctx, &allindices)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -417,7 +472,7 @@ IndexSearchLabel:
|
||||
if exp == expireSeconds {
|
||||
return nil
|
||||
}
|
||||
_, err = matchcoll.Indexes().DropOne(context.Background(), tsname)
|
||||
_, err = matchcoll.Indexes().DropOne(mc.ctx, tsname)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -428,24 +483,24 @@ IndexSearchLabel:
|
||||
Options: options.Index().SetExpireAfterSeconds(expireSeconds),
|
||||
}
|
||||
|
||||
_, err = matchcoll.Indexes().CreateOne(context.Background(), mod)
|
||||
_, err = matchcoll.Indexes().CreateOne(mc.ctx, mod)
|
||||
return err
|
||||
}
|
||||
|
||||
func (mc MongoClient) makeIndicesWithOption(coll CollectionName, indices map[string]bson.D, option *options.IndexOptions) error {
|
||||
func (mc *MongoClient) makeIndicesWithOption(coll CollectionName, indices map[string]bson.D, opts ...*options.IndexOptions) error {
|
||||
collection := mc.Collection(coll)
|
||||
cursor, err := collection.Indexes().List(context.Background(), options.ListIndexes().SetMaxTime(time.Second))
|
||||
cursor, err := collection.Indexes().List(mc.ctx, options.ListIndexes().SetMaxTime(time.Second))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cursor.Close(context.Background())
|
||||
defer cursor.Close(mc.ctx)
|
||||
|
||||
found := make(map[string]bool)
|
||||
for k := range indices {
|
||||
found[k] = false
|
||||
}
|
||||
|
||||
for cursor.TryNext(context.Background()) {
|
||||
for cursor.TryNext(mc.ctx) {
|
||||
rawval := cursor.Current
|
||||
name := rawval.Lookup("name").StringValue()
|
||||
if _, ok := indices[name]; ok {
|
||||
@ -460,16 +515,16 @@ func (mc MongoClient) makeIndicesWithOption(coll CollectionName, indices map[str
|
||||
if len(v) == 1 {
|
||||
mod = mongo.IndexModel{
|
||||
Keys: primitive.M{v[0].Key: v[0].Value},
|
||||
Options: options.MergeIndexOptions(options.Index().SetName(name), option),
|
||||
Options: options.MergeIndexOptions(append(opts, options.Index().SetName(name))...),
|
||||
}
|
||||
} else {
|
||||
mod = mongo.IndexModel{
|
||||
Keys: indices[name],
|
||||
Options: options.MergeIndexOptions(options.Index().SetName(name), option),
|
||||
Options: options.MergeIndexOptions(append(opts, options.Index().SetName(name))...),
|
||||
}
|
||||
}
|
||||
|
||||
_, err = collection.Indexes().CreateOne(context.Background(), mod)
|
||||
_, err = collection.Indexes().CreateOne(mc.ctx, mod)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -478,10 +533,10 @@ func (mc MongoClient) makeIndicesWithOption(coll CollectionName, indices map[str
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc MongoClient) MakeUniqueIndices(coll CollectionName, indices map[string]bson.D) error {
|
||||
return mc.makeIndicesWithOption(coll, indices, options.Index().SetUnique(true))
|
||||
func (mc *MongoClient) MakeUniqueIndices(coll CollectionName, indices map[string]bson.D, opts ...*options.IndexOptions) error {
|
||||
return mc.makeIndicesWithOption(coll, indices, append(opts, options.Index().SetUnique(true))...)
|
||||
}
|
||||
|
||||
func (mc MongoClient) MakeIndices(coll CollectionName, indices map[string]bson.D) error {
|
||||
return mc.makeIndicesWithOption(coll, indices, options.Index())
|
||||
func (mc *MongoClient) MakeIndices(coll CollectionName, indices map[string]bson.D, opts ...*options.IndexOptions) error {
|
||||
return mc.makeIndicesWithOption(coll, indices, opts...)
|
||||
}
|
||||
|
||||
243
opensearch/client.go
Normal file
243
opensearch/client.go
Normal file
@ -0,0 +1,243 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
osg "github.com/opensearch-project/opensearch-go/v4"
|
||||
osapi "github.com/opensearch-project/opensearch-go/v4/opensearchapi"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
osg.Config `json:",inline"`
|
||||
IndexPrefix string `json:"IndexPrefix"`
|
||||
SigningKey string `json:"SigningKey"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
*osg.Client
|
||||
cfg Config
|
||||
signingKey []byte
|
||||
indexTemplatePattern string
|
||||
bulkHeader http.Header
|
||||
singleHeader http.Header
|
||||
sendingCount int32
|
||||
}
|
||||
|
||||
type LogDocument struct {
|
||||
Type string `json:"type"`
|
||||
Body any `json:"body"`
|
||||
Timestamp string `json:"@timestamp"`
|
||||
|
||||
Country string `json:"country"`
|
||||
Ip string `json:"ip"`
|
||||
Uid string `json:"uid"`
|
||||
Auth struct {
|
||||
Type string `json:"type"`
|
||||
Id string `json:"id"`
|
||||
} `json:"auth"`
|
||||
}
|
||||
|
||||
func NewLogDocument(logType string, body any) *LogDocument {
|
||||
return &LogDocument{
|
||||
Type: strings.ToLower(logType),
|
||||
Timestamp: time.Now().UTC().Format("2006-01-02T15:04:05Z"),
|
||||
Body: body,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Send(ld *LogDocument) {
|
||||
if c.Client == nil {
|
||||
return
|
||||
}
|
||||
|
||||
serialized, _ := json.Marshal(ld)
|
||||
go func(serialized []byte) {
|
||||
sending := atomic.AddInt32(&c.sendingCount, 1)
|
||||
defer atomic.AddInt32(&c.sendingCount, -1)
|
||||
|
||||
if sending > 100 {
|
||||
logger.Println("sending log bottleneck :", sending)
|
||||
logger.Println(string(serialized))
|
||||
return
|
||||
}
|
||||
|
||||
reader := bytes.NewBuffer(serialized)
|
||||
req := osapi.IndexReq{
|
||||
Index: c.indexTemplatePattern + ld.Type,
|
||||
Body: reader,
|
||||
Header: c.singleHeader,
|
||||
}
|
||||
|
||||
resp, err := c.Do(context.Background(), req, nil)
|
||||
if err != nil {
|
||||
logger.Println("log send failed :", err)
|
||||
return
|
||||
}
|
||||
resp.Body.Close()
|
||||
}(serialized)
|
||||
}
|
||||
|
||||
func (c *Client) SendBulk(ds map[string]*LogDocument) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var contents string
|
||||
|
||||
for _, d := range ds {
|
||||
b, _ := json.Marshal(d)
|
||||
contents += fmt.Sprintf(`{"create":{"_index":"%s%s"}}`+"\n"+`%s`+"\n", c.indexTemplatePattern, d.Type, string(b))
|
||||
}
|
||||
|
||||
go func(contents string) {
|
||||
sending := atomic.AddInt32(&c.sendingCount, 1)
|
||||
defer atomic.AddInt32(&c.sendingCount, -1)
|
||||
|
||||
if sending > 100 {
|
||||
logger.Println("sending log bottleneck :", sending)
|
||||
logger.Println(contents)
|
||||
return
|
||||
}
|
||||
|
||||
reader := bytes.NewBuffer([]byte(contents))
|
||||
req := osapi.BulkReq{
|
||||
Body: reader,
|
||||
Header: c.bulkHeader,
|
||||
}
|
||||
resp, err := c.Do(context.Background(), req, nil)
|
||||
if err != nil {
|
||||
logger.Println("log send bulk failed :", err)
|
||||
return
|
||||
}
|
||||
resp.Body.Close()
|
||||
}(contents)
|
||||
}
|
||||
|
||||
var jwtHeader string
|
||||
var encoding = base64.RawURLEncoding
|
||||
|
||||
func init() {
|
||||
src := []byte(`{"alg": "HS256","typ": "JWT"}`)
|
||||
dst := make([]byte, len(src)*2)
|
||||
encoding.Encode(dst, src)
|
||||
enclen := encoding.EncodedLen(len(src))
|
||||
jwtHeader = string(dst[:enclen])
|
||||
}
|
||||
|
||||
func (c *Client) MakeJWT(subject string, role string, ttl time.Duration) string {
|
||||
if len(c.signingKey) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
now := time.Now().Add(ttl).Unix()
|
||||
src := []byte(fmt.Sprintf(`{"exp":%d,"sub":"%s","roles":"%s"}`, now, subject, role))
|
||||
payload := make([]byte, encoding.EncodedLen(len(src)))
|
||||
encoding.Encode(payload, src)
|
||||
|
||||
encoded := jwtHeader + "." + string(payload)
|
||||
mac := hmac.New(sha256.New, c.signingKey)
|
||||
mac.Write([]byte(encoded))
|
||||
signature := mac.Sum(nil)
|
||||
sigenc := make([]byte, encoding.EncodedLen(len(signature)))
|
||||
encoding.Encode(sigenc, signature)
|
||||
|
||||
return encoded + "." + string(sigenc)
|
||||
}
|
||||
|
||||
func (c *Client) VerifyJWT(token string) (subject string, role string) {
|
||||
dot := strings.LastIndex(token, ".")
|
||||
if dot < 0 {
|
||||
return
|
||||
}
|
||||
|
||||
encoded := token[:dot]
|
||||
sigenc := token[dot+1:]
|
||||
signature := make([]byte, encoding.DecodedLen(len(sigenc)))
|
||||
encoding.Decode(signature, []byte(sigenc))
|
||||
|
||||
mac := hmac.New(sha256.New, c.signingKey)
|
||||
mac.Write([]byte(encoded))
|
||||
calsig := mac.Sum(nil)
|
||||
if slices.Compare(calsig, signature) != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
_, payload, ok := strings.Cut(encoded, ".")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
srcjson, err := encoding.DecodeString(payload)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var src struct {
|
||||
Exp int64 `json:"exp"`
|
||||
Sub string `json:"sub"`
|
||||
Roles string `json:"roles"`
|
||||
}
|
||||
if json.Unmarshal([]byte(srcjson), &src) != nil {
|
||||
return
|
||||
}
|
||||
if src.Exp < time.Now().Unix() {
|
||||
return
|
||||
}
|
||||
|
||||
return src.Sub, src.Roles
|
||||
}
|
||||
|
||||
func NewClient(cfg Config) (Client, error) {
|
||||
if len(cfg.Addresses) == 0 {
|
||||
return Client{}, nil
|
||||
}
|
||||
|
||||
client, err := osg.NewClient(cfg.Config)
|
||||
if err != nil {
|
||||
return Client{}, err
|
||||
}
|
||||
|
||||
var signingKey []byte
|
||||
if len(cfg.SigningKey) > 0 {
|
||||
dst := make([]byte, len(cfg.SigningKey)*2)
|
||||
dstlen, _ := base64.StdEncoding.Decode(dst, []byte(cfg.SigningKey))
|
||||
signingKey = dst[:dstlen]
|
||||
}
|
||||
|
||||
indexPrefix := cfg.IndexPrefix
|
||||
if !strings.HasSuffix(indexPrefix, "-") && len(indexPrefix) > 0 {
|
||||
indexPrefix += "-"
|
||||
}
|
||||
if !strings.HasSuffix(indexPrefix, "ds-logs-") {
|
||||
indexPrefix = "ds-logs-" + indexPrefix
|
||||
}
|
||||
|
||||
authHeader := fmt.Sprintf("Basic %s", base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", cfg.Username, cfg.Password))))
|
||||
|
||||
bulkHeader := make(http.Header)
|
||||
bulkHeader.Set("Authorization", authHeader)
|
||||
|
||||
singleHeader := make(http.Header)
|
||||
singleHeader.Set("Authorization", authHeader)
|
||||
|
||||
return Client{
|
||||
Client: client,
|
||||
cfg: cfg,
|
||||
signingKey: signingKey,
|
||||
indexTemplatePattern: indexPrefix,
|
||||
bulkHeader: bulkHeader,
|
||||
singleHeader: singleHeader,
|
||||
}, nil
|
||||
}
|
||||
78
opensearch/client_test.go
Normal file
78
opensearch/client_test.go
Normal file
@ -0,0 +1,78 @@
|
||||
package opensearch
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
func TestNewClient(t *testing.T) {
|
||||
// var cfg Config
|
||||
|
||||
// cfg.Addresses = []string{"http://localhost:9200"}
|
||||
// client, err := NewClient(cfg)
|
||||
// if err != nil {
|
||||
// t.Errorf("NewClient() error = %v", err)
|
||||
// return
|
||||
// }
|
||||
|
||||
// for i := 0; i < 10; i++ {
|
||||
// MakeActorLog("LOGIN", "test_user", "stalkername").Write(&client, bson.M{
|
||||
// "country": "kr",
|
||||
// "ip": "127.0.0.1",
|
||||
// })
|
||||
// time.Sleep(time.Second)
|
||||
// }
|
||||
|
||||
// for i := 0; i < 10; i++ {
|
||||
// MakeActorLog("Match", "test_user", "stalkername").Write(&client, bson.M{
|
||||
// "server": "kr001",
|
||||
// "mode": "pvp",
|
||||
// "address": "server address",
|
||||
// })
|
||||
// time.Sleep(time.Second)
|
||||
// }
|
||||
}
|
||||
|
||||
func TestClient_MakeJWT(t *testing.T) {
|
||||
sk := "UGdiOTdLVjFBTWtndTRNRiZmVjdwMDdCRW1lSSUxTnA="
|
||||
dst := make([]byte, len(sk)*2)
|
||||
dstlen, _ := base64.StdEncoding.Decode(dst, []byte(sk))
|
||||
signingKey := dst[:dstlen]
|
||||
uid := primitive.NewObjectID().Hex()
|
||||
|
||||
type args struct {
|
||||
subject string
|
||||
role string
|
||||
ttl time.Duration
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
c *Client
|
||||
args args
|
||||
want string
|
||||
}{
|
||||
// TODO: Add test cases.
|
||||
{
|
||||
c: &Client{
|
||||
signingKey: signingKey,
|
||||
},
|
||||
args: args{
|
||||
subject: uid,
|
||||
role: "ds_client",
|
||||
ttl: time.Minute,
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := tt.c.MakeJWT(tt.args.subject, tt.args.role, tt.args.ttl)
|
||||
subj, role := tt.c.VerifyJWT(got)
|
||||
if subj != tt.args.subject || role != tt.args.role {
|
||||
t.Errorf("Client.MakeJWT() = %v, %v, want %v, %v", subj, role, tt.args.subject, tt.args.role)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
439
redis.go
439
redis.go
@ -2,9 +2,11 @@ package gocommon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
@ -19,23 +21,30 @@ func newRedisClient(uri string, dbidxoffset int) *redis.Client {
|
||||
return redis.NewClient(option)
|
||||
}
|
||||
|
||||
func NewRedisClient(uri string, dbidx int) (*redis.Client, error) {
|
||||
func NewRedisClient(uri string) (*redis.Client, error) {
|
||||
if !*devflag {
|
||||
return newRedisClient(uri, dbidx), nil
|
||||
return newRedisClient(uri, 0), nil
|
||||
}
|
||||
|
||||
rdb := newRedisClient(uri, 0)
|
||||
devUrl, _ := url.Parse(uri)
|
||||
option, err := redis.ParseURL(uri)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
zero := *option
|
||||
zero.DB = 0
|
||||
rdb := redis.NewClient(&zero)
|
||||
defer rdb.Close()
|
||||
|
||||
hostname, _ := os.Hostname()
|
||||
myidx, _ := rdb.HGet(context.Background(), "private_db", hostname).Result()
|
||||
if len(myidx) > 0 {
|
||||
devUrl.Path = "/" + myidx
|
||||
return newRedisClient(devUrl.String(), dbidx), nil
|
||||
offset, _ := strconv.Atoi(myidx)
|
||||
option.DB += offset
|
||||
return redis.NewClient(option), nil
|
||||
}
|
||||
|
||||
alldbs, err := rdb.HGetAll(context.Background(), "private_db").Result()
|
||||
if err != nil {
|
||||
rdb.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@ -53,6 +62,416 @@ func NewRedisClient(uri string, dbidx int) (*redis.Client, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
devUrl.Path = "/" + strconv.Itoa(newidx)
|
||||
return newRedisClient(devUrl.String(), dbidx), nil
|
||||
option.DB += newidx
|
||||
return redis.NewClient(option), nil
|
||||
}
|
||||
|
||||
type RedisonSetOption = string
|
||||
type RedisonGetOption = [2]any
|
||||
|
||||
const (
|
||||
// JSONSET command Options
|
||||
RedisonSetOptionNX RedisonSetOption = "NX"
|
||||
RedisonSetOptionXX RedisonSetOption = "XX"
|
||||
)
|
||||
|
||||
var (
|
||||
RedisonGetOptionSPACE = RedisonGetOption{"SPACE", " "}
|
||||
RedisonGetOptionINDENT = RedisonGetOption{"INDENT", "\t"}
|
||||
RedisonGetOptionNEWLINE = RedisonGetOption{"NEWLINE", "\n"}
|
||||
RedisonGetOptionNOESCAPE = RedisonGetOption{"NOESCAPE", ""}
|
||||
)
|
||||
|
||||
// gocommon으로 옮길 거
|
||||
type RedisonHandler struct {
|
||||
*redis.Client
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func NewRedisonHandler(ctx context.Context, redisClient *redis.Client) *RedisonHandler {
|
||||
return &RedisonHandler{
|
||||
Client: redisClient,
|
||||
ctx: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func respToArray[T any](resp any, err error) ([]T, error) {
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resArr := resp.([]any)
|
||||
v := make([]T, len(resArr))
|
||||
for i, e := range resArr {
|
||||
v[i] = e.(T)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func appendArgs[T any](args []any, ext ...T) []any {
|
||||
for _, e := range ext {
|
||||
args = append(args, e)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONMSetRel(key string, prefixPath string, kv map[string]any) error {
|
||||
if len(prefixPath) > 0 && !strings.HasSuffix(prefixPath, ".") {
|
||||
prefixPath += "."
|
||||
}
|
||||
|
||||
pl := rh.Pipeline()
|
||||
for path, obj := range kv {
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pl.Do(rh.ctx, "JSON.SET", key, prefixPath+path, b)
|
||||
}
|
||||
|
||||
cmders, err := pl.Exec(rh.ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, cmder := range cmders {
|
||||
if cmder.Err() != nil {
|
||||
return cmder.Err()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONMSet(key string, kv map[string]any) error {
|
||||
return rh.JSONMSetRel(key, "", kv)
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) jsonSetMergeJSONSet(cmd, key, path string, obj any, opts ...RedisonSetOption) (bool, error) {
|
||||
b, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
args := []any{
|
||||
"JSON.SET",
|
||||
key,
|
||||
path,
|
||||
b,
|
||||
}
|
||||
if len(opts) > 0 {
|
||||
args = append(args, opts[0])
|
||||
}
|
||||
|
||||
res, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return res.(string) == "OK", nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONSet(key, path string, obj any, opts ...RedisonSetOption) (bool, error) {
|
||||
return rh.jsonSetMergeJSONSet("JSON.SET", key, path, obj, opts...)
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONMerge(key, path string, obj any, opts ...RedisonSetOption) (bool, error) {
|
||||
return rh.jsonSetMergeJSONSet("JSON.MERGE", key, path, obj, opts...)
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONGet(key, path string, opts ...RedisonGetOption) (res any, err error) {
|
||||
args := appendArgs[string]([]any{
|
||||
"JSON.GET",
|
||||
key,
|
||||
}, strings.Split(path, " ")...)
|
||||
|
||||
for _, opt := range opts {
|
||||
args = append(args, opt[:]...)
|
||||
}
|
||||
|
||||
return rh.Do(rh.ctx, args...).Result()
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONGetString(key, path string) ([]string, error) {
|
||||
return respToArray[string](rh.JSONResp(key, path))
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONGetDocuments(key, path string) ([]map[string]any, error) {
|
||||
resp, err := rh.JSONGet(key, path)
|
||||
|
||||
if err != nil {
|
||||
if err == redis.Nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var objs []map[string]any
|
||||
err = json.Unmarshal([]byte(resp.(string)), &objs)
|
||||
return objs, err
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONGetInt64(key, path string) ([]int64, error) {
|
||||
return respToArray[int64](rh.JSONResp(key, path))
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONMGet(path string, keys ...string) (res any, err error) {
|
||||
args := appendArgs[string]([]any{
|
||||
"JSON.MGET",
|
||||
path,
|
||||
}, keys...)
|
||||
return rh.Do(rh.ctx, args...).Result()
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONMDel(key string, paths []string) error {
|
||||
pl := rh.Pipeline()
|
||||
for _, path := range paths {
|
||||
args := []any{
|
||||
"JSON.DEL",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
pl.Do(rh.ctx, args...)
|
||||
}
|
||||
_, err := pl.Exec(rh.ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONDel(key, path string) (int64, error) {
|
||||
args := []any{
|
||||
"JSON.DEL",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
resp, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return resp.(int64), nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONType(key, path string) ([]string, error) {
|
||||
args := []any{
|
||||
"JSON.TYPE",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
return respToArray[string](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONNumIncrBy(key, path string, number int) ([]int64, error) {
|
||||
args := []any{
|
||||
"JSON.NUMINCRBY",
|
||||
key,
|
||||
path,
|
||||
number,
|
||||
}
|
||||
resp, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var cnts []int64
|
||||
err = json.Unmarshal([]byte(resp.(string)), &cnts)
|
||||
return cnts, err
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONNumMultBy(key, path string, number int) (res any, err error) {
|
||||
args := []any{
|
||||
"JSON.NUMMULTBY",
|
||||
key,
|
||||
path,
|
||||
number,
|
||||
}
|
||||
resp, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return resp.([]any), nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONStrAppend(key, path string, jsonstring string) ([]int64, error) {
|
||||
args := []any{
|
||||
"JSON.STRAPPEND",
|
||||
key,
|
||||
path,
|
||||
fmt.Sprintf(`'"%s"'`, jsonstring),
|
||||
}
|
||||
return respToArray[int64](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONStrLen(key, path string) (res []int64, err error) {
|
||||
args := []any{
|
||||
"JSON.STRLEN",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
return respToArray[int64](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONArrAppend(key, path string, values ...any) (int64, error) {
|
||||
args := appendValues([]any{
|
||||
"JSON.ARRAPPEND",
|
||||
key,
|
||||
path,
|
||||
}, values...)
|
||||
|
||||
resp, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return resp.(int64), nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONArrLen(key, path string) ([]int64, error) {
|
||||
args := []any{
|
||||
"JSON.ARRLEN",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
return respToArray[int64](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONArrPop(key, path string, index int) (res any, err error) {
|
||||
args := []any{
|
||||
"JSON.ARRPOP",
|
||||
key,
|
||||
path,
|
||||
index,
|
||||
}
|
||||
resp, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.([]any)[0], nil
|
||||
}
|
||||
|
||||
func appendValues(args []any, values ...any) []any {
|
||||
for _, jsonValue := range values {
|
||||
switch jsonValue := jsonValue.(type) {
|
||||
case string:
|
||||
args = append(args, fmt.Sprintf(`'"%s"'`, jsonValue))
|
||||
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
|
||||
args = append(args, jsonValue)
|
||||
default:
|
||||
bt, _ := json.Marshal(jsonValue)
|
||||
args = append(args, bt)
|
||||
}
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONArrIndex(key, path string, jsonValue any, optionalRange ...int) ([]int64, error) {
|
||||
args := appendValues([]any{
|
||||
"JSON.ARRINDEX",
|
||||
key,
|
||||
path,
|
||||
}, jsonValue)
|
||||
|
||||
return respToArray[int64](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONArrTrim(key, path string, start, end int) (res any, err error) {
|
||||
args := []any{
|
||||
"JSON.ARRTRIM",
|
||||
key,
|
||||
path,
|
||||
start,
|
||||
end,
|
||||
}
|
||||
return respToArray[int64](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONArrInsert(key, path string, index int, values ...any) (res any, err error) {
|
||||
args := appendValues([]any{
|
||||
"JSON.ARRINSERT",
|
||||
key,
|
||||
path,
|
||||
index,
|
||||
}, values...)
|
||||
|
||||
return respToArray[int64](rh.Do(rh.ctx, args...).Result())
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONObjKeys(key, path string) ([]string, error) {
|
||||
args := []any{
|
||||
"JSON.OBJKEYS",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
|
||||
res, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resArr := res.([]any)
|
||||
if len(resArr) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
resArr = resArr[0].([]any)
|
||||
slc := make([]string, len(resArr))
|
||||
|
||||
for i, r := range resArr {
|
||||
slc[i] = r.(string)
|
||||
}
|
||||
|
||||
return slc, nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONObjLen(key, path string) ([]int64, error) {
|
||||
args := []any{
|
||||
"JSON.OBJLEN",
|
||||
key,
|
||||
}
|
||||
|
||||
if path != "$" {
|
||||
args = append(args, path)
|
||||
}
|
||||
|
||||
resp, err := rh.Do(rh.ctx, args...).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch resp := resp.(type) {
|
||||
case []any:
|
||||
return respToArray[int64](resp, nil)
|
||||
|
||||
case int64:
|
||||
return []int64{resp}, nil
|
||||
}
|
||||
|
||||
return []int64{0}, nil
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONDebug(key, path string) (res any, err error) {
|
||||
args := []any{
|
||||
"JSON.DEBUG",
|
||||
"MEMORY",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
return rh.Do(rh.ctx, args...).Result()
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONForget(key, path string) (int64, error) {
|
||||
return rh.JSONDel(key, path)
|
||||
}
|
||||
|
||||
func (rh *RedisonHandler) JSONResp(key, path string) (res any, err error) {
|
||||
args := []any{
|
||||
"JSON.RESP",
|
||||
key,
|
||||
path,
|
||||
}
|
||||
return rh.Do(rh.ctx, args...).Result()
|
||||
}
|
||||
|
||||
@ -1,8 +1,15 @@
|
||||
package gocommon
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/flagx"
|
||||
@ -16,6 +23,11 @@ func configFilePath() string {
|
||||
configfilepath = *configfileflag
|
||||
}
|
||||
|
||||
// if !strings.HasPrefix(configfilepath, "/") {
|
||||
// exe, _ := os.Executable()
|
||||
// configfilepath = path.Join(path.Dir(exe), configfilepath)
|
||||
// }
|
||||
|
||||
return configfilepath
|
||||
}
|
||||
|
||||
@ -53,22 +65,69 @@ func MonitorConfig[T any](onChanged func(newconf *T)) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func LoadConfig[T any](outptr *T) error {
|
||||
configfilepath := configFilePath()
|
||||
content, err := os.ReadFile(configfilepath)
|
||||
if os.IsNotExist(err) {
|
||||
return os.WriteFile(configfilepath, []byte("{}"), 0666)
|
||||
var configContents []byte
|
||||
|
||||
func splitURL(inputURL string) (string, string, error) {
|
||||
parsedURL, err := url.Parse(inputURL)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
return json.Unmarshal(content, outptr)
|
||||
base := fmt.Sprintf("%s://%s", parsedURL.Scheme, parsedURL.Host)
|
||||
path := parsedURL.Path
|
||||
|
||||
return base, path, nil
|
||||
}
|
||||
|
||||
func LoadConfig[T any](outptr *T) error {
|
||||
configfilepath := configFilePath()
|
||||
if len(configContents) == 0 {
|
||||
if strings.HasPrefix(configfilepath, "http") {
|
||||
// 여기서 다운받음
|
||||
_, subpath, err := splitURL(configfilepath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
h := md5.New()
|
||||
h.Write([]byte(subpath))
|
||||
at := hex.EncodeToString(h.Sum(nil))
|
||||
|
||||
req, _ := http.NewRequest("GET", configfilepath, nil)
|
||||
req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.51")
|
||||
req.Header.Add("As-X-UrlHash", at)
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
configContents, err = io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
content, _ := os.ReadFile(configfilepath)
|
||||
if len(content) == 0 {
|
||||
content = []byte("{}")
|
||||
}
|
||||
|
||||
configContents = content
|
||||
}
|
||||
}
|
||||
|
||||
return json.Unmarshal([]byte(os.Expand(string(configContents), func(in string) string {
|
||||
envval := os.Getenv(in)
|
||||
if len(envval) == 0 {
|
||||
return "$" + in
|
||||
}
|
||||
return envval
|
||||
})), outptr)
|
||||
}
|
||||
|
||||
type StorageAddr struct {
|
||||
Mongo string
|
||||
Redis struct {
|
||||
URL string
|
||||
Offset map[string]int
|
||||
}
|
||||
Redis map[string]string
|
||||
}
|
||||
|
||||
type RegionStorageConfig struct {
|
||||
|
||||
438
server.go
438
server.go
@ -1,7 +1,9 @@
|
||||
package gocommon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/gob"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@ -12,6 +14,7 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strconv"
|
||||
@ -20,6 +23,7 @@ import (
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/flagx"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
@ -28,6 +32,22 @@ import (
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
func init() {
|
||||
gob.Register(map[string]any{})
|
||||
gob.Register(primitive.A{})
|
||||
gob.Register(primitive.M{})
|
||||
gob.Register(primitive.D{})
|
||||
gob.Register(primitive.ObjectID{})
|
||||
gob.Register([]any{})
|
||||
}
|
||||
|
||||
type ServerMuxInterface interface {
|
||||
http.Handler
|
||||
|
||||
HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
|
||||
Handle(pattern string, handler http.Handler)
|
||||
}
|
||||
|
||||
const (
|
||||
// HTTPStatusReloginRequired : http status를 이걸 받으면 클라이언트는 로그아웃하고 로그인 화면으로 돌아가야 한다.
|
||||
HTTPStatusReloginRequired = 599
|
||||
@ -46,6 +66,14 @@ const (
|
||||
ShutdownFlagIdle = ShutdownFlag(3)
|
||||
)
|
||||
|
||||
type ErrorWithStatus struct {
|
||||
StatusCode int
|
||||
}
|
||||
|
||||
func (e ErrorWithStatus) Error() string {
|
||||
return fmt.Sprintf("%d", e.StatusCode)
|
||||
}
|
||||
|
||||
type RpcReturnTypeInterface interface {
|
||||
Value() any
|
||||
Error() error
|
||||
@ -86,37 +114,77 @@ func welcomeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte("welcome"))
|
||||
}
|
||||
|
||||
var tls = flagx.String("tls", "", "")
|
||||
var tlsflag = flagx.String("tls", "", "")
|
||||
var portptr = flagx.Int("port", 80, "")
|
||||
|
||||
func isTlsEnabled(fileout ...*string) bool {
|
||||
if len(*tlsflag) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.HasSuffix(*tlsflag, "/") {
|
||||
return false
|
||||
}
|
||||
|
||||
crtfile := *tlsflag + ".crt"
|
||||
if _, err := os.Stat(crtfile); os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
|
||||
keyfile := *tlsflag + ".key"
|
||||
if _, err := os.Stat(keyfile); os.IsNotExist(err) {
|
||||
return false
|
||||
}
|
||||
|
||||
if len(fileout) > 0 {
|
||||
*fileout[0] = crtfile
|
||||
}
|
||||
|
||||
if len(fileout) > 1 {
|
||||
*fileout[1] = keyfile
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func registUnhandledPattern(serveMux ServerMuxInterface) {
|
||||
defer func() {
|
||||
recover()
|
||||
}()
|
||||
|
||||
serveMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
logger.Println("page not found :", r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
}
|
||||
|
||||
// NewHTTPServer :
|
||||
func NewHTTPServerWithPort(serveMux *http.ServeMux, port int) *Server {
|
||||
if len(*tls) > 0 && port == 80 {
|
||||
func NewHTTPServerWithPort(serveMux ServerMuxInterface, port int) *Server {
|
||||
if isTlsEnabled() && port == 80 {
|
||||
port = 443
|
||||
}
|
||||
addr := fmt.Sprintf(":%d", port)
|
||||
serveMux.HandleFunc(MakeHttpHandlerPattern("welcome"), welcomeHandler)
|
||||
serveMux.HandleFunc(MakeHttpHandlerPattern("lb_health_chceck"), healthCheckHandler)
|
||||
serveMux.HandleFunc(MakeHttpHandlerPattern("lb_health_check"), healthCheckHandler)
|
||||
registUnhandledPattern(serveMux)
|
||||
|
||||
server := &Server{
|
||||
httpserver: &http.Server{Addr: addr, Handler: serveMux},
|
||||
interrupt: make(chan os.Signal, 1),
|
||||
httpserver: &http.Server{
|
||||
Addr: addr,
|
||||
Handler: serveMux,
|
||||
MaxHeaderBytes: 2 << 20, // 2 MB
|
||||
},
|
||||
}
|
||||
server.httpserver.SetKeepAlivesEnabled(true)
|
||||
|
||||
signal.Notify(server.interrupt, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
|
||||
go func() {
|
||||
c := <-server.interrupt
|
||||
logger.Println("interrupt!!!!!!!! :", c.String())
|
||||
server.shutdown()
|
||||
}()
|
||||
|
||||
return server
|
||||
}
|
||||
|
||||
func NewHTTPServer(serveMux *http.ServeMux) *Server {
|
||||
func NewHTTPServer(serveMux ServerMuxInterface) *Server {
|
||||
|
||||
// 시작시 자동으로 enable됨
|
||||
if len(*tls) > 0 && *portptr == 80 {
|
||||
if isTlsEnabled() && *portptr == 80 {
|
||||
*portptr = 443
|
||||
}
|
||||
return NewHTTPServerWithPort(serveMux, *portptr)
|
||||
@ -153,13 +221,35 @@ func (server *Server) shutdown() {
|
||||
}
|
||||
}
|
||||
|
||||
func (server *Server) Stop() {
|
||||
if server.interrupt != nil {
|
||||
server.interrupt <- os.Interrupt
|
||||
} else {
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
// Start :
|
||||
func (server *Server) Start() error {
|
||||
func (server *Server) Start(name ...string) error {
|
||||
if len(name) == 0 {
|
||||
exepath, _ := os.Executable()
|
||||
name = []string{path.Base(exepath)}
|
||||
}
|
||||
|
||||
if server.httpserver != nil {
|
||||
ln, r := net.Listen("tcp", server.httpserver.Addr)
|
||||
if r != nil {
|
||||
return r
|
||||
}
|
||||
server.interrupt = make(chan os.Signal, 1)
|
||||
signal.Notify(server.interrupt, os.Interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
|
||||
|
||||
go func() {
|
||||
c := <-server.interrupt
|
||||
logger.Println("interrupt!!!!!!!! :", c.String())
|
||||
server.shutdown()
|
||||
}()
|
||||
|
||||
proxyListener := &proxyproto.Listener{
|
||||
Listener: ln,
|
||||
ReadHeaderTimeout: 10 * time.Second,
|
||||
@ -167,12 +257,14 @@ func (server *Server) Start() error {
|
||||
defer proxyListener.Close()
|
||||
|
||||
var err error
|
||||
if len(*tls) > 0 {
|
||||
crtfile := *tls + ".crt"
|
||||
keyfile := *tls + ".key"
|
||||
var crtfile string
|
||||
var keyfile string
|
||||
if isTlsEnabled(&crtfile, &keyfile) {
|
||||
logger.Println("tls enabled :", crtfile, keyfile)
|
||||
err = server.httpserver.ServeTLS(proxyListener, crtfile, keyfile)
|
||||
} else {
|
||||
logger.Println("tls disabled")
|
||||
logger.Println(strings.Join(name, ", "), "started")
|
||||
err = server.httpserver.Serve(proxyListener)
|
||||
}
|
||||
|
||||
@ -262,6 +354,12 @@ func ConvertInterface(from interface{}, toType reflect.Type) reflect.Value {
|
||||
case reflect.Bool:
|
||||
val, _ := strconv.ParseBool(from.(string))
|
||||
return reflect.ValueOf(val)
|
||||
|
||||
case reflect.String:
|
||||
if toType == reflect.TypeOf(primitive.ObjectID{}) {
|
||||
objid, _ := primitive.ObjectIDFromHex(from.(string))
|
||||
return reflect.ValueOf(objid)
|
||||
}
|
||||
}
|
||||
|
||||
return fromrv.Convert(toType)
|
||||
@ -419,6 +517,53 @@ func ReadStringFormValue(r url.Values, key string) (string, bool) {
|
||||
return strval, len(strval) > 0
|
||||
}
|
||||
|
||||
func ReadStringsFormValue(r url.Values, key string) ([]string, bool) {
|
||||
if r.Has(key) {
|
||||
return (map[string][]string)(r)[key], true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
type encoder interface {
|
||||
Encode(any) error
|
||||
}
|
||||
|
||||
type nilEncoder struct{}
|
||||
|
||||
func (ne *nilEncoder) Encode(any) error { return nil }
|
||||
|
||||
type decoder interface {
|
||||
Decode(any) error
|
||||
}
|
||||
|
||||
type nilDecoder struct{}
|
||||
|
||||
func (nd *nilDecoder) Decode(any) error { return nil }
|
||||
|
||||
func MakeDecoder(r *http.Request) decoder {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct == "application/gob" {
|
||||
return gob.NewDecoder(r.Body)
|
||||
} else if ct == "application/json" {
|
||||
return json.NewDecoder(r.Body)
|
||||
}
|
||||
|
||||
logger.Error("Content-Type is not supported :", ct)
|
||||
return &nilDecoder{}
|
||||
}
|
||||
|
||||
func MakeEncoder(w http.ResponseWriter, r *http.Request) encoder {
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if ct == "application/gob" {
|
||||
return gob.NewEncoder(w)
|
||||
} else if ct == "application/json" {
|
||||
return json.NewEncoder(w)
|
||||
}
|
||||
|
||||
logger.Error("Content-Type is not supported :", ct)
|
||||
return &nilEncoder{}
|
||||
}
|
||||
|
||||
func DotStringToTimestamp(tv string) primitive.Timestamp {
|
||||
if len(tv) == 0 {
|
||||
return primitive.Timestamp{T: 0, I: 0}
|
||||
@ -505,7 +650,11 @@ func (rt *RpcReturnError) WithCode(code int) *RpcReturnError {
|
||||
}
|
||||
|
||||
func (rt *RpcReturnError) WithError(err error) *RpcReturnError {
|
||||
rt.err = err
|
||||
if err2, ok := err.(*ErrorWithStatus); ok {
|
||||
rt.WithCode(err2.StatusCode)
|
||||
} else {
|
||||
rt.err = err
|
||||
}
|
||||
return rt
|
||||
}
|
||||
|
||||
@ -535,6 +684,14 @@ func MakeRPCReturn(value interface{}) *RpcReturnSimple {
|
||||
}
|
||||
}
|
||||
|
||||
func MakeRPCFail() *RpcReturnError {
|
||||
return &RpcReturnError{
|
||||
err: nil,
|
||||
code: http.StatusInternalServerError,
|
||||
h: nil,
|
||||
}
|
||||
}
|
||||
|
||||
func MakeRPCError() *RpcReturnError {
|
||||
pc, _, _, ok := runtime.Caller(1)
|
||||
if ok {
|
||||
@ -597,3 +754,246 @@ func MakeHttpRequestForLogging(r *http.Request) *http.Request {
|
||||
r.Body = ib
|
||||
return r
|
||||
}
|
||||
|
||||
type apiFuncType func(http.ResponseWriter, *http.Request)
|
||||
type HttpApiHandler struct {
|
||||
methods map[string]apiFuncType
|
||||
originalReceiverName string
|
||||
}
|
||||
|
||||
func MakeHttpApiHandler[T any](receiver *T, receiverName string) HttpApiHandler {
|
||||
methods := make(map[string]apiFuncType)
|
||||
|
||||
tp := reflect.TypeOf(receiver)
|
||||
if len(receiverName) == 0 {
|
||||
receiverName = tp.Elem().Name()
|
||||
}
|
||||
writerType := reflect.TypeOf((*http.ResponseWriter)(nil)).Elem()
|
||||
for i := 0; i < tp.NumMethod(); i++ {
|
||||
method := tp.Method(i)
|
||||
if method.Type.NumIn() != 3 {
|
||||
continue
|
||||
}
|
||||
|
||||
if method.Type.In(0) != tp {
|
||||
continue
|
||||
}
|
||||
|
||||
if !method.Type.In(1).Implements(writerType) {
|
||||
continue
|
||||
}
|
||||
|
||||
var r http.Request
|
||||
if method.Type.In(2) != reflect.TypeOf(&r) {
|
||||
continue
|
||||
}
|
||||
|
||||
if method.Name == "ServeHTTP" {
|
||||
continue
|
||||
}
|
||||
|
||||
funcptr := method.Func.Pointer()
|
||||
p1 := unsafe.Pointer(&funcptr)
|
||||
p2 := unsafe.Pointer(&p1)
|
||||
testfunc := (*func(*T, http.ResponseWriter, *http.Request))(p2)
|
||||
methods[receiverName+"."+method.Name] = func(w http.ResponseWriter, r *http.Request) {
|
||||
(*testfunc)(receiver, w, r)
|
||||
}
|
||||
}
|
||||
|
||||
return HttpApiHandler{
|
||||
methods: methods,
|
||||
originalReceiverName: tp.Elem().Name(),
|
||||
}
|
||||
}
|
||||
|
||||
type HttpApiBroker struct {
|
||||
methods map[string]apiFuncType
|
||||
methods_dup map[string][]apiFuncType
|
||||
}
|
||||
|
||||
type bufferReadCloser struct {
|
||||
*bytes.Reader
|
||||
}
|
||||
|
||||
func (buff *bufferReadCloser) Close() error { return nil }
|
||||
|
||||
type readOnlyResponseWriter struct {
|
||||
inner http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *readOnlyResponseWriter) Header() http.Header {
|
||||
return w.inner.Header()
|
||||
}
|
||||
|
||||
func (w *readOnlyResponseWriter) Write(in []byte) (int, error) {
|
||||
logger.Println("readOnlyResponseWriter cannot write")
|
||||
return len(in), nil
|
||||
}
|
||||
|
||||
func (w *readOnlyResponseWriter) WriteHeader(statusCode int) {
|
||||
w.statusCode = statusCode
|
||||
}
|
||||
|
||||
func (hc *HttpApiBroker) AddHandler(receiver HttpApiHandler) {
|
||||
if hc.methods == nil {
|
||||
hc.methods = make(map[string]apiFuncType)
|
||||
hc.methods_dup = make(map[string][]apiFuncType)
|
||||
}
|
||||
|
||||
for k, v := range receiver.methods {
|
||||
ab := strings.Split(k, ".")
|
||||
logger.Printf("http api registered : %s.%s -> %s\n", receiver.originalReceiverName, ab[1], k)
|
||||
|
||||
hc.methods_dup[k] = append(hc.methods_dup[k], v)
|
||||
if len(hc.methods_dup[k]) > 1 {
|
||||
chain := hc.methods_dup[k]
|
||||
hc.methods[k] = func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
defer r.Body.Close()
|
||||
|
||||
wrap := &readOnlyResponseWriter{inner: w, statusCode: 200}
|
||||
for _, f := range chain {
|
||||
r.Body = &bufferReadCloser{bytes.NewReader(body)}
|
||||
f(wrap, r)
|
||||
}
|
||||
|
||||
if wrap.statusCode != 200 {
|
||||
w.WriteHeader(wrap.statusCode)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hc.methods[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *HttpApiBroker) AllMethodNames() (out []string) {
|
||||
out = make([]string, 0, len(hc.methods))
|
||||
for name := range hc.methods {
|
||||
out = append(out, name)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (hc *HttpApiBroker) CallByHeader(w http.ResponseWriter, r *http.Request) {
|
||||
funcname := r.Header.Get("AS-X-CALL")
|
||||
if len(funcname) == 0 {
|
||||
logger.Println("as-x-call header is missing")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
hc.call(funcname, w, r)
|
||||
}
|
||||
|
||||
func (hc *HttpApiBroker) Call(w http.ResponseWriter, r *http.Request) {
|
||||
funcname := r.URL.Query().Get("call")
|
||||
if len(funcname) == 0 {
|
||||
logger.Println("query param 'call' is missing")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
|
||||
}
|
||||
hc.call(funcname, w, r)
|
||||
}
|
||||
|
||||
func (hc *HttpApiBroker) call(funcname string, w http.ResponseWriter, r *http.Request) {
|
||||
if found := hc.methods[funcname]; found != nil {
|
||||
found(w, r)
|
||||
} else {
|
||||
logger.Println("api is not found :", funcname)
|
||||
}
|
||||
}
|
||||
|
||||
func CallInternalServiceAPI[T any](url string, apitoken string, method string, data T, headers ...string) error {
|
||||
tempHeader := make(http.Header)
|
||||
tempHeader.Set("MG-X-API-TOKEN", apitoken)
|
||||
tempHeader.Set("Content-Type", "application/gob")
|
||||
|
||||
for i := 1; i < len(headers); i += 2 {
|
||||
tempHeader.Set(headers[i-1], headers[i])
|
||||
}
|
||||
|
||||
buff := new(bytes.Buffer)
|
||||
ct := tempHeader.Get("Content-Type")
|
||||
if ct == "application/gob" {
|
||||
enc := gob.NewEncoder(buff)
|
||||
enc.Encode(data)
|
||||
} else if ct == "application/json" {
|
||||
enc := json.NewEncoder(buff)
|
||||
enc.Encode(data)
|
||||
}
|
||||
|
||||
reqURL := fmt.Sprintf("%s/api?call=%s", url, method)
|
||||
req, err := http.NewRequest("POST", reqURL, buff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header = tempHeader
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
|
||||
defer func() {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
if err == nil {
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return &ErrorWithStatus{StatusCode: resp.StatusCode}
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func CallInternalServiceAPIAs[Tin any, Tout any](url string, apitoken string, method string, data Tin, out *Tout, headers ...string) error {
|
||||
tempHeader := make(http.Header)
|
||||
tempHeader.Set("MG-X-API-TOKEN", apitoken)
|
||||
tempHeader.Set("Content-Type", "application/gob")
|
||||
|
||||
for i := 1; i < len(headers); i += 2 {
|
||||
tempHeader.Set(headers[i-1], headers[i])
|
||||
}
|
||||
|
||||
buff := new(bytes.Buffer)
|
||||
ct := tempHeader.Get("Content-Type")
|
||||
if ct == "application/gob" {
|
||||
enc := gob.NewEncoder(buff)
|
||||
enc.Encode(data)
|
||||
} else if ct == "application/json" {
|
||||
enc := json.NewEncoder(buff)
|
||||
enc.Encode(data)
|
||||
}
|
||||
|
||||
reqURL := fmt.Sprintf("%s/api?call=%s", url, method)
|
||||
req, err := http.NewRequest("POST", reqURL, buff)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Header = tempHeader
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return &ErrorWithStatus{StatusCode: resp.StatusCode}
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if resp != nil && resp.Body != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
if out != nil && resp.Body != nil {
|
||||
dec := gob.NewDecoder(resp.Body)
|
||||
return dec.Decode(out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
166
session/common.go
Normal file
166
session/common.go
Normal file
@ -0,0 +1,166 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
type Authorization struct {
|
||||
Account primitive.ObjectID `bson:"a" json:"a"`
|
||||
invalidated string
|
||||
|
||||
// by authorization provider
|
||||
Platform string `bson:"p" json:"p"`
|
||||
Uid string `bson:"u" json:"u"`
|
||||
Alias string `bson:"al" json:"al"`
|
||||
CreatedTime int64 `bson:"ct" json:"ct"`
|
||||
}
|
||||
|
||||
func (auth *Authorization) ToStrings() []string {
|
||||
return []string{
|
||||
"a", auth.Account.Hex(),
|
||||
"p", auth.Platform,
|
||||
"u", auth.Uid,
|
||||
"al", auth.Alias,
|
||||
"inv", auth.invalidated,
|
||||
"ct", strconv.FormatInt(auth.CreatedTime, 10),
|
||||
}
|
||||
}
|
||||
|
||||
func (auth *Authorization) Valid() bool {
|
||||
return len(auth.invalidated) == 0 && !auth.Account.IsZero()
|
||||
}
|
||||
|
||||
func MakeAuthrizationFromStringMap(src map[string]string) Authorization {
|
||||
accid, _ := primitive.ObjectIDFromHex(src["a"])
|
||||
ct, _ := strconv.ParseInt(src["ct"], 10, 0)
|
||||
return Authorization{
|
||||
Account: accid,
|
||||
Platform: src["p"],
|
||||
Uid: src["u"],
|
||||
Alias: src["al"],
|
||||
invalidated: src["inv"],
|
||||
CreatedTime: ct,
|
||||
}
|
||||
}
|
||||
|
||||
type Provider interface {
|
||||
New(*Authorization) (string, error)
|
||||
RevokeAll(primitive.ObjectID) error
|
||||
Query(string) (Authorization, error)
|
||||
Touch(string) (bool, error)
|
||||
}
|
||||
|
||||
type Consumer interface {
|
||||
Query(string) Authorization
|
||||
Touch(string) (Authorization, error)
|
||||
IsRevoked(primitive.ObjectID) bool
|
||||
Revoke(string)
|
||||
RegisterOnSessionInvalidated(func(primitive.ObjectID))
|
||||
}
|
||||
|
||||
type storagekey string
|
||||
type publickey string
|
||||
|
||||
var r = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
func make_storagekey(acc primitive.ObjectID) storagekey {
|
||||
bs := [4]byte{}
|
||||
binary.LittleEndian.PutUint32(bs[:], r.Uint32())
|
||||
|
||||
return storagekey(acc.Hex() + hex.EncodeToString(bs[2:]))
|
||||
}
|
||||
|
||||
func storagekey_to_publickey(sk storagekey) publickey {
|
||||
bs, _ := hex.DecodeString(string(sk))
|
||||
|
||||
acc := bs[:12]
|
||||
cs := bs[12:]
|
||||
|
||||
encoded := [14]byte{}
|
||||
for i, v := range acc[:] {
|
||||
encoded[i] = (v ^ cs[0]) ^ cs[1]
|
||||
}
|
||||
encoded[12] = cs[0]
|
||||
encoded[13] = cs[1]
|
||||
|
||||
return publickey(hex.EncodeToString(encoded[:]))
|
||||
}
|
||||
|
||||
func publickey_to_storagekey(pk publickey) storagekey {
|
||||
bs, _ := hex.DecodeString(string(pk))
|
||||
|
||||
acc := bs[:12]
|
||||
cs := bs[12:]
|
||||
|
||||
decoded := [14]byte{}
|
||||
for i, v := range acc[:] {
|
||||
decoded[i] = (v ^ cs[1]) ^ cs[0]
|
||||
}
|
||||
decoded[12] = cs[0]
|
||||
decoded[13] = cs[1]
|
||||
|
||||
return storagekey(hex.EncodeToString(decoded[:]))
|
||||
}
|
||||
|
||||
type SessionConfig struct {
|
||||
SessionTTL int64 `json:"session_ttl"`
|
||||
SessionStorage string `json:"session_storage"`
|
||||
}
|
||||
|
||||
var errInvalidScheme = errors.New("storageAddr is not valid scheme")
|
||||
var errSessionStorageMissing = errors.New("session_storageis missing")
|
||||
|
||||
func NewConsumer(ctx context.Context, storageAddr string, ttl time.Duration) (Consumer, error) {
|
||||
if strings.HasPrefix(storageAddr, "mongodb") {
|
||||
return newConsumerWithMongo(ctx, storageAddr, ttl)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(storageAddr, "redis") {
|
||||
return newConsumerWithRedis(ctx, storageAddr, ttl)
|
||||
}
|
||||
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
|
||||
func NewConsumerWithConfig(ctx context.Context, cfg SessionConfig) (Consumer, error) {
|
||||
if len(cfg.SessionStorage) == 0 {
|
||||
return nil, errSessionStorageMissing
|
||||
}
|
||||
|
||||
if cfg.SessionTTL == 0 {
|
||||
cfg.SessionTTL = 3600
|
||||
}
|
||||
return NewConsumer(ctx, cfg.SessionStorage, time.Duration(cfg.SessionTTL)*time.Second)
|
||||
}
|
||||
|
||||
func NewProvider(ctx context.Context, storageAddr string, ttl time.Duration) (Provider, error) {
|
||||
if strings.HasPrefix(storageAddr, "mongodb") {
|
||||
return newProviderWithMongo(ctx, storageAddr, ttl)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(storageAddr, "redis") {
|
||||
return newProviderWithRedis(ctx, storageAddr, ttl)
|
||||
}
|
||||
|
||||
return nil, errInvalidScheme
|
||||
}
|
||||
|
||||
func NewProviderWithConfig(ctx context.Context, cfg SessionConfig) (Provider, error) {
|
||||
if len(cfg.SessionStorage) == 0 {
|
||||
return nil, errSessionStorageMissing
|
||||
}
|
||||
|
||||
if cfg.SessionTTL == 0 {
|
||||
cfg.SessionTTL = 3600
|
||||
}
|
||||
return NewProvider(ctx, cfg.SessionStorage, time.Duration(cfg.SessionTTL)*time.Second)
|
||||
}
|
||||
70
session/consumer_common.go
Normal file
70
session/consumer_common.go
Normal file
@ -0,0 +1,70 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
)
|
||||
|
||||
type cache_stage[T any] struct {
|
||||
cache map[storagekey]T
|
||||
deleted map[storagekey]T
|
||||
}
|
||||
|
||||
func make_cache_stage[T any]() *cache_stage[T] {
|
||||
return &cache_stage[T]{
|
||||
cache: make(map[storagekey]T),
|
||||
deleted: make(map[storagekey]T),
|
||||
}
|
||||
}
|
||||
|
||||
type consumer_common[T any] struct {
|
||||
lock sync.Mutex
|
||||
ttl time.Duration
|
||||
ctx context.Context
|
||||
stages [2]*cache_stage[T]
|
||||
startTime time.Time
|
||||
onSessionInvalidated []func(primitive.ObjectID)
|
||||
}
|
||||
|
||||
func (c *consumer_common[T]) add_internal(sk storagekey, si T) {
|
||||
c.stages[0].cache[sk] = si
|
||||
delete(c.stages[0].deleted, sk)
|
||||
c.stages[1].cache[sk] = si
|
||||
delete(c.stages[1].deleted, sk)
|
||||
}
|
||||
|
||||
func (c *consumer_common[T]) delete_internal(sk storagekey) (old T) {
|
||||
if v, ok := c.stages[0].cache[sk]; ok {
|
||||
old = v
|
||||
c.stages[0].deleted[sk] = old
|
||||
c.stages[1].deleted[sk] = old
|
||||
|
||||
delete(c.stages[0].cache, sk)
|
||||
delete(c.stages[1].cache, sk)
|
||||
} else if v, ok = c.stages[1].cache[sk]; ok {
|
||||
old = v
|
||||
c.stages[1].deleted[sk] = old
|
||||
|
||||
delete(c.stages[1].cache, sk)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (c *consumer_common[T]) delete(sk storagekey) T {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
return c.delete_internal(sk)
|
||||
}
|
||||
|
||||
func (c *consumer_common[T]) changeStage() {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.stages[1] = c.stages[0]
|
||||
c.stages[0] = make_cache_stage[T]()
|
||||
}
|
||||
383
session/impl_mongo.go
Normal file
383
session/impl_mongo.go
Normal file
@ -0,0 +1,383 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
"repositories.action2quare.com/ayo/gocommon"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
session_collection_name = gocommon.CollectionName("session")
|
||||
)
|
||||
|
||||
type provider_mongo struct {
|
||||
mongoClient gocommon.MongoClient
|
||||
}
|
||||
|
||||
type sessionMongo struct {
|
||||
Id primitive.ObjectID `bson:"_id,omitempty"`
|
||||
Auth *Authorization `bson:"auth"`
|
||||
Key storagekey `bson:"key"`
|
||||
Ts primitive.DateTime `bson:"_ts"`
|
||||
}
|
||||
|
||||
func newProviderWithMongo(ctx context.Context, mongoUrl string, ttl time.Duration) (Provider, error) {
|
||||
mc, err := gocommon.NewMongoClient(ctx, mongoUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err = mc.MakeUniqueIndices(session_collection_name, map[string]bson.D{
|
||||
"key": {{Key: "key", Value: 1}},
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := mc.MakeExpireIndex(session_collection_name, int32(ttl.Seconds())); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &provider_mongo{
|
||||
mongoClient: mc,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider_mongo) New(input *Authorization) (string, error) {
|
||||
sk := make_storagekey(input.Account)
|
||||
|
||||
_, _, err := p.mongoClient.Update(session_collection_name, bson.M{
|
||||
"_id": input.Account,
|
||||
}, bson.M{
|
||||
"$set": sessionMongo{
|
||||
Auth: input,
|
||||
Key: sk,
|
||||
Ts: primitive.NewDateTimeFromTime(time.Now().UTC()),
|
||||
},
|
||||
}, options.Update().SetUpsert(true))
|
||||
|
||||
return string(storagekey_to_publickey(sk)), err
|
||||
}
|
||||
|
||||
func (p *provider_mongo) RevokeAll(acc primitive.ObjectID) error {
|
||||
_, err := p.mongoClient.Delete(session_collection_name, bson.M{
|
||||
"_id": acc,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (p *provider_mongo) Query(pk string) (Authorization, error) {
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
var auth Authorization
|
||||
err := p.mongoClient.FindOneAs(session_collection_name, bson.M{
|
||||
"key": sk,
|
||||
}, &auth)
|
||||
|
||||
return auth, err
|
||||
}
|
||||
|
||||
func (p *provider_mongo) Touch(pk string) (bool, error) {
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
worked, _, err := p.mongoClient.Update(session_collection_name, bson.M{
|
||||
"key": sk,
|
||||
}, bson.M{
|
||||
"$currentDate": bson.M{
|
||||
"_ts": bson.M{"$type": "date"},
|
||||
},
|
||||
}, options.Update().SetUpsert(false))
|
||||
|
||||
if err != nil {
|
||||
logger.Println("provider Touch :", err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
return worked, nil
|
||||
}
|
||||
|
||||
type consumer_mongo struct {
|
||||
consumer_common[*sessionMongo]
|
||||
ids map[primitive.ObjectID]storagekey
|
||||
mongoClient gocommon.MongoClient
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
type sessionPipelineDocument struct {
|
||||
OperationType string `bson:"operationType"`
|
||||
DocumentKey struct {
|
||||
Id primitive.ObjectID `bson:"_id"`
|
||||
} `bson:"documentKey"`
|
||||
Session *sessionMongo `bson:"fullDocument"`
|
||||
}
|
||||
|
||||
func newConsumerWithMongo(ctx context.Context, mongoUrl string, ttl time.Duration) (Consumer, error) {
|
||||
mc, err := gocommon.NewMongoClient(ctx, mongoUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
consumer := &consumer_mongo{
|
||||
consumer_common: consumer_common[*sessionMongo]{
|
||||
ttl: ttl,
|
||||
ctx: ctx,
|
||||
stages: [2]*cache_stage[*sessionMongo]{make_cache_stage[*sessionMongo](), make_cache_stage[*sessionMongo]()},
|
||||
startTime: time.Now(),
|
||||
},
|
||||
ids: make(map[primitive.ObjectID]storagekey),
|
||||
ttl: ttl,
|
||||
mongoClient: mc,
|
||||
}
|
||||
|
||||
go func() {
|
||||
matchStage := bson.D{
|
||||
{
|
||||
Key: "$match", Value: bson.D{
|
||||
{Key: "operationType", Value: bson.D{
|
||||
{Key: "$in", Value: bson.A{
|
||||
"delete",
|
||||
"insert",
|
||||
"update",
|
||||
}},
|
||||
}},
|
||||
},
|
||||
}}
|
||||
projectStage := bson.D{
|
||||
{
|
||||
Key: "$project", Value: bson.D{
|
||||
{Key: "documentKey", Value: 1},
|
||||
{Key: "operationType", Value: 1},
|
||||
{Key: "fullDocument", Value: 1},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var stream *mongo.ChangeStream
|
||||
nextswitch := time.Now().Add(ttl)
|
||||
for {
|
||||
if stream == nil {
|
||||
stream, err = mc.Watch(session_collection_name, mongo.Pipeline{matchStage, projectStage})
|
||||
if err != nil {
|
||||
logger.Error("watchAuthCollection watch failed :", err)
|
||||
time.Sleep(time.Minute)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
changed := stream.TryNext(ctx)
|
||||
if ctx.Err() != nil {
|
||||
logger.Error("watchAuthCollection stream.TryNext failed. process should be restarted! :", ctx.Err().Error())
|
||||
break
|
||||
}
|
||||
|
||||
if changed {
|
||||
var data sessionPipelineDocument
|
||||
if err := stream.Decode(&data); err == nil {
|
||||
ot := data.OperationType
|
||||
switch ot {
|
||||
case "insert":
|
||||
consumer.add(data.Session.Key, data.DocumentKey.Id, data.Session)
|
||||
case "update":
|
||||
if data.Session == nil {
|
||||
if old := consumer.deleteById(data.DocumentKey.Id); old != nil {
|
||||
for _, f := range consumer.onSessionInvalidated {
|
||||
f(old.Auth.Account)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
consumer.add(data.Session.Key, data.DocumentKey.Id, data.Session)
|
||||
}
|
||||
case "delete":
|
||||
if old := consumer.deleteById(data.DocumentKey.Id); old != nil {
|
||||
for _, f := range consumer.onSessionInvalidated {
|
||||
f(old.Auth.Account)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
logger.Error("watchAuthCollection stream.Decode failed :", err)
|
||||
}
|
||||
} else if stream.Err() != nil || stream.ID() == 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
logger.Println("watchAuthCollection is done")
|
||||
stream.Close(ctx)
|
||||
return
|
||||
|
||||
case <-time.After(time.Second):
|
||||
logger.Error("watchAuthCollection stream error :", stream.Err())
|
||||
stream.Close(ctx)
|
||||
stream = nil
|
||||
}
|
||||
} else {
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
for now.After(nextswitch) {
|
||||
consumer.changeStage()
|
||||
nextswitch = nextswitch.Add(ttl)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return consumer, nil
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) query_internal(sk storagekey) (*sessionMongo, bool, error) {
|
||||
if _, deleted := c.stages[0].deleted[sk]; deleted {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
if _, deleted := c.stages[1].deleted[sk]; deleted {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
found, ok := c.stages[0].cache[sk]
|
||||
if !ok {
|
||||
found, ok = c.stages[1].cache[sk]
|
||||
}
|
||||
|
||||
if ok {
|
||||
return found, false, nil
|
||||
}
|
||||
|
||||
var si sessionMongo
|
||||
err := c.mongoClient.FindOneAs(session_collection_name, bson.M{
|
||||
"key": sk,
|
||||
}, &si)
|
||||
|
||||
if err != nil {
|
||||
logger.Println("consumer Query :", err)
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
if len(si.Key) > 0 {
|
||||
siptr := &si
|
||||
c.add_internal(sk, siptr)
|
||||
return siptr, true, nil
|
||||
}
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) Query(pk string) Authorization {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
si, _, err := c.query_internal(sk)
|
||||
if err != nil {
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
if si == nil {
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
if time.Now().After(si.Ts.Time().Add(c.ttl)) {
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
return *si.Auth
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) Touch(pk string) (Authorization, error) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
worked, _, err := c.mongoClient.Update(session_collection_name, bson.M{
|
||||
"key": sk,
|
||||
}, bson.M{
|
||||
"$currentDate": bson.M{
|
||||
"_ts": bson.M{"$type": "date"},
|
||||
},
|
||||
}, options.Update().SetUpsert(false))
|
||||
|
||||
if err != nil {
|
||||
logger.Println("consumer Touch :", err)
|
||||
return Authorization{}, err
|
||||
}
|
||||
|
||||
if !worked {
|
||||
// 이미 만료되서 사라짐
|
||||
return Authorization{}, nil
|
||||
}
|
||||
|
||||
si, added, err := c.query_internal(sk)
|
||||
if err != nil {
|
||||
return Authorization{}, err
|
||||
}
|
||||
|
||||
if si == nil {
|
||||
return Authorization{}, nil
|
||||
}
|
||||
|
||||
if !added {
|
||||
var doc sessionMongo
|
||||
err := c.mongoClient.FindOneAs(session_collection_name, bson.M{
|
||||
"key": sk,
|
||||
}, &doc)
|
||||
|
||||
if err != nil {
|
||||
logger.Println("consumer Query :", err)
|
||||
return Authorization{}, err
|
||||
}
|
||||
|
||||
if len(si.Key) > 0 {
|
||||
c.add_internal(sk, &doc)
|
||||
c.ids[doc.Id] = sk
|
||||
|
||||
return *doc.Auth, nil
|
||||
}
|
||||
}
|
||||
|
||||
return *si.Auth, nil
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) Revoke(pk string) {
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
_, err := c.mongoClient.Delete(session_collection_name, bson.M{
|
||||
"key": sk,
|
||||
})
|
||||
|
||||
if err == nil {
|
||||
for id, v := range c.ids {
|
||||
if v == sk {
|
||||
delete(c.ids, id)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) IsRevoked(id primitive.ObjectID) bool {
|
||||
_, ok := c.ids[id]
|
||||
return !ok
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) add(sk storagekey, id primitive.ObjectID, si *sessionMongo) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
c.consumer_common.add_internal(sk, si)
|
||||
c.ids[id] = sk
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) deleteById(id primitive.ObjectID) (old *sessionMongo) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
if sk, ok := c.ids[id]; ok {
|
||||
old = c.consumer_common.delete_internal(sk)
|
||||
delete(c.ids, id)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *consumer_mongo) RegisterOnSessionInvalidated(cb func(primitive.ObjectID)) {
|
||||
c.onSessionInvalidated = append(c.onSessionInvalidated, cb)
|
||||
}
|
||||
371
session/impl_redis.go
Normal file
371
session/impl_redis.go
Normal file
@ -0,0 +1,371 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/go-redis/redis/v8"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"repositories.action2quare.com/ayo/gocommon"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
communication_channel_name_prefix = "_sess_comm_chan_name"
|
||||
)
|
||||
|
||||
type sessionRedis struct {
|
||||
*Authorization
|
||||
expireAt time.Time
|
||||
}
|
||||
|
||||
type provider_redis struct {
|
||||
redisClient *redis.Client
|
||||
deleteChannel string
|
||||
ttl time.Duration
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func newProviderWithRedis(ctx context.Context, redisUrl string, ttl time.Duration) (Provider, error) {
|
||||
redisClient, err := gocommon.NewRedisClient(redisUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &provider_redis{
|
||||
redisClient: redisClient,
|
||||
deleteChannel: fmt.Sprintf("%s_%d_d", communication_channel_name_prefix, redisClient.Options().DB),
|
||||
ttl: ttl,
|
||||
ctx: ctx,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *provider_redis) New(input *Authorization) (string, error) {
|
||||
newsk := make_storagekey(input.Account)
|
||||
prefix := input.Account.Hex()
|
||||
sks, err := p.redisClient.Keys(p.ctx, prefix+"*").Result()
|
||||
if err != nil {
|
||||
logger.Println("session provider delete :", sks, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
p.redisClient.Del(p.ctx, sks...)
|
||||
for _, sk := range sks {
|
||||
p.redisClient.Publish(p.ctx, p.deleteChannel, sk).Result()
|
||||
}
|
||||
|
||||
for {
|
||||
duplicated := false
|
||||
for _, sk := range sks {
|
||||
if sk == string(newsk) {
|
||||
duplicated = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !duplicated {
|
||||
break
|
||||
}
|
||||
newsk = make_storagekey(input.Account)
|
||||
}
|
||||
|
||||
_, err = p.redisClient.HSet(p.ctx, string(newsk), input.ToStrings()).Result()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err = p.redisClient.Expire(p.ctx, string(newsk), p.ttl).Result()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
pk := storagekey_to_publickey(newsk)
|
||||
return string(pk), err
|
||||
}
|
||||
|
||||
func (p *provider_redis) RevokeAll(account primitive.ObjectID) error {
|
||||
prefix := account.Hex()
|
||||
sks, err := p.redisClient.Keys(p.ctx, prefix+"*").Result()
|
||||
if err != nil {
|
||||
logger.Println("session provider delete :", sks, err)
|
||||
return err
|
||||
}
|
||||
|
||||
for _, sk := range sks {
|
||||
p.redisClient.HSet(p.ctx, sk, "inv", "true")
|
||||
p.redisClient.Publish(p.ctx, p.deleteChannel, sk).Result()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *provider_redis) Query(pk string) (Authorization, error) {
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
src, err := p.redisClient.HGetAll(p.ctx, string(sk)).Result()
|
||||
if err == redis.Nil {
|
||||
logger.Println("session provider query :", pk, err)
|
||||
return Authorization{}, nil
|
||||
} else if err != nil {
|
||||
logger.Println("session provider query :", pk, err)
|
||||
return Authorization{}, err
|
||||
}
|
||||
|
||||
auth := MakeAuthrizationFromStringMap(src)
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
func (p *provider_redis) Touch(pk string) (bool, error) {
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
ok, err := p.redisClient.Expire(p.ctx, string(sk), p.ttl).Result()
|
||||
|
||||
if err == redis.Nil {
|
||||
// 이미 만료됨
|
||||
logger.Println("session provider touch :", pk, err)
|
||||
return false, nil
|
||||
} else if err != nil {
|
||||
logger.Println("session provider touch :", pk, err)
|
||||
return false, err
|
||||
}
|
||||
|
||||
return ok, nil
|
||||
}
|
||||
|
||||
type consumer_redis struct {
|
||||
consumer_common[*sessionRedis]
|
||||
redisClient *redis.Client
|
||||
deleteChannel string
|
||||
}
|
||||
|
||||
func newConsumerWithRedis(ctx context.Context, redisUrl string, ttl time.Duration) (Consumer, error) {
|
||||
redisClient, err := gocommon.NewRedisClient(redisUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
deleteChannel := fmt.Sprintf("%s_%d_d", communication_channel_name_prefix, redisClient.Options().DB)
|
||||
sub := redisClient.Subscribe(ctx, deleteChannel)
|
||||
|
||||
consumer := &consumer_redis{
|
||||
consumer_common: consumer_common[*sessionRedis]{
|
||||
ttl: ttl,
|
||||
ctx: ctx,
|
||||
stages: [2]*cache_stage[*sessionRedis]{make_cache_stage[*sessionRedis](), make_cache_stage[*sessionRedis]()},
|
||||
startTime: time.Now(),
|
||||
},
|
||||
redisClient: redisClient,
|
||||
deleteChannel: deleteChannel,
|
||||
}
|
||||
|
||||
go func() {
|
||||
stageswitch := time.Now().Add(ttl)
|
||||
tickTimer := time.After(ttl)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
|
||||
case <-tickTimer:
|
||||
consumer.changeStage()
|
||||
stageswitch = stageswitch.Add(ttl)
|
||||
tempttl := time.Until(stageswitch)
|
||||
tickTimer = time.After(tempttl)
|
||||
|
||||
case msg := <-sub.Channel():
|
||||
if msg == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if len(msg.Payload) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
switch msg.Channel {
|
||||
case deleteChannel:
|
||||
sk := storagekey(msg.Payload)
|
||||
old := consumer.delete(sk)
|
||||
if old != nil {
|
||||
for _, f := range consumer.onSessionInvalidated {
|
||||
f(old.Account)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return consumer, nil
|
||||
}
|
||||
|
||||
func (c *consumer_redis) query_internal(sk storagekey) (*sessionRedis, error) {
|
||||
if old, deleted := c.stages[0].deleted[sk]; deleted {
|
||||
return old, nil
|
||||
}
|
||||
|
||||
if old, deleted := c.stages[1].deleted[sk]; deleted {
|
||||
return old, nil
|
||||
}
|
||||
|
||||
found, ok := c.stages[0].cache[sk]
|
||||
if !ok {
|
||||
found, ok = c.stages[1].cache[sk]
|
||||
}
|
||||
|
||||
if ok {
|
||||
if time.Now().Before(found.expireAt) {
|
||||
// 만료전 세션
|
||||
return found, nil
|
||||
}
|
||||
|
||||
// 다른 Consumer가 Touch했을 수도 있으므로 redis에서 읽어본다.
|
||||
}
|
||||
|
||||
payload, err := c.redisClient.HGetAll(c.ctx, string(sk)).Result()
|
||||
if err != nil && err != redis.Nil {
|
||||
logger.Println("consumer Query :", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(payload) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
ttl, err := c.redisClient.TTL(c.ctx, string(sk)).Result()
|
||||
if err != nil {
|
||||
logger.Println("consumer Query :", err)
|
||||
return nil, err
|
||||
}
|
||||
if ttl < 0 {
|
||||
ttl = time.Duration(time.Hour * 24)
|
||||
}
|
||||
|
||||
auth := MakeAuthrizationFromStringMap(payload)
|
||||
si := &sessionRedis{
|
||||
Authorization: &auth,
|
||||
expireAt: time.Now().Add(ttl),
|
||||
}
|
||||
|
||||
if auth.Valid() {
|
||||
c.add_internal(sk, si)
|
||||
} else {
|
||||
c.stages[0].deleted[sk] = si
|
||||
}
|
||||
|
||||
return si, nil
|
||||
}
|
||||
|
||||
var errRevoked = errors.New("session revoked")
|
||||
var errExpired = errors.New("session expired")
|
||||
|
||||
func (c *consumer_redis) Query(pk string) Authorization {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
|
||||
if _, deleted := c.stages[0].deleted[sk]; deleted {
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
if _, deleted := c.stages[1].deleted[sk]; deleted {
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
si, err := c.query_internal(sk)
|
||||
if err != nil {
|
||||
logger.Println("session consumer query :", pk, err)
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
if si == nil {
|
||||
logger.Println("session consumer query(si nil) :", pk, nil)
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
if time.Now().After(si.expireAt) {
|
||||
logger.Println("session consumer query(expired):", pk, nil)
|
||||
return Authorization{}
|
||||
}
|
||||
|
||||
return *si.Authorization
|
||||
}
|
||||
|
||||
func (c *consumer_redis) Touch(pk string) (Authorization, error) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
|
||||
if _, deleted := c.stages[0].deleted[sk]; deleted {
|
||||
return Authorization{}, nil
|
||||
}
|
||||
|
||||
if _, deleted := c.stages[1].deleted[sk]; deleted {
|
||||
return Authorization{}, nil
|
||||
}
|
||||
|
||||
ok, err := c.redisClient.Expire(c.ctx, string(sk), c.ttl).Result()
|
||||
if err == redis.Nil {
|
||||
logger.Println("session consumer touch :", pk, err)
|
||||
|
||||
return Authorization{}, nil
|
||||
} else if err != nil {
|
||||
logger.Println("session consumer touch :", pk, err)
|
||||
return Authorization{}, err
|
||||
}
|
||||
|
||||
if ok {
|
||||
// redis에 살아있다.
|
||||
si, err := c.query_internal(sk)
|
||||
if err != nil {
|
||||
logger.Println("session consumer touch(ok) :", pk, err)
|
||||
return Authorization{}, err
|
||||
}
|
||||
|
||||
if si == nil {
|
||||
logger.Println("session consumer touch(ok, si nil) :", pk)
|
||||
return Authorization{}, nil
|
||||
}
|
||||
|
||||
return *si.Authorization, nil
|
||||
}
|
||||
|
||||
return Authorization{}, nil
|
||||
}
|
||||
|
||||
func (c *consumer_redis) Revoke(pk string) {
|
||||
sk := publickey_to_storagekey(publickey(pk))
|
||||
|
||||
c.redisClient.Del(c.ctx, string(sk))
|
||||
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
if sr, ok := c.stages[0].cache[sk]; ok {
|
||||
c.stages[0].deleted[sk] = sr
|
||||
}
|
||||
|
||||
if sr, ok := c.stages[1].cache[sk]; ok {
|
||||
c.stages[1].deleted[sk] = sr
|
||||
}
|
||||
}
|
||||
|
||||
func (c *consumer_redis) IsRevoked(accid primitive.ObjectID) bool {
|
||||
sk := make_storagekey(accid)
|
||||
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
if _, deleted := c.stages[0].deleted[sk]; deleted {
|
||||
return true
|
||||
}
|
||||
|
||||
if _, deleted := c.stages[1].deleted[sk]; deleted {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *consumer_redis) RegisterOnSessionInvalidated(cb func(primitive.ObjectID)) {
|
||||
c.onSessionInvalidated = append(c.onSessionInvalidated, cb)
|
||||
}
|
||||
93
session/session_test.go
Normal file
93
session/session_test.go
Normal file
@ -0,0 +1,93 @@
|
||||
// package main ...
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
func TestExpTable(t *testing.T) {
|
||||
// pv, err := NewProvider(context.Background(), "redis://192.168.8.94:6380/1", 10*time.Second)
|
||||
// if err != nil {
|
||||
// t.Error(err)
|
||||
// }
|
||||
|
||||
// cs, err := NewConsumer(context.Background(), "redis://192.168.8.94:6380/1", 10*time.Second)
|
||||
// if err != nil {
|
||||
// t.Error(err)
|
||||
// }
|
||||
|
||||
pv, err := NewProvider(context.Background(), "mongodb://192.168.8.94:27017/maingate?replicaSet=repl01&retrywrites=false", 10*time.Second)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
cs, err := NewConsumer(context.Background(), "mongodb://192.168.8.94:27017/maingate?replicaSet=repl01&retrywrites=false", 10*time.Second)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
test := primitive.NewObjectID()
|
||||
sk := make_storagekey(test)
|
||||
pk := storagekey_to_publickey(sk)
|
||||
if publickey_to_storagekey(pk) != sk {
|
||||
t.Errorf("pk != sk : %s, %s", pk, sk)
|
||||
}
|
||||
|
||||
au1 := &Authorization{
|
||||
Account: primitive.NewObjectID(),
|
||||
Platform: "editor",
|
||||
Uid: "uid-1",
|
||||
}
|
||||
sk1, err := pv.New(au1)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
au2 := &Authorization{
|
||||
Account: primitive.NewObjectID(),
|
||||
Platform: "editor",
|
||||
Uid: "uid-2",
|
||||
}
|
||||
sk2, err := pv.New(au2)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
go func() {
|
||||
for {
|
||||
q1 := cs.Query(sk1)
|
||||
logger.Println("query :", q1)
|
||||
|
||||
q2 := cs.Query(sk2)
|
||||
logger.Println("query :", q2)
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}()
|
||||
|
||||
cs.Touch(sk1)
|
||||
time.Sleep(2 * time.Second)
|
||||
cs.Touch(sk2)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
time.Sleep(2 * time.Second)
|
||||
pv.RevokeAll(au1.Account)
|
||||
|
||||
cs.Touch(sk1)
|
||||
time.Sleep(2 * time.Second)
|
||||
cs.Touch(sk2)
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
cs2, err := NewConsumer(context.Background(), "redis://192.168.8.94:6380/1", 10*time.Second)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
q2 := cs2.Query(sk2)
|
||||
logger.Println("queryf :", q2)
|
||||
time.Sleep(20 * time.Second)
|
||||
}
|
||||
146
voicechat/eos_impl.go
Normal file
146
voicechat/eos_impl.go
Normal file
@ -0,0 +1,146 @@
|
||||
package voicechat
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
type eosauth struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
DeploymentId string `json:"deployment_id"`
|
||||
ProductId string `json:"product_id"`
|
||||
SandboxId string `json:"sandbox_id"`
|
||||
TokenType string `json:"token_type"`
|
||||
}
|
||||
|
||||
func eosTokenRefresh(target *unsafe.Pointer, ctx context.Context) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r != nil {
|
||||
logger.Error(r)
|
||||
}
|
||||
}()
|
||||
|
||||
endpoint := "https://api.epicgames.dev/auth/v1/oauth/token"
|
||||
auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", config.EosClientId, config.EosClientSecret)))
|
||||
for {
|
||||
req, _ := http.NewRequest("POST", endpoint, bytes.NewBufferString("grant_type=client_credentials&deployment_id="+config.EosDeploymentId))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Basic %s", auth))
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
logger.Println("eosTokenRefresh failed. eos token reqeust err :", err)
|
||||
time.Sleep(time.Minute)
|
||||
continue
|
||||
}
|
||||
|
||||
var neweos eosauth
|
||||
err = json.NewDecoder(resp.Body).Decode(&neweos)
|
||||
resp.Body.Close()
|
||||
|
||||
if err != nil {
|
||||
logger.Println("eosTokenRefresh failed. decode err :", err)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Printf("eos access_token retreived : %s...", neweos.AccessToken[:20])
|
||||
atomic.StorePointer(target, unsafe.Pointer(&neweos))
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
|
||||
case <-time.After(time.Duration(neweos.ExpiresIn-60) * time.Second):
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type eosRoomParticipantRequests struct {
|
||||
Puid string `json:"puid"`
|
||||
ClientIP string `json:"clientIP"`
|
||||
HardMuted bool `json:"hardMuted"`
|
||||
}
|
||||
|
||||
type eosRoomParticipants struct {
|
||||
Participants []eosRoomParticipantRequests `json:"participants"`
|
||||
}
|
||||
|
||||
func (gv *eosauth) joinVoiceChat(data JoinVoiceChatRequst) map[string]any {
|
||||
// https://dev.epicgames.com/docs/web-api-ref/voice-web-api
|
||||
accessToken := gv.AccessToken
|
||||
if len(accessToken) == 0 {
|
||||
logger.Println("eos voice chat is not ready. access_token is empty")
|
||||
return nil
|
||||
}
|
||||
|
||||
voiceendpoint := fmt.Sprintf("https://api.epicgames.dev/rtc/v1/%s/room/%s", config.EosDeploymentId, data.Gid)
|
||||
participants := eosRoomParticipants{
|
||||
Participants: []eosRoomParticipantRequests{
|
||||
{Puid: data.Alias},
|
||||
},
|
||||
}
|
||||
|
||||
body, _ := json.Marshal(participants)
|
||||
req, _ := http.NewRequest("POST", voiceendpoint, bytes.NewBuffer(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
logger.Println("join voice room failed. api.epicgames.dev return err :", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
var result map[string]any
|
||||
json.NewDecoder(resp.Body).Decode(&result)
|
||||
resp.Body.Close()
|
||||
|
||||
result["client_id"] = config.EosClientId
|
||||
result["client_secret"] = config.EosClientSecret
|
||||
|
||||
par := result["participants"].([]any)[0]
|
||||
participant := par.(map[string]any)
|
||||
|
||||
channelCredentials := map[string]any{
|
||||
"override_userid": data.Alias,
|
||||
"client_base_url": result["clientBaseUrl"],
|
||||
"participant_token": participant["token"],
|
||||
}
|
||||
marshaled, _ := json.Marshal(channelCredentials)
|
||||
result["channel_credentials"] = base64.StdEncoding.EncodeToString(marshaled)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (gv *eosauth) leaveVoiceChat(data LeaveVoiceChatRequst) {
|
||||
voiceendpoint := fmt.Sprintf("https://api.epicgames.dev/rtc/v1/%s/room/%s/participants/%s", config.EosDeploymentId, data.Gid, data.Alias)
|
||||
accessToken := gv.AccessToken
|
||||
|
||||
req, _ := http.NewRequest("DELETE", voiceendpoint, nil)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken))
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
|
||||
if err != nil {
|
||||
logger.Println("LeaveVoiceChat failed. err :", err)
|
||||
return
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
// 204가 정상 응답
|
||||
logger.Println("LeaveVoiceChat failed. status code :", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
83
voicechat/voice_chat.go
Normal file
83
voicechat/voice_chat.go
Normal file
@ -0,0 +1,83 @@
|
||||
package voicechat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"unsafe"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
type JoinVoiceChatRequst struct {
|
||||
Gid string
|
||||
Alias string
|
||||
Service string
|
||||
}
|
||||
|
||||
type LeaveVoiceChatRequst struct {
|
||||
Gid string
|
||||
Alias string
|
||||
Service string
|
||||
}
|
||||
|
||||
type voiceChatConfig struct {
|
||||
EosClientId string `json:"eos_client_id"`
|
||||
EosClientSecret string `json:"eos_client_secret"`
|
||||
EosDeploymentId string `json:"eos_deployment_id"`
|
||||
}
|
||||
|
||||
type voiceServiceImpl interface {
|
||||
joinVoiceChat(JoinVoiceChatRequst) map[string]any
|
||||
leaveVoiceChat(LeaveVoiceChatRequst)
|
||||
}
|
||||
|
||||
var config voiceChatConfig
|
||||
|
||||
type VoiceChatService struct {
|
||||
eosptr unsafe.Pointer
|
||||
}
|
||||
|
||||
func (gv *VoiceChatService) Initialize(ctx context.Context) error {
|
||||
if err := gocommon.LoadConfig(&config); err != nil {
|
||||
return logger.ErrorWithCallStack(err)
|
||||
}
|
||||
|
||||
if len(config.EosClientId) == 0 {
|
||||
logger.Println("eos voice chat is disabled. 'eos_client_id' is empty")
|
||||
}
|
||||
if len(config.EosClientSecret) == 0 {
|
||||
logger.Println("eos voice chat is disabled. 'eos_client_secret' is empty")
|
||||
}
|
||||
if len(config.EosDeploymentId) == 0 {
|
||||
logger.Println("eos voice chat is disabled. 'eos_deployment_id' is empty")
|
||||
}
|
||||
|
||||
gv.eosptr = unsafe.Pointer(&eosauth{})
|
||||
if len(config.EosClientId) > 0 && len(config.EosClientSecret) > 0 && len(config.EosDeploymentId) > 0 {
|
||||
go eosTokenRefresh(&gv.eosptr, ctx)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (gv *VoiceChatService) eos() voiceServiceImpl {
|
||||
ptr := atomic.LoadPointer(&gv.eosptr)
|
||||
return (*eosauth)(ptr)
|
||||
}
|
||||
|
||||
func (gv *VoiceChatService) JoinVoiceChat(req JoinVoiceChatRequst) map[string]any {
|
||||
switch req.Service {
|
||||
case "eos":
|
||||
return gv.eos().joinVoiceChat(req)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (gv *VoiceChatService) LeaveVoiceChat(req LeaveVoiceChatRequst) {
|
||||
switch req.Service {
|
||||
case "eos":
|
||||
gv.eos().leaveVoiceChat(req)
|
||||
}
|
||||
}
|
||||
184
wshandler/api_handler.go
Normal file
184
wshandler/api_handler.go
Normal file
@ -0,0 +1,184 @@
|
||||
package wshandler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
ClientConnected = "ClientConnected"
|
||||
ClientDisconnected = "ClientDisconnected"
|
||||
)
|
||||
|
||||
type apiFuncType func(ApiCallContext)
|
||||
type connFuncType func(*Conn, *Sender)
|
||||
type disconnFuncType func(string, *Sender)
|
||||
|
||||
type WebsocketApiHandler struct {
|
||||
methods map[string]apiFuncType
|
||||
connfunc connFuncType
|
||||
disconnfunc disconnFuncType
|
||||
originalReceiverName string
|
||||
}
|
||||
|
||||
type ApiCallContext struct {
|
||||
CallBy *Sender
|
||||
Arguments []any
|
||||
}
|
||||
|
||||
func MakeWebsocketApiHandler[T any](receiver *T, receiverName string) WebsocketApiHandler {
|
||||
methods := make(map[string]apiFuncType)
|
||||
|
||||
tp := reflect.TypeOf(receiver)
|
||||
if len(receiverName) == 0 {
|
||||
receiverName = tp.Elem().Name()
|
||||
}
|
||||
|
||||
var connfunc connFuncType
|
||||
var disconnfunc disconnFuncType
|
||||
|
||||
for i := 0; i < tp.NumMethod(); i++ {
|
||||
method := tp.Method(i)
|
||||
if method.Type.In(0) != tp {
|
||||
continue
|
||||
}
|
||||
|
||||
if method.Name == ClientConnected {
|
||||
if method.Type.NumIn() != 3 {
|
||||
continue
|
||||
}
|
||||
if method.Type.In(1) != reflect.TypeOf((*Conn)(nil)) {
|
||||
continue
|
||||
}
|
||||
if method.Type.In(2) != reflect.TypeOf((*Sender)(nil)) {
|
||||
continue
|
||||
}
|
||||
funcptr := method.Func.Pointer()
|
||||
p1 := unsafe.Pointer(&funcptr)
|
||||
p2 := unsafe.Pointer(&p1)
|
||||
connfuncptr := (*func(*T, *Conn, *Sender))(p2)
|
||||
|
||||
connfunc = func(c *Conn, s *Sender) {
|
||||
(*connfuncptr)(receiver, c, s)
|
||||
}
|
||||
} else if method.Name == ClientDisconnected {
|
||||
if method.Type.NumIn() != 3 {
|
||||
continue
|
||||
}
|
||||
if method.Type.In(1) != reflect.TypeOf("") {
|
||||
continue
|
||||
}
|
||||
if method.Type.In(2) != reflect.TypeOf((*Sender)(nil)) {
|
||||
continue
|
||||
}
|
||||
funcptr := method.Func.Pointer()
|
||||
p1 := unsafe.Pointer(&funcptr)
|
||||
p2 := unsafe.Pointer(&p1)
|
||||
disconnfuncptr := (*func(*T, string, *Sender))(p2)
|
||||
|
||||
disconnfunc = func(msg string, s *Sender) {
|
||||
(*disconnfuncptr)(receiver, msg, s)
|
||||
}
|
||||
} else {
|
||||
if method.Type.NumIn() != 2 {
|
||||
continue
|
||||
}
|
||||
if method.Type.In(1) != reflect.TypeOf((*ApiCallContext)(nil)).Elem() {
|
||||
continue
|
||||
}
|
||||
|
||||
funcptr := method.Func.Pointer()
|
||||
p1 := unsafe.Pointer(&funcptr)
|
||||
p2 := unsafe.Pointer(&p1)
|
||||
apifuncptr := (*func(*T, ApiCallContext))(p2)
|
||||
methods[receiverName+"."+method.Name] = func(ctx ApiCallContext) {
|
||||
(*apifuncptr)(receiver, ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return WebsocketApiHandler{
|
||||
methods: methods,
|
||||
connfunc: connfunc,
|
||||
disconnfunc: disconnfunc,
|
||||
originalReceiverName: tp.Elem().Name(),
|
||||
}
|
||||
}
|
||||
|
||||
type WebsocketApiBroker struct {
|
||||
methods map[string]apiFuncType
|
||||
methods_dup map[string][]apiFuncType
|
||||
connFuncs []connFuncType
|
||||
disconnFuncs []disconnFuncType
|
||||
}
|
||||
|
||||
func (hc *WebsocketApiBroker) AddHandler(receiver WebsocketApiHandler) {
|
||||
if hc.methods == nil {
|
||||
hc.methods = make(map[string]apiFuncType)
|
||||
hc.methods_dup = make(map[string][]apiFuncType)
|
||||
}
|
||||
|
||||
for k, v := range receiver.methods {
|
||||
ab := strings.Split(k, ".")
|
||||
logger.Printf("ws api registered : %s.%s -> %s\n", receiver.originalReceiverName, ab[1], k)
|
||||
|
||||
hc.methods_dup[k] = append(hc.methods_dup[k], v)
|
||||
if len(hc.methods_dup[k]) > 1 {
|
||||
chain := hc.methods_dup[k]
|
||||
hc.methods[k] = func(ctx ApiCallContext) {
|
||||
for _, f := range chain {
|
||||
f(ctx)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hc.methods[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
if receiver.connfunc != nil {
|
||||
logger.Printf("ws api registered : %s.ClientConnected\n", receiver.originalReceiverName)
|
||||
hc.connFuncs = append(hc.connFuncs, receiver.connfunc)
|
||||
}
|
||||
|
||||
if receiver.disconnfunc != nil {
|
||||
// disconnfunc은 역순
|
||||
logger.Printf("ws api registered : %s.ClientDisconnected\n", receiver.originalReceiverName)
|
||||
hc.disconnFuncs = append([]disconnFuncType{receiver.disconnfunc}, hc.disconnFuncs...)
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *WebsocketApiBroker) ClientConnected(c *wsconn) {
|
||||
for _, v := range hc.connFuncs {
|
||||
v(c.Conn, c.sender)
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *WebsocketApiBroker) ClientDisconnected(c *wsconn) {
|
||||
for _, v := range hc.disconnFuncs {
|
||||
v(c.closeMessage, c.sender)
|
||||
}
|
||||
}
|
||||
|
||||
func (hc *WebsocketApiBroker) Call(callby *Sender, funcname string, r io.Reader) {
|
||||
if found := hc.methods[funcname]; found != nil {
|
||||
var args []any
|
||||
if r != nil {
|
||||
dec := json.NewDecoder(r)
|
||||
if err := dec.Decode(&args); err != nil {
|
||||
logger.Println("WebsocketApiBroker.Call failed. decode returns err :", err)
|
||||
}
|
||||
}
|
||||
|
||||
found(ApiCallContext{
|
||||
CallBy: callby,
|
||||
Arguments: args,
|
||||
})
|
||||
} else {
|
||||
logger.Println("api is not found :", funcname)
|
||||
}
|
||||
}
|
||||
66
wshandler/api_handler_test.go
Normal file
66
wshandler/api_handler_test.go
Normal file
@ -0,0 +1,66 @@
|
||||
// package main ...
|
||||
package wshandler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type TestReceiver struct {
|
||||
}
|
||||
|
||||
func (tr *TestReceiver) Func1([]any) {
|
||||
|
||||
}
|
||||
|
||||
func (tr *TestReceiver) Func2(args []any) {
|
||||
fmt.Println(args...)
|
||||
}
|
||||
|
||||
func TestUnmarshalToken(t *testing.T) {
|
||||
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7
|
||||
// 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
|
||||
insrc := []byte(`["string value 1",200,["inner string value 1","inner string value 2"],{"inner map key 1":"inner map string value 1","inner map key 2":"inner map string value 2"},500.1]`)
|
||||
|
||||
dec := json.NewDecoder(bytes.NewBuffer(insrc))
|
||||
dec.Token()
|
||||
|
||||
for {
|
||||
token_start := dec.InputOffset()
|
||||
tok, _ := dec.Token()
|
||||
token_end := dec.InputOffset()
|
||||
|
||||
var string_val_1 string
|
||||
stringtype := reflect.TypeOf(string_val_1)
|
||||
stringvalue := reflect.New(stringtype)
|
||||
castptr := stringvalue.Interface()
|
||||
|
||||
err := json.Unmarshal(insrc[token_start:token_end], castptr)
|
||||
fmt.Println(err)
|
||||
|
||||
if tok == nil {
|
||||
break
|
||||
}
|
||||
fmt.Println(tok, dec.InputOffset())
|
||||
}
|
||||
// src := []any{"a", 1, false}
|
||||
// payload, _ := json.Marshal(src)
|
||||
|
||||
// tr := new(TestReceiver)
|
||||
// receiver := MakeWebsocketApiHandler(tr, "test")
|
||||
|
||||
// var con WebsocketApiBroker
|
||||
// con.AddHandler(receiver)
|
||||
|
||||
}
|
||||
func TestUnmarshal(t *testing.T) {
|
||||
src := []byte(`{"123" :"str1", "456": "str2"}`)
|
||||
var test map[int]string
|
||||
err := json.Unmarshal(src, &test)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
1
wshandler/config.json
Normal file
1
wshandler/config.json
Normal file
@ -0,0 +1 @@
|
||||
{}
|
||||
108
wshandler/room.go
Normal file
108
wshandler/room.go
Normal file
@ -0,0 +1,108 @@
|
||||
package wshandler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
)
|
||||
|
||||
type room struct {
|
||||
inChan chan *wsconn
|
||||
outChan chan primitive.ObjectID
|
||||
messageChan chan *UpstreamMessage
|
||||
name string
|
||||
destroyChan chan<- string
|
||||
sendMsgChan chan<- send_msg_queue_elem
|
||||
}
|
||||
|
||||
// 만약 destroyChan가 nil이면 room이 비어도 파괴되지 않는다. 영구 유지되는 room
|
||||
func makeRoom(name string, destroyChan chan<- string, sendMsgChan chan<- send_msg_queue_elem) *room {
|
||||
return &room{
|
||||
inChan: make(chan *wsconn, 10),
|
||||
outChan: make(chan primitive.ObjectID, 10),
|
||||
messageChan: make(chan *UpstreamMessage, 100),
|
||||
name: name,
|
||||
destroyChan: destroyChan,
|
||||
sendMsgChan: sendMsgChan,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *room) broadcast(msg *UpstreamMessage) {
|
||||
r.messageChan <- msg
|
||||
}
|
||||
|
||||
func (r *room) in(conn *wsconn) *room {
|
||||
r.inChan <- conn
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *room) out(accid primitive.ObjectID) *room {
|
||||
r.outChan <- accid
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *room) start(ctx context.Context) {
|
||||
go func(ctx context.Context) {
|
||||
conns := make(map[string]*wsconn)
|
||||
normal := false
|
||||
for !normal {
|
||||
normal = r.loop(ctx, &conns)
|
||||
}
|
||||
}(ctx)
|
||||
}
|
||||
|
||||
func (r *room) loop(ctx context.Context, conns *map[string]*wsconn) (normalEnd bool) {
|
||||
defer func() {
|
||||
s := recover()
|
||||
if s != nil {
|
||||
logger.Error(s)
|
||||
normalEnd = false
|
||||
}
|
||||
}()
|
||||
|
||||
tag := "#" + r.name
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return true
|
||||
|
||||
case conn := <-r.inChan:
|
||||
(*conns)[conn.sender.Accid.Hex()] = conn
|
||||
|
||||
case accid := <-r.outChan:
|
||||
delete((*conns), accid.Hex())
|
||||
if len(*conns) == 0 && r.destroyChan != nil {
|
||||
r.destroyChan <- r.name
|
||||
return true
|
||||
}
|
||||
|
||||
case msg := <-r.messageChan:
|
||||
ds := DownstreamMessage{
|
||||
Alias: msg.Alias,
|
||||
Body: msg.Body,
|
||||
Tag: append(msg.Tag, tag),
|
||||
}
|
||||
|
||||
buff := new(bytes.Buffer)
|
||||
enc := json.NewEncoder(buff)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.Encode(ds)
|
||||
|
||||
for _, conn := range *conns {
|
||||
pmsg, err := websocket.NewPreparedMessage(websocket.TextMessage, buff.Bytes())
|
||||
if err != nil {
|
||||
logger.Println("websocket.NewPreparedMessage failed :", err)
|
||||
} else {
|
||||
r.sendMsgChan <- send_msg_queue_elem{
|
||||
to: conn.Conn,
|
||||
pmsg: pmsg,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
389
wshandler/wshandler_peer.go
Normal file
389
wshandler/wshandler_peer.go
Normal file
@ -0,0 +1,389 @@
|
||||
package wshandler
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.mongodb.org/mongo-driver/bson/primitive"
|
||||
"repositories.action2quare.com/ayo/gocommon"
|
||||
"repositories.action2quare.com/ayo/gocommon/logger"
|
||||
"repositories.action2quare.com/ayo/gocommon/session"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type WebsocketPeerHandler interface {
|
||||
RegisterHandlers(serveMux gocommon.ServerMuxInterface, prefix string) error
|
||||
}
|
||||
|
||||
type peerCtorChannelValue struct {
|
||||
accid primitive.ObjectID
|
||||
conn *Conn
|
||||
}
|
||||
|
||||
type peerDtorChannelValue struct {
|
||||
accid primitive.ObjectID
|
||||
sk string
|
||||
}
|
||||
|
||||
type websocketPeerHandler[T PeerInterface] struct {
|
||||
methods map[string]peerApiFuncType[T]
|
||||
createPeer func(primitive.ObjectID) T
|
||||
sessionConsumer session.Consumer
|
||||
|
||||
peerCtorChannel chan peerCtorChannelValue
|
||||
peerDtorChannel chan peerDtorChannelValue
|
||||
}
|
||||
|
||||
type PeerInterface interface {
|
||||
ClientDisconnected(string)
|
||||
ClientConnected(*Conn)
|
||||
}
|
||||
type peerApiFuncType[T PeerInterface] func(T, io.Reader) (any, error)
|
||||
|
||||
type websocketPeerApiHandler[T PeerInterface] struct {
|
||||
methods map[string]peerApiFuncType[T]
|
||||
originalReceiverName string
|
||||
}
|
||||
|
||||
func (hc *websocketPeerHandler[T]) call(recv T, funcname string, r io.Reader) (v any, e error) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r != nil {
|
||||
logger.Error(r)
|
||||
e = fmt.Errorf("%v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
if found := hc.methods[funcname]; found != nil {
|
||||
return found(recv, r)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("api is not found : %s", funcname)
|
||||
}
|
||||
|
||||
func makeWebsocketPeerApiHandler[T PeerInterface]() websocketPeerApiHandler[T] {
|
||||
methods := make(map[string]peerApiFuncType[T])
|
||||
|
||||
var archetype T
|
||||
tp := reflect.TypeOf(archetype)
|
||||
|
||||
for i := 0; i < tp.NumMethod(); i++ {
|
||||
method := tp.Method(i)
|
||||
if method.Type.In(0) != tp {
|
||||
continue
|
||||
}
|
||||
|
||||
if method.Name == ClientDisconnected {
|
||||
continue
|
||||
}
|
||||
|
||||
var intypes []reflect.Type
|
||||
for i := 1; i < method.Type.NumIn(); i++ {
|
||||
intypes = append(intypes, method.Type.In(i))
|
||||
}
|
||||
|
||||
var outconv func([]reflect.Value) (any, error)
|
||||
if method.Type.NumOut() == 0 {
|
||||
outconv = func([]reflect.Value) (any, error) { return nil, nil }
|
||||
} else if method.Type.NumOut() == 1 {
|
||||
if method.Type.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
|
||||
outconv = func(out []reflect.Value) (any, error) {
|
||||
if out[0].Interface() == nil {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, out[0].Interface().(error)
|
||||
}
|
||||
} else {
|
||||
outconv = func(out []reflect.Value) (any, error) {
|
||||
return out[0].Interface(), nil
|
||||
}
|
||||
}
|
||||
} else if method.Type.NumOut() == 2 && method.Type.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
|
||||
outconv = func(out []reflect.Value) (any, error) {
|
||||
if out[1].Interface() == nil {
|
||||
return out[0].Interface(), nil
|
||||
}
|
||||
return out[0].Interface(), out[1].Interface().(error)
|
||||
}
|
||||
}
|
||||
|
||||
methods[method.Name] = func(recv T, r io.Reader) (any, error) {
|
||||
decoder := json.NewDecoder(r)
|
||||
inargs := make([]any, len(intypes))
|
||||
|
||||
for i, intype := range intypes {
|
||||
zerovalueptr := reflect.New(intype)
|
||||
inargs[i] = zerovalueptr.Interface()
|
||||
}
|
||||
|
||||
err := decoder.Decode(&inargs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
reflectargs := make([]reflect.Value, 0, len(inargs)+1)
|
||||
reflectargs = append(reflectargs, reflect.ValueOf(recv))
|
||||
for _, p := range inargs {
|
||||
reflectargs = append(reflectargs, reflect.ValueOf(p).Elem())
|
||||
}
|
||||
|
||||
return outconv(method.Func.Call(reflectargs))
|
||||
}
|
||||
}
|
||||
|
||||
return websocketPeerApiHandler[T]{
|
||||
methods: methods,
|
||||
originalReceiverName: tp.Elem().Name(),
|
||||
}
|
||||
}
|
||||
|
||||
func NewWebsocketPeerHandler[T PeerInterface](consumer session.Consumer, creator func(primitive.ObjectID) T) WebsocketPeerHandler {
|
||||
methods := make(map[string]peerApiFuncType[T])
|
||||
receiver := makeWebsocketPeerApiHandler[T]()
|
||||
|
||||
for k, v := range receiver.methods {
|
||||
logger.Printf("ws api registered : %s.%s\n", receiver.originalReceiverName, k)
|
||||
methods[k] = v
|
||||
}
|
||||
|
||||
wsh := &websocketPeerHandler[T]{
|
||||
sessionConsumer: consumer,
|
||||
methods: methods,
|
||||
createPeer: creator,
|
||||
peerCtorChannel: make(chan peerCtorChannelValue),
|
||||
peerDtorChannel: make(chan peerDtorChannelValue),
|
||||
}
|
||||
|
||||
consumer.RegisterOnSessionInvalidated(wsh.onSessionInvalidated)
|
||||
return wsh
|
||||
}
|
||||
|
||||
func (ws *websocketPeerHandler[T]) RegisterHandlers(serveMux gocommon.ServerMuxInterface, prefix string) error {
|
||||
if *noAuthFlag {
|
||||
serveMux.HandleFunc(prefix, ws.upgrade_noauth)
|
||||
} else {
|
||||
serveMux.HandleFunc(prefix, ws.upgrade)
|
||||
}
|
||||
go ws.sessionMonitoring()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ws *websocketPeerHandler[T]) onSessionInvalidated(accid primitive.ObjectID) {
|
||||
ws.peerDtorChannel <- peerDtorChannelValue{
|
||||
accid: accid,
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *websocketPeerHandler[T]) sessionMonitoring() {
|
||||
all := make(map[primitive.ObjectID]*Conn)
|
||||
unauthdata := []byte{0x03, 0xec}
|
||||
unauthdata = append(unauthdata, []byte("unauthorized")...)
|
||||
for {
|
||||
select {
|
||||
case estVal := <-ws.peerCtorChannel:
|
||||
all[estVal.accid] = estVal.conn
|
||||
case disVal := <-ws.peerDtorChannel:
|
||||
if c := all[disVal.accid]; c != nil {
|
||||
c.MakeWriter().WriteControl(websocket.CloseMessage, unauthdata, time.Time{})
|
||||
delete(all, disVal.accid)
|
||||
}
|
||||
|
||||
if len(disVal.sk) > 0 {
|
||||
ws.sessionConsumer.Revoke(disVal.sk)
|
||||
delete(all, disVal.accid)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ws *websocketPeerHandler[T]) upgrade_core(conn *Conn, accid primitive.ObjectID, sk string) {
|
||||
go func(c *Conn, accid primitive.ObjectID, sk string) {
|
||||
peer := ws.createPeer(accid)
|
||||
var closeReason string
|
||||
|
||||
peer.ClientConnected(conn)
|
||||
ws.peerCtorChannel <- peerCtorChannelValue{accid: accid, conn: conn}
|
||||
|
||||
defer func() {
|
||||
ws.peerDtorChannel <- peerDtorChannelValue{accid: accid, sk: sk}
|
||||
peer.ClientDisconnected(closeReason)
|
||||
}()
|
||||
|
||||
response := make([]byte, 255)
|
||||
writer := c.MakeWriter()
|
||||
for {
|
||||
response = response[:5]
|
||||
messageType, r, err := c.NextReader()
|
||||
if err != nil {
|
||||
if ce, ok := err.(*websocket.CloseError); ok {
|
||||
closeReason = ce.Text
|
||||
}
|
||||
c.Close()
|
||||
break
|
||||
}
|
||||
|
||||
if messageType == websocket.CloseMessage {
|
||||
closeMsg, _ := io.ReadAll(r)
|
||||
closeReason = string(closeMsg)
|
||||
break
|
||||
}
|
||||
|
||||
if messageType == websocket.BinaryMessage {
|
||||
var flag [1]byte
|
||||
r.Read(flag[:])
|
||||
if flag[0] == 0xff {
|
||||
// nonce
|
||||
r.Read(response[1:5])
|
||||
|
||||
var size [1]byte
|
||||
r.Read(size[:])
|
||||
|
||||
cmd := make([]byte, size[0])
|
||||
r.Read(cmd)
|
||||
|
||||
result, err := ws.call(peer, string(cmd), r)
|
||||
|
||||
if err != nil {
|
||||
response[0] = 21 // 21 : Negative Ack
|
||||
response = append(response, []byte(err.Error())...)
|
||||
} else {
|
||||
response[0] = 6 // 6 : Acknowledgement
|
||||
|
||||
switch result := result.(type) {
|
||||
case string:
|
||||
response = append(response, []byte(result)...)
|
||||
|
||||
case int8, int16, int32, int64, uint8, uint16, uint32, uint64:
|
||||
response = append(response, []byte(fmt.Sprintf("%d", result))...)
|
||||
|
||||
case float32, float64:
|
||||
response = append(response, []byte(fmt.Sprintf("%f", result))...)
|
||||
|
||||
case []byte:
|
||||
response = append(response, result...)
|
||||
|
||||
default:
|
||||
j, _ := json.Marshal(result)
|
||||
response = append(response, j...)
|
||||
}
|
||||
}
|
||||
pmsg, err := websocket.NewPreparedMessage(websocket.BinaryMessage, response)
|
||||
if err != nil {
|
||||
logger.Println("websocket.NewPreparedMessage failed :", err)
|
||||
} else {
|
||||
writer.WritePreparedMessage(pmsg)
|
||||
}
|
||||
} else {
|
||||
cmd := make([]byte, flag[0])
|
||||
r.Read(cmd)
|
||||
ws.call(peer, string(cmd), r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}(conn, accid, sk)
|
||||
}
|
||||
|
||||
func (ws *websocketPeerHandler[T]) upgrade_noauth(w http.ResponseWriter, r *http.Request) {
|
||||
// 클라이언트 접속
|
||||
defer func() {
|
||||
s := recover()
|
||||
if s != nil {
|
||||
logger.Error(s)
|
||||
}
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}()
|
||||
|
||||
sk := r.Header.Get("AS-X-SESSION")
|
||||
var accid primitive.ObjectID
|
||||
if len(sk) > 0 {
|
||||
authinfo := ws.sessionConsumer.Query(sk)
|
||||
if !authinfo.Valid() {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
accid = authinfo.Account
|
||||
}
|
||||
|
||||
if accid.IsZero() {
|
||||
auth := strings.Split(r.Header.Get("Authorization"), " ")
|
||||
if len(auth) != 2 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
temp, err := hex.DecodeString(auth[1])
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if len(temp) != len(primitive.NilObjectID) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
raw := (*[12]byte)(temp)
|
||||
accid = primitive.ObjectID(*raw)
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{} // use default options
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// var alias string
|
||||
// if v := r.Header.Get("AS-X-ALIAS"); len(v) > 0 {
|
||||
// vt, _ := base64.StdEncoding.DecodeString(v)
|
||||
// alias = string(vt)
|
||||
// } else {
|
||||
// alias = accid.Hex()
|
||||
// }
|
||||
|
||||
ws.upgrade_core(&Conn{innerConn: conn}, accid, sk)
|
||||
}
|
||||
|
||||
func (ws *websocketPeerHandler[T]) upgrade(w http.ResponseWriter, r *http.Request) {
|
||||
// 클라이언트 접속
|
||||
defer func() {
|
||||
s := recover()
|
||||
if s != nil {
|
||||
logger.Error(s)
|
||||
}
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}()
|
||||
|
||||
sk := r.Header.Get("AS-X-SESSION")
|
||||
authinfo := ws.sessionConsumer.Query(sk)
|
||||
if !authinfo.Valid() {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
var upgrader = websocket.Upgrader{} // use default options
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// var alias string
|
||||
// if v := r.Header.Get("AS-X-ALIAS"); len(v) > 0 {
|
||||
// vt, _ := base64.StdEncoding.DecodeString(v)
|
||||
// alias = string(vt)
|
||||
// } else {
|
||||
// alias = authinfo.Account.Hex()
|
||||
// }
|
||||
ws.upgrade_core(makeConn(conn), authinfo.Account, sk)
|
||||
}
|
||||
@ -13,7 +13,6 @@ import (
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
@ -235,7 +234,7 @@ func deflate(inflated []byte) string {
|
||||
|
||||
zr := flate.NewReader(byteReader)
|
||||
if _, err := io.Copy(wBuf, zr); err != nil {
|
||||
log.Fatal(err)
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return wBuf.String()
|
||||
|
||||
Reference in New Issue
Block a user