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

initialize the store lazily #25

Merged
merged 1 commit into from
Feb 24, 2023
Merged
Changes from all 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
40 changes: 19 additions & 21 deletions asn.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import (
"errors"
"fmt"
"net"
"sync"

"github.com/libp2p/go-cidranger"
)

var Store *indirectAsnStore
var Store *lazyAsnStore

func init() {
Store = newIndirectAsnStore()
Store = &lazyAsnStore{}
}

type networkWithAsn struct {
Expand Down Expand Up @@ -66,32 +67,29 @@ func newAsnStore() (*asnStore, error) {
return &asnStore{cr}, nil
}

type indirectAsnStore struct {
store *asnStore
doneLoading chan struct{}
// lazyAsnStore builds the underlying trie on first call to AsnForIPv6.
// Alternatively, Init can be called to manually trigger initialization.
type lazyAsnStore struct {
store *asnStore
once sync.Once
}

// AsnForIPv6 returns the AS number for the given IPv6 address.
// If no mapping exists for the given IP, this function will
// return an empty ASN and a nil error.
func (a *indirectAsnStore) AsnForIPv6(ip net.IP) (string, error) {
<-a.doneLoading
func (a *lazyAsnStore) AsnForIPv6(ip net.IP) (string, error) {
a.once.Do(a.init)
return a.store.AsnForIPv6(ip)
}

func newIndirectAsnStore() *indirectAsnStore {
a := &indirectAsnStore{
doneLoading: make(chan struct{}),
}

go func() {
defer close(a.doneLoading)
store, err := newAsnStore()
if err != nil {
panic(err)
}
a.store = store
}()
func (a *lazyAsnStore) Init() {
a.once.Do(a.init)
}

return a
func (a *lazyAsnStore) init() {
store, err := newAsnStore()
if err != nil {
panic(err)
}
a.store = store
}