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 3 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
94 changes: 94 additions & 0 deletions x/reporter/reporter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// 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{}


func sendReport(record map[string]interface{}, collectorURL string) error {
amircybersec marked this conversation as resolved.
Show resolved Hide resolved
amircybersec marked this conversation as resolved.
Show resolved Hide resolved
jsonData, err := json.Marshal(record)
if err != nil {
log.Printf("Error encoding JSON: %s\n", err)
return err
}

Copy link
Contributor

Choose a reason for hiding this comment

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

TODO: WriteCollector that takes a io.Writer

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)
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
}

func sendReportRandomly(record map[string]interface{}, collectorURL string, success bool, successSampleRate float64, failureSampleRate float64) error {

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

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

var samplingRate float64
if success {
samplingRate = successSampleRate
} else {
samplingRate = failureSampleRate
}
// Generate a random number between 0 and 1
random := rand.Float64()
if random < samplingRate {
// Run your function here
err := sendReport(record, 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
}
}
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 record map[string]interface{}
err := json.Unmarshal([]byte(jsonData), &record)
if err != nil {
fmt.Println(err)
t.Errorf("Expected no error, but got: %v", err)
}
collectorURL := "example.com"
success := true
successSampleRate := 1.0
failureSampleRate := 0.0

err = sendReportRandomly(record, collectorURL, success, successSampleRate, failureSampleRate)

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