Skip to content

Commit

Permalink
Merge branch 'feat_dev'
Browse files Browse the repository at this point in the history
  • Loading branch information
wangzhiyongcc committed Jan 9, 2023
2 parents 2e170ca + 290d5f4 commit efee1e9
Show file tree
Hide file tree
Showing 14 changed files with 646 additions and 0 deletions.
38 changes: 38 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
MIT License

Copyright 2023 Bytedance Ltd. and/or its affiliates

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

=======================================================================
Douyincloud Configcenter-sdk-golang Subcomponents:

The Douyincloud Configcenter-sdk-golang project contains subcomponents with separate copyright
notices and license terms. Your use of the source code for the these
subcomponents is subject to the terms and conditions of the following
licenses.

========================================================================
MIT licenses
========================================================================

The following components are provided under the MIT License. See project link for details.
The text of each license is the standard MIT license.

avast/retry-go:https://github.com/avast/retry-go MIT
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
本项目是抖音云配置中心的SDK插件,用以访问抖音云配置中心。

## 使用方法
### 获取与安装
```go
go get github.com/bytedance/douyincloud-configcenter-sdk-go
```
### 初始化客户端
**方式一**:直接初始化
```go
Expand Down
142 changes: 142 additions & 0 deletions base/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package base

import (
"context"
"encoding/json"
"errors"
"log"
"strconv"

"github.com/bytedance/douyincloud-configcenter-sdk-go/cache"
error2 "github.com/bytedance/douyincloud-configcenter-sdk-go/error"
"github.com/bytedance/douyincloud-configcenter-sdk-go/http"
"github.com/bytedance/douyincloud-configcenter-sdk-go/openapi"
)

type Client interface {
Get(key string) (string, error)
RefreshConfig() error
}

type internalClient struct {
cache *cache.Cache
ccClient *http.Client
ticker *cache.Ticker
}

func Start() (Client, error) {
config := NewClientConfig()
return StartWithConfig(config)
}

func StartWithConfig(config *clientConfig) (Client, error) {
client := &internalClient{}

client.ccClient = http.NewClient(func(options *http.Options) {
options.Timeout = config.GetTimeout()
})
client.cache = cache.NewCache()

err := updateCache(client.cache, client.ccClient)
if err != nil {
log.Printf("first update cache err, err = %v", err)
return nil, err
}

client.ticker = cache.NewTicker(client.cache, client.ccClient, config.GetUpdateInterval())

log.Println("sdk start finished!")

return client, nil
}

func (c *internalClient) Get(key string) (string, error) {
var value string
var ok bool
v, _, err := c.getWithCache(key)
if err != nil {
return "", err
}
if value, ok = v.Object.(string); !ok {
log.Printf("current type of the key is not string, cur key: %v", key)
return "", errors.New("current type of the key is not string")
}
return value, nil
}

func (c *internalClient) RefreshConfig() error {
err := updateCache(c.cache, c.ccClient)
if err != nil {
log.Printf("update cache err, err = %v", err)
return err
}
return nil
}

func (c *internalClient) getWithCache(key string) (*cache.Item, bool, error) {
item, exist := c.cache.Get(key)
if !exist {
log.Printf("item not exist, current key name: %v", key)
return nil, false, errors.New("item not exist")
}
return item, true, nil

}

func updateCache(cache2 *cache.Cache, ccClient *http.Client) error {
configVersion := cache2.GetVersion()
if configVersion == "" {
configVersion = "0"
}
bodyStruct := openapi.GetConfigListReqBody{Version: configVersion}
jsonByte, _ := json.Marshal(bodyStruct)
body := string(jsonByte)

respBody, _, err := ccClient.CtxHttpPostRaw(context.Background(), body, nil)
if err != nil {
log.Printf("resp err in updateCache, err: %v", err)
return err
}

var resp openapi.GetConfigListResponse
var httpResult openapi.HttpResp
err = json.Unmarshal(respBody, &httpResult)
if err != nil {
log.Printf("json unmarshal err in init config, err: %v", err)
return err
}
resp = httpResult.Data
code := httpResult.Code
msg := httpResult.Msg

if code != 0 {
if code == error2.ConfigServiceNotExist {
log.Println("Please check whether the config center is opened in douyin cloud.")
return errors.New("please check whether the config center is opened in douyin cloud")
}
if code == error2.AuthenticationFailed {
log.Println("Permission denied. You have no permission to access the dyc config center. Please check whether the program is running in dyc cloud or in the ide with dyc plugin.")
return errors.New("permission denied. You have no permission to access the dyc config center. Please check whether the program is running in dyc cloud or in the ide with dyc plugin")
}
log.Printf("Get config from config center err, err: %v", msg)
return errors.New("Get config from config center err, err: " + msg)
}

localVersion, _ := strconv.Atoi(configVersion)
onlineVersion, _ := strconv.Atoi(resp.Version)

if localVersion >= onlineVersion {
return nil
}

items := make(map[string]*cache.Item, len(resp.Kvs))
for _, v := range resp.Kvs {
items[v.Key] = &cache.Item{
Object: v.Value,
Type: v.Type,
}
}
cache2.Set(items)
cache2.SetVersion(resp.Version)
return nil
}
42 changes: 42 additions & 0 deletions base/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package base

import (
"time"
)

const (
DefaultUpdateInterval = 1 * time.Minute
DefaultTimeout = 5 * time.Second
)

type clientConfig struct {
updateInterval time.Duration
timeout time.Duration
}

func NewClientConfig() *clientConfig {
c := &clientConfig{
updateInterval: DefaultUpdateInterval,
timeout: DefaultTimeout,
}
return c
}

func (c *clientConfig) SetUpdateInterval(t time.Duration) {
if t < 10*time.Second {
t = 10 * time.Second
}
c.updateInterval = t
}

func (c *clientConfig) SetTimeout(t time.Duration) {
c.timeout = t
}

func (c *clientConfig) GetUpdateInterval() time.Duration {
return c.updateInterval
}

func (c *clientConfig) GetTimeout() time.Duration {
return c.timeout
}
58 changes: 58 additions & 0 deletions cache/cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package cache

import (
"sync"
)

type Cache struct {
Config map[string]*Item
version string
mu sync.RWMutex
}

// NewCache creates instance of Cache
func NewCache() *Cache {
return &Cache{Config: map[string]*Item{}}
}

type Item struct {
Object interface{}
Type int64
}

func (c *Cache) Set(items map[string]*Item) {
c.mu.Lock()
newKeys := make(map[string]string, len(items))
for k, v := range items {
value := Item{Object: v.Object, Type: v.Type}
c.Config[k] = &value
newKeys[k] = ""
}

for k := range c.Config {
if _, found := newKeys[k]; !found {
delete(c.Config, k)
}
}

c.mu.Unlock()
}

func (c *Cache) Get(k string) (*Item, bool) {
c.mu.RLock()
item, found := c.Config[k]
if !found {
c.mu.RUnlock()
return nil, false
}
c.mu.RUnlock()
return item, true
}

func (c *Cache) SetVersion(version string) {
c.version = version
}

func (c *Cache) GetVersion() string {
return c.version
}
Loading

0 comments on commit efee1e9

Please sign in to comment.