-
-
Notifications
You must be signed in to change notification settings - Fork 946
Expand file tree
/
Copy pathwcloud.go
More file actions
349 lines (323 loc) · 9.62 KB
/
wcloud.go
File metadata and controls
349 lines (323 loc) · 9.62 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Copyright 2025, Command Line Inc.
// SPDX-License-Identifier: Apache-2.0
package wcloud
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/wavetermdev/waveterm/pkg/telemetry"
"github.com/wavetermdev/waveterm/pkg/telemetry/telemetrydata"
"github.com/wavetermdev/waveterm/pkg/util/daystr"
"github.com/wavetermdev/waveterm/pkg/wavebase"
)
const WCloudEndpoint = "https://api.waveterm.dev/central"
const WCloudEndpointVarName = "WCLOUD_ENDPOINT"
const WCloudWSEndpoint = "wss://wsapi.waveterm.dev/"
const WCloudWSEndpointVarName = "WCLOUD_WS_ENDPOINT"
const WCloudPingEndpoint = "https://ping.waveterm.dev/central"
const WCloudPingEndpointVarName = "WCLOUD_PING_ENDPOINT"
var WCloudWSEndpoint_VarCache string
var WCloudEndpoint_VarCache string
var WCloudPingEndpoint_VarCache string
const APIVersion = 1
const MaxPtyUpdateSize = (128 * 1024)
const MaxUpdatesPerReq = 10
const MaxUpdatesToDeDup = 1000
const MaxUpdateWriterErrors = 3
const WCloudDefaultTimeout = 5 * time.Second
const WCloudWebShareUpdateTimeout = 15 * time.Second
// setting to 1M to be safe (max is 6M for API-GW + Lambda, but there is base64 encoding and upload time)
// we allow one extra update past this estimated size
const MaxUpdatePayloadSize = 1 * (1024 * 1024)
const TelemetryUrl = "/telemetry"
const TEventsUrl = "/tevents"
const NoTelemetryUrl = "/no-telemetry"
const WebShareUpdateUrl = "/auth/web-share-update"
const PingUrl = "/ping"
func CacheAndRemoveEnvVars() error {
WCloudEndpoint_VarCache = os.Getenv(WCloudEndpointVarName)
err := checkEndpointVar(WCloudEndpoint_VarCache, "wcloud endpoint", WCloudEndpointVarName)
if err != nil {
return err
}
os.Unsetenv(WCloudEndpointVarName)
WCloudWSEndpoint_VarCache = os.Getenv(WCloudWSEndpointVarName)
err = checkWSEndpointVar(WCloudWSEndpoint_VarCache, "wcloud ws endpoint", WCloudWSEndpointVarName)
if err != nil {
return err
}
os.Unsetenv(WCloudWSEndpointVarName)
WCloudPingEndpoint_VarCache = os.Getenv(WCloudPingEndpointVarName)
os.Unsetenv(WCloudPingEndpointVarName)
return nil
}
func checkEndpointVar(endpoint string, debugName string, varName string) error {
if !wavebase.IsDevMode() {
return nil
}
if endpoint == "" || !strings.HasPrefix(endpoint, "https://") {
return fmt.Errorf("invalid %s, %s not set or invalid", debugName, varName)
}
return nil
}
func checkWSEndpointVar(endpoint string, debugName string, varName string) error {
if !wavebase.IsDevMode() {
return nil
}
log.Printf("checking endpoint %q\n", endpoint)
if endpoint == "" || !strings.HasPrefix(endpoint, "wss://") {
return fmt.Errorf("invalid %s, %s not set or invalid", debugName, varName)
}
return nil
}
func GetEndpoint() string {
if !wavebase.IsDevMode() {
return WCloudEndpoint
}
endpoint := WCloudEndpoint_VarCache
return endpoint
}
func GetWSEndpoint() string {
if !wavebase.IsDevMode() {
return WCloudWSEndpoint
}
endpoint := WCloudWSEndpoint_VarCache
return endpoint
}
func GetPingEndpoint() string {
if !wavebase.IsDevMode() {
return WCloudPingEndpoint
}
endpoint := WCloudPingEndpoint_VarCache
return endpoint
}
func makeAnonPostReq(ctx context.Context, apiUrl string, data interface{}) (*http.Request, error) {
endpoint := GetEndpoint()
if endpoint == "" {
return nil, errors.New("wcloud endpoint not set")
}
var dataReader io.Reader
if data != nil {
byteArr, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("error marshaling json for %s request: %v", apiUrl, err)
}
dataReader = bytes.NewReader(byteArr)
}
fullUrl := GetEndpoint() + apiUrl
req, err := http.NewRequestWithContext(ctx, "POST", fullUrl, dataReader)
if err != nil {
return nil, fmt.Errorf("error creating %s request: %v", apiUrl, err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-PromptAPIVersion", strconv.Itoa(APIVersion))
req.Header.Set("X-PromptAPIUrl", apiUrl)
req.Close = true
return req, nil
}
func doRequest(req *http.Request, outputObj interface{}) (*http.Response, error) {
apiUrl := req.Header.Get("X-PromptAPIUrl")
log.Printf("[wcloud] sending request %s %v\n", req.Method, req.URL)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, fmt.Errorf("error contacting wcloud %q service: %v", apiUrl, err)
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return resp, fmt.Errorf("error reading %q response body: %v", apiUrl, err)
}
if resp.StatusCode != http.StatusOK {
return resp, fmt.Errorf("error contacting wcloud %q service: %s", apiUrl, resp.Status)
}
if outputObj != nil && resp.Header.Get("Content-Type") == "application/json" {
err = json.Unmarshal(bodyBytes, outputObj)
if err != nil {
return resp, fmt.Errorf("error decoding json: %v", err)
}
}
return resp, nil
}
type TEventsInputType struct {
ClientId string `json:"clientid"`
Events []*telemetrydata.TEvent `json:"events"`
}
const TEventsBatchSize = 200
const TEventsMaxBatches = 10
// returns (done, num-sent, error)
func sendTEventsBatch(clientId string) (bool, int, error) {
ctx, cancelFn := context.WithTimeout(context.Background(), WCloudDefaultTimeout)
defer cancelFn()
events, err := telemetry.GetNonUploadedTEvents(ctx, TEventsBatchSize)
if err != nil {
return true, 0, fmt.Errorf("cannot get events: %v", err)
}
if len(events) == 0 {
return true, 0, nil
}
input := TEventsInputType{
ClientId: clientId,
Events: events,
}
req, err := makeAnonPostReq(ctx, TEventsUrl, input)
if err != nil {
return true, 0, err
}
startTime := time.Now()
_, err = doRequest(req, nil)
latency := time.Since(startTime)
log.Printf("[wcloud] sent %d tevents (latency: %v)\n", len(events), latency)
if err != nil {
return true, 0, err
}
err = telemetry.MarkTEventsAsUploaded(ctx, events)
if err != nil {
return true, 0, fmt.Errorf("error marking activity as uploaded: %v", err)
}
return len(events) < TEventsBatchSize, len(events), nil
}
func sendTEvents(clientId string) (int, error) {
numIters := 0
totalEvents := 0
for {
numIters++
done, numEvents, err := sendTEventsBatch(clientId)
if err != nil {
log.Printf("error sending telemetry events: %v\n", err)
break
}
totalEvents += numEvents
if done {
break
}
if numIters > TEventsMaxBatches {
log.Printf("sendTEvents, hit %d iterations, stopping\n", numIters)
break
}
}
return totalEvents, nil
}
func SendAllTelemetry(clientId string) error {
ctx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second)
defer cancelFn()
if err := telemetry.CleanOldTEvents(ctx); err != nil {
log.Printf("error cleaning old telemetry events: %v\n", err)
}
if !telemetry.IsTelemetryEnabled() {
log.Printf("telemetry disabled, not sending\n")
return nil
}
_, err := sendTEvents(clientId)
if err != nil {
return err
}
return nil
}
func sendTelemetry(clientId string) error {
ctx, cancelFn := context.WithTimeout(context.Background(), WCloudDefaultTimeout)
defer cancelFn()
activity, err := telemetry.GetNonUploadedActivity(ctx)
if err != nil {
return fmt.Errorf("cannot get activity: %v", err)
}
if len(activity) == 0 {
return nil
}
log.Printf("[wcloud] sending telemetry data\n")
dayStr := daystr.GetCurDayStr()
input := TelemetryInputType{
ClientId: clientId,
UserId: clientId,
AppType: "w2",
AutoUpdateEnabled: telemetry.IsAutoUpdateEnabled(),
AutoUpdateChannel: telemetry.AutoUpdateChannel(),
CurDay: dayStr,
Activity: activity,
}
req, err := makeAnonPostReq(ctx, TelemetryUrl, input)
if err != nil {
return err
}
_, err = doRequest(req, nil)
if err != nil {
return err
}
err = telemetry.MarkActivityAsUploaded(ctx, activity)
if err != nil {
return fmt.Errorf("error marking activity as uploaded: %v", err)
}
return nil
}
func SendNoTelemetryUpdate(ctx context.Context, clientId string, noTelemetryVal bool) error {
req, err := makeAnonPostReq(ctx, NoTelemetryUrl, NoTelemetryInputType{ClientId: clientId, Value: noTelemetryVal})
if err != nil {
return err
}
_, err = doRequest(req, nil)
if err != nil {
return err
}
return nil
}
func makePingPostReq(ctx context.Context, apiUrl string, data interface{}) (*http.Request, error) {
endpoint := GetPingEndpoint()
if endpoint == "" {
return nil, errors.New("wcloud ping endpoint not set")
}
var dataReader io.Reader
if data != nil {
byteArr, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("error marshaling json for %s request: %v", apiUrl, err)
}
dataReader = bytes.NewReader(byteArr)
}
fullUrl := endpoint + apiUrl
req, err := http.NewRequestWithContext(ctx, "POST", fullUrl, dataReader)
if err != nil {
return nil, fmt.Errorf("error creating %s request: %v", apiUrl, err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-PromptAPIVersion", strconv.Itoa(APIVersion))
req.Close = true
return req, nil
}
type PingInputType struct {
ClientId string `json:"clientid"`
Arch string `json:"arch"`
Version string `json:"version"`
LocalDate string `json:"localdate"`
UsageTelemetry bool `json:"usagetelemetry"`
}
func SendDiagnosticPing(ctx context.Context, clientId string, usageTelemetry bool) error {
endpoint := GetPingEndpoint()
if endpoint == "" {
return nil
}
localDate := time.Now().Format("2006-01-02")
input := PingInputType{
ClientId: clientId,
Arch: wavebase.ClientArch(),
Version: "v" + wavebase.WaveVersion,
LocalDate: localDate,
UsageTelemetry: usageTelemetry,
}
req, err := makePingPostReq(ctx, PingUrl, input)
if err != nil {
return err
}
_, err = doRequest(req, nil)
if err != nil {
return err
}
return nil
}