Skip to content

Commit

Permalink
Use JSONL format for aggregated scans (#233)
Browse files Browse the repository at this point in the history
  • Loading branch information
vbrown608 authored and sydneyli committed May 10, 2019
1 parent 10c9944 commit da4a653
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 18 deletions.
38 changes: 22 additions & 16 deletions stats/stats.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package stats

import (
"bufio"
"encoding/json"
"log"
"net/http"
"os"
"time"
Expand All @@ -21,38 +23,42 @@ type Store interface {
// of the web's top domains
const topDomainsSource = "TOP_DOMAINS"

// Import imports JSON list of aggregated scans from a remote server to the
// datastore.
func Import(store Store) {
// Import imports aggregated scans from a remote server to the datastore.
// Expected format is JSONL (newline-separated JSON objects).
func Import(store Store) error {
statsURL := os.Getenv("REMOTE_STATS_URL")
resp, err := http.Get(statsURL)
if err != nil {
raven.CaptureError(err, nil)
return
return err
}
defer resp.Body.Close()

var agScans []checker.AggregatedScan
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&agScans)
if err != nil {
raven.CaptureError(err, nil)
return
}
for _, a := range agScans {
s := bufio.NewScanner(resp.Body)
for s.Scan() {
var a checker.AggregatedScan
err := json.Unmarshal(s.Bytes(), &a)
if err != nil {
return err
}
a.Source = topDomainsSource
err := store.PutAggregatedScan(a)
err = store.PutAggregatedScan(a)
if err != nil {
raven.CaptureError(err, nil)
return err
}
}
if err := s.Err(); err != nil {
return err
}
return nil
}

// ImportRegularly runs Import to import aggregated stats from a remote server at regular intervals.
func ImportRegularly(store Store, interval time.Duration) {
for {
<-time.After(interval)
Import(store)
err := Import(store)
log.Println(err)
raven.CaptureError(err, nil)
}
}

Expand Down
9 changes: 7 additions & 2 deletions stats/stats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,17 @@ func TestImport(t *testing.T) {
}
ts := httptest.NewServer(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(agScans)
enc := json.NewEncoder(w)
enc.Encode(agScans[0])
enc.Encode(agScans[1])
}),
)
os.Setenv("REMOTE_STATS_URL", ts.URL)
store := mockAgScanStore{}
Import(&store)
err := Import(&store)
if err != nil {
t.Fatal(err)
}
for i, want := range agScans {
got := store[i]
// Times must be compared with Time.Equal, so we can't reflect.DeepEqual.
Expand Down

0 comments on commit da4a653

Please sign in to comment.