Skip to content

Commit

Permalink
Refactor Params -> ClientOptions and logging
Browse files Browse the repository at this point in the history
Closes ably#15.
  • Loading branch information
rjeczalik committed Apr 18, 2015
1 parent c286e79 commit 794fbc3
Show file tree
Hide file tree
Showing 10 changed files with 119 additions and 107 deletions.
19 changes: 0 additions & 19 deletions ably/ably_logger.go

This file was deleted.

14 changes: 7 additions & 7 deletions ably/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,28 +71,28 @@ func (t *TokenRequest) Sign(secret string) {
}

type Auth struct {
Params
ClientOptions
client *RestClient
}

func NewAuth(params Params, client *RestClient) *Auth {
func NewAuth(params ClientOptions, client *RestClient) *Auth {
return &Auth{
Params: params,
client: client,
ClientOptions: params,
client: client,
}
}

func (a *Auth) CreateTokenRequest(ttl int, capability Capability) *TokenRequest {
req := &TokenRequest{
ID: a.AppID,
ID: a.ApiID,
TTL: ttl,
Capability: capability,
ClientID: a.ClientID,
Timestamp: time.Now().Unix(),
Nonce: random.String(32),
}

req.Sign(a.AppSecret)
req.Sign(a.ApiSecret)

return req
}
Expand All @@ -101,7 +101,7 @@ func (a *Auth) RequestToken(ttl int, capability Capability) (*Token, error) {
req := a.CreateTokenRequest(ttl, capability)

res := &tokenResponse{}
_, err := a.client.Post("/keys/"+a.AppID+"/requestToken", req, res)
_, err := a.client.Post("/keys/"+a.ApiID+"/requestToken", req, res)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions ably/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ var _ = Describe("Auth", func() {
token, err := client.Auth.RequestToken(ttl, capability)

Expect(err).NotTo(HaveOccurred())
Expect(token.ID).To(ContainSubstring(testApp.Config.AppID))
Expect(token.ID).To(ContainSubstring(testApp.Config.ApiID))
Expect(token.Key).To(Equal(testApp.AppKeyId()))
Expect(token.Capability).To(Equal(capability))
})
Expand All @@ -27,7 +27,7 @@ var _ = Describe("Auth", func() {
capability := ably.Capability{"foo": []string{"publish"}}
tokenRequest := client.Auth.CreateTokenRequest(ttl, capability)

Expect(tokenRequest.ID).To(ContainSubstring(testApp.Config.AppID))
Expect(tokenRequest.ID).To(ContainSubstring(testApp.Config.ApiID))
Expect(tokenRequest.Mac).NotTo(BeNil())
})
})
Expand Down
47 changes: 47 additions & 0 deletions ably/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package ably

import (
"log"
"os"
)

const (
LogError = 1 + iota
LogWarn
LogInfo
LogVerbose
)

var logLevels = map[int]string{
LogError: "ERROR: ",
LogWarn: "WARN: ",
LogInfo: "INFO: ",
LogVerbose: "VERBOSE: ",
}

var Log = Logger{
Logger: log.New(os.Stdout, "", log.Lmicroseconds|log.Lshortfile),
Level: LogError,
}

type Logger struct {
Logger *log.Logger
Level int
}

func (l Logger) Print(level int, v ...interface{}) {
if l.Level >= level {
if prefix, ok := logLevels[level]; ok {
v = append(v, interface{}(nil))
copy(v[1:], v)
v[0] = prefix
}
l.Logger.Print(v...)
}
}

func (l Logger) Printf(level int, format string, v ...interface{}) {
if l.Level >= level {
l.Logger.Printf(logLevels[level]+format, v...)
}
}
54 changes: 17 additions & 37 deletions ably/params.go → ably/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,67 +2,48 @@ package ably

import (
"fmt"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)

type ProtocolType string

const (
ProtocolJSON = "json"
ProtocolMsgPack = "msgpack"
)

type Params struct {
type ClientOptions struct {
RealtimeEndpoint string
RestEndpoint string

ApiKey string
ClientID string
AppID string
AppSecret string
UseTokenAuth bool

Protocol ProtocolType
Tls bool
Key string
ClientID string
ApiID string
ApiSecret string
UseTokenAuth bool
Protocol string
NoTLS bool

HTTPClient *http.Client

AblyLogger *AblyLogger
LogLevel string
}

func (p *Params) Prepare() {
p.setLogger()

if p.ApiKey != "" {
p.parseApiKey()
func (p *ClientOptions) Prepare() {
if p.Key != "" {
p.parseKey()
}
}

func (p *Params) parseApiKey() {
keyParts := strings.Split(p.ApiKey, ":")
func (p *ClientOptions) parseKey() {
keyParts := strings.Split(p.Key, ":")

if len(keyParts) != 2 {
p.AblyLogger.Error("ApiKey doesn't use the right format. Ignoring this parameter.")
Log.Print(LogError, "invalid key format, ignoring")
return
}

p.AppID = keyParts[0]
p.AppSecret = keyParts[1]
}

func (p *Params) setLogger() {
if p.AblyLogger == nil {
p.AblyLogger = &AblyLogger{
Logger: log.New(os.Stdout, "", log.Lmicroseconds|log.Lshortfile),
}
}
p.ApiID = keyParts[0]
p.ApiSecret = keyParts[1]
}

// This needs to use a timestamp in millisecond
Expand All @@ -89,7 +70,7 @@ func (t *TimestampMillisecond) ToInt() int64 {

func (s *ScopeParams) EncodeValues(out *url.Values) error {
if s.Start != 0 && s.End != 0 && s.Start > s.End {
return fmt.Errorf("ScopeParams.Start can not be after ScopeParams.End")
return fmt.Errorf("start must be before end")
}

if s.Start != 0 {
Expand All @@ -110,7 +91,6 @@ func (s *ScopeParams) EncodeValues(out *url.Values) error {
type PaginateParams struct {
Limit int
Direction string

ScopeParams
}

Expand Down
36 changes: 20 additions & 16 deletions ably/params_test.go → ably/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,40 +13,44 @@ import (

var _ = Describe("Params", func() {
var (
params *ably.Params
buffer *gbytes.Buffer
options *ably.ClientOptions
buffer *gbytes.Buffer
)

BeforeEach(func() {
buffer = gbytes.NewBuffer()

params = &ably.Params{
ApiKey: "id:secret",
options = &ably.ClientOptions{
Key: "id:secret",
}

params.Prepare()
options.Prepare()
})

It("parses ApiKey into a set of known parameters", func() {
Expect(params.AppID).To(Equal("id"))
Expect(params.AppSecret).To(Equal("secret"))
It("parses Key into a set of known parameters", func() {
Expect(options.ApiID).To(Equal("id"))
Expect(options.ApiSecret).To(Equal("secret"))
})

Context("when ApiKey is invalid", func() {
Context("when Key is invalid", func() {
var old *log.Logger

BeforeEach(func() {
params = &ably.Params{
ApiKey: "invalid",
AblyLogger: &ably.AblyLogger{
Logger: log.New(buffer, "", log.Lmicroseconds|log.Llongfile),
},
old, ably.Log.Logger = ably.Log.Logger, log.New(buffer, "", log.Lmicroseconds|log.Llongfile)
options = &ably.ClientOptions{
Key: "invalid",
}

params.Prepare()
options.Prepare()
})

AfterEach(func() {
ably.Log.Logger = old
})

It("prints an error", func() {
Expect(string(buffer.Contents())).To(
ContainSubstring("ERRO: ApiKey doesn't use the right format. Ignoring this parameter"),
ContainSubstring("ERROR: invalid key format, ignoring"),
)
})
})
Expand Down
14 changes: 7 additions & 7 deletions ably/realtime_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@ import (
"github.com/ably/ably-go/ably/proto"
)

func NewRealtimeClient(params Params) *RealtimeClient {
func NewRealtimeClient(params ClientOptions) *RealtimeClient {
params.Prepare()
c := &RealtimeClient{
Params: params,
Err: make(chan error),
rest: NewRestClient(params),
channels: make(map[string]*RealtimeChannel),
Connection: NewConn(params),
ClientOptions: params,
Err: make(chan error),
rest: NewRestClient(params),
channels: make(map[string]*RealtimeChannel),
Connection: NewConn(params),
}
go c.connect()
return c
}

type RealtimeClient struct {
Params
ClientOptions
Err chan error

rest *RestClient
Expand Down
18 changes: 9 additions & 9 deletions ably/realtime_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const (
type ConnListener func()

type Conn struct {
Params
ClientOptions

ID string
stateChan chan ConnState
Expand All @@ -42,13 +42,13 @@ type Conn struct {
listenerMtx sync.RWMutex
}

func NewConn(params Params) *Conn {
func NewConn(params ClientOptions) *Conn {
c := &Conn{
Params: params,
state: ConnStateInitialized,
stateChan: make(chan ConnState),
Ch: make(chan *proto.ProtocolMessage),
Err: make(chan error),
ClientOptions: params,
state: ConnStateInitialized,
stateChan: make(chan ConnState),
Ch: make(chan *proto.ProtocolMessage),
Err: make(chan error),
}
go c.watchConnectionState()
return c
Expand Down Expand Up @@ -87,7 +87,7 @@ func (c *Conn) Close() {
}

func (c *Conn) websocketUrl(token *Token) (*url.URL, error) {
u, err := url.Parse(c.Params.RealtimeEndpoint + "?access_token=" + token.ID + "&binary=false&timestamp=" + strconv.Itoa(int(time.Now().Unix())))
u, err := url.Parse(c.ClientOptions.RealtimeEndpoint + "?access_token=" + token.ID + "&binary=false&timestamp=" + strconv.Itoa(int(time.Now().Unix())))
if err != nil {
return nil, err
}
Expand All @@ -104,7 +104,7 @@ func (c *Conn) Connect() error {

c.setState(ConnStateConnecting)

restRealtimeClient := NewRestClient(c.Params)
restRealtimeClient := NewRestClient(c.ClientOptions)
token, err := restRealtimeClient.Auth.RequestToken(60*60, Capability{"*": []string{"*"}})
if err != nil {
return fmt.Errorf("Error fetching token: %s", err)
Expand Down
Loading

0 comments on commit 794fbc3

Please sign in to comment.