-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathconfig.go
More file actions
255 lines (226 loc) · 9.34 KB
/
Copy pathconfig.go
File metadata and controls
255 lines (226 loc) · 9.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
package pubnub
import (
"fmt"
"log"
"sync"
"github.com/pubnub/go/v9/crypto"
)
const (
presenceTimeout = 0
)
type UserId string
// Config instance is storage for user-provided information which describe further
// PubNub client behaviour. Configuration instance contain additional set of
// properties which allow to perform precise PubNub client configuration.
type Config struct {
sync.RWMutex
PublishKey string // PublishKey you can get it from admin panel (only required if publishing).
SubscribeKey string // SubscribeKey you can get it from admin panel.
SecretKey string // SecretKey (only required for modifying/revealing access permissions).
AuthKey string // AuthKey If Access Manager is utilized, client will use this AuthKey in all restricted requests.
Origin string // Custom Origin if needed
// UUID to be used as a device identifier.
//
//Deprecated: please use SetUserId/GetUserId
UUID string
//DEPRECATED: please use CryptoModule
CipherKey string // If CipherKey is passed, all communications to/from PubNub will be encrypted.
Secure bool // True to use TLS
ConnectTimeout int // net.Dialer.Timeout
NonSubscribeRequestTimeout int // http.Client.Timeout for non-subscribe requests
SubscribeRequestTimeout int // http.Client.Timeout for subscribe requests only
FileUploadRequestTimeout int // http.Client.Timeout File Upload Request only
HeartbeatInterval int // The frequency of the pings to the server to state that the client is active
PresenceTimeout int // The time after which the server will send a timeout for the client
MaximumReconnectionRetries int // The config sets how many times to retry to reconnect before giving up.
MaximumLatencyDataAge int // Max time to store the latency data for telemetry
FilterExpression string // Feature to subscribe with a custom filter expression.
PNReconnectionPolicy ReconnectionPolicy // Reconnection policy selection
Log *log.Logger // Deprecated: Logger instance. Use Loggers instead for enhanced logging.
Loggers []PNLogger // Custom loggers for enhanced logging. If empty, no logging will occur unless the deprecated Log field is set.
SuppressLeaveEvents bool // When true the SDK doesn't send out the leave requests.
DisablePNOtherProcessing bool // PNOther processing looks for pn_other in the JSON on the recevied message
UseHTTP2 bool // When true (the default), the SDK uses a transport that prefers HTTP/2 via TLS ALPN on HTTPS and automatically falls back to HTTP/1.1 when the origin does not advertise HTTP/2.
MessageQueueOverflowCount int // When the limit is exceeded by the number of messages received in a single subscribe request, a status event PNRequestMessageCountExceededCategory is fired.
MaxIdleConnsPerHost int // Used to set the value of HTTP Transport's MaxIdleConnsPerHost.
MaxWorkers int // Number of max workers for Publish and Grant requests
UsePAMV3 bool // Use PAM version 2, Objects requets would still use PAM v3
StoreTokensOnGrant bool // Will store grant v3 tokens in token manager for further use.
FileMessagePublishRetryLimit int // The number of tries made in case of Publish File Message failure.
//DEPRECATED: please use CryptoModule
UseRandomInitializationVector bool // When true the IV will be random for all requests and not just file upload. When false the IV will be hardcoded for all requests except File Upload
CryptoModule crypto.CryptoModule // A cryptography module used for encryption and decryption
validationWarnings []string // Internal field to store validation warnings during config setup
}
// NewDemoConfig initiates the config with demo keys, for tests only.
func NewDemoConfig() *Config {
demoConfig := NewConfigWithUserId(UserId(GenerateUUID()))
demoConfig.PublishKey = "demo"
demoConfig.SubscribeKey = "demo"
demoConfig.SecretKey = "demo"
return demoConfig
}
func NewConfigWithUserId(userId UserId) *Config {
c := Config{
UUID: string(userId),
Origin: "ps.pndsn.com",
Secure: true,
ConnectTimeout: 10,
NonSubscribeRequestTimeout: 10,
SubscribeRequestTimeout: 310,
FileUploadRequestTimeout: 60,
MaximumLatencyDataAge: 60,
MaximumReconnectionRetries: 50,
SuppressLeaveEvents: false,
DisablePNOtherProcessing: false,
PNReconnectionPolicy: PNNonePolicy,
MessageQueueOverflowCount: 100,
MaxIdleConnsPerHost: 30,
MaxWorkers: 20,
UsePAMV3: true,
StoreTokensOnGrant: true,
FileMessagePublishRetryLimit: 5,
UseRandomInitializationVector: true,
UseHTTP2: true,
}
return &c
}
// Deprecated: Please use NewConfigWithUserId
func NewConfig(uuid string) *Config {
return NewConfigWithUserId(UserId(uuid))
}
func (c *Config) checkMinTimeout(timeout int) int {
if timeout < minTimeout {
warning := fmt.Sprintf("PresenceTimeout value %d is less than the min recommended value of %d, adjusting to %d", timeout, minTimeout, minTimeout)
// Store warning to be logged when PubNub instance is created
c.validationWarnings = append(c.validationWarnings, warning)
timeout = minTimeout
}
return timeout
}
// SetPresenceTimeoutWithCustomInterval sets the presence timeout and interval.
// timeout: How long the server will consider the client alive for presence.
// interval: How often the client will announce itself to server.
func (c *Config) SetPresenceTimeoutWithCustomInterval(
timeout, interval int) *Config {
timeout = c.checkMinTimeout(timeout)
c.Lock()
c.PresenceTimeout = timeout
c.HeartbeatInterval = interval
c.Unlock()
return c
}
var minTimeout = 20
// SetPresenceTimeout sets the presence timeout and automatically calulates the preferred timeout value.
// timeout: How long the server will consider the client alive for presence.
func (c *Config) SetPresenceTimeout(timeout int) *Config {
timeout = c.checkMinTimeout(timeout)
return c.SetPresenceTimeoutWithCustomInterval(timeout, (timeout/2)-1)
}
// SetUserId sets userId
func (c *Config) SetUserId(userId UserId) *Config {
c.UUID = string(userId)
return c
}
// GetUserId gets value of userId
func (c *Config) GetUserId() UserId {
return UserId(c.UUID)
}
// secretKeyRedactPrefixLen is the number of leading characters preserved when
// partially redacting a SecretKey for logging (e.g. "sec-c-YT… (len=54)").
const secretKeyRedactPrefixLen = 8
// redactPrefix returns a partially redacted representation of a sensitive value:
// the first prefixLen characters followed by an ellipsis and the total length,
// e.g. "sec-c-YT… (len=54)".
//
// An empty value yields an empty string. To avoid leaking short secrets, any
// value whose length does not exceed prefixLen is fully masked with "***".
func redactPrefix(value string, prefixLen int) string {
if value == "" {
return ""
}
if len(value) <= prefixLen {
return "***"
}
return fmt.Sprintf("%s\u2026 (len=%d)", value[:prefixLen], len(value))
}
// GetLogString returns a formatted string representation of the Config for logging purposes.
// Sensitive fields (SecretKey, CipherKey) are masked.
func (c *Config) GetLogString() string {
c.RLock()
defer c.RUnlock()
maskIfNotEmpty := func(value string) string {
if value != "" {
return "***"
}
return ""
}
cryptoModuleStr := "<nil>"
if c.CryptoModule != nil {
cryptoModuleStr = "<configured>"
}
loggersStr := fmt.Sprintf("%d logger(s)", len(c.Loggers))
return fmt.Sprintf(`Config{
PublishKey: %s
SubscribeKey: %s
SecretKey: %s
AuthKey: %s
Origin: %s
UUID: %s
CipherKey: %s
Secure: %t
ConnectTimeout: %d
NonSubscribeRequestTimeout: %d
SubscribeRequestTimeout: %d
FileUploadRequestTimeout: %d
HeartbeatInterval: %d
PresenceTimeout: %d
MaximumReconnectionRetries: %d
MaximumLatencyDataAge: %d
FilterExpression: %s
PNReconnectionPolicy: %s
SuppressLeaveEvents: %t
DisablePNOtherProcessing: %t
UseHTTP2: %t
MessageQueueOverflowCount: %d
MaxIdleConnsPerHost: %d
MaxWorkers: %d
UsePAMV3: %t
StoreTokensOnGrant: %t
FileMessagePublishRetryLimit: %d
UseRandomInitializationVector: %t
CryptoModule: %s
Loggers: %s
}`,
c.PublishKey,
c.SubscribeKey,
redactPrefix(c.SecretKey, secretKeyRedactPrefixLen),
maskIfNotEmpty(c.AuthKey),
c.Origin,
c.UUID,
maskIfNotEmpty(c.CipherKey),
c.Secure,
c.ConnectTimeout,
c.NonSubscribeRequestTimeout,
c.SubscribeRequestTimeout,
c.FileUploadRequestTimeout,
c.HeartbeatInterval,
c.PresenceTimeout,
c.MaximumReconnectionRetries,
c.MaximumLatencyDataAge,
c.FilterExpression,
c.PNReconnectionPolicy,
c.SuppressLeaveEvents,
c.DisablePNOtherProcessing,
c.UseHTTP2,
c.MessageQueueOverflowCount,
c.MaxIdleConnsPerHost,
c.MaxWorkers,
c.UsePAMV3,
c.StoreTokensOnGrant,
c.FileMessagePublishRetryLimit,
c.UseRandomInitializationVector,
cryptoModuleStr,
loggersStr,
)
}