Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reporter package #116

Merged
merged 18 commits into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 101 additions & 0 deletions x/reporter/reporter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package reporter
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
package reporter
package report


import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math/rand"
"net/http"
)

var debugLog log.Logger = *log.New(io.Discard, "", 0)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should remove all logging from this library.

Suggested change
var debugLog log.Logger = *log.New(io.Discard, "", 0)

var httpClient = &http.Client{}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pass the client to the RemoteReporter

Suggested change
var httpClient = &http.Client{}


type Record struct {
collectorURL string
successSampleRate float64
failureSampleRate float64
success bool
record interface{}
}
amircybersec marked this conversation as resolved.
Show resolved Hide resolved

func Report(r Record) error {

// Perform custom range validation for sampling rate
if r.successSampleRate < 0.0 || r.successSampleRate > 1.0 {
return errors.New("Error: successSampleRate must be between 0 and 1.")
}

if r.failureSampleRate < 0.0 || r.failureSampleRate > 1.0 {
return errors.New("Error: failureSampleRate must be between 0 and 1.")
}

var samplingRate float64
if r.success {
samplingRate = r.successSampleRate
} else {
samplingRate = r.failureSampleRate
}
// Generate a random number between 0 and 1
random := rand.Float64()
if random < samplingRate {
err := sendReport(r.record, r.collectorURL)
if err != nil {
log.Printf("HTTP request failed: %v", err)
return err
} else {
fmt.Println("Report sent")
return nil
}
} else {
fmt.Println("Report was not sent this time")
return nil
}
}

func sendReport(record any, collectorURL string) error {
jsonData, err := json.Marshal(record)
if err != nil {
log.Printf("Error encoding JSON: %s\n", err)
return err
}

req, err := http.NewRequest("POST", collectorURL, bytes.NewReader(jsonData))
if err != nil {
debugLog.Printf("Error creating the HTTP request: %s\n", err)
return err
}

req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := httpClient.Do(req)
amircybersec marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
log.Printf("Error sending the HTTP request: %s\n", err)
return err
}
defer resp.Body.Close()

respBody, err := io.ReadAll(resp.Body)
if err != nil {
debugLog.Printf("Error reading the HTTP response body: %s\n", err)
return err
}
debugLog.Printf("Response: %s\n", respBody)
return nil
}
55 changes: 55 additions & 0 deletions x/reporter/reporter_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright 2023 Jigsaw Operations LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package reporter

import (
"encoding/json"
"fmt"
"testing"
)

// When success is true and random number is less than successSampleRate, report is sent successfully
func TestSendReportSuccessfully(t *testing.T) {
// Example JSON data
jsonData := `{
"proxy": "192.168.1.1:65000",
"resolver": "8.8.8.8:53",
"proto": "tcp",
"prefix": "HTTP1/1",
"time": "2021-01-01T00:00:00Z",
"durationMs": 100,
"error": {
"operation": "read",
"posixError": "ETIMEDOUT",
"msg": "i/o timeout"
}
}`
var testRecord Record
err := json.Unmarshal([]byte(jsonData), &testRecord.record)
if err != nil {
fmt.Println(err)
t.Errorf("Expected no error, but got: %v", err)
}
testRecord.collectorURL = "https://example.com"
testRecord.success = true
testRecord.successSampleRate = 1.0
testRecord.failureSampleRate = 0.0

err = Report(testRecord)

if err != nil {
t.Errorf("Expected no error, but got: %v", err)
}
}