<commit_before>package tunnel

import (
	"os"
	"sync"
	"time"

	"github.com/micro/cli"
	"github.com/micro/go-micro"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/config/options"
	"github.com/micro/go-micro/proxy/mucp"
	"github.com/micro/go-micro/registry/memory"
	"github.com/micro/go-micro/router"
	"github.com/micro/go-micro/server"
	tun "github.com/micro/go-micro/tunnel"
	"github.com/micro/go-micro/tunnel/transport"
	"github.com/micro/go-micro/util/log"
)

var (
	// Name of the router microservice
	Name = "go.micro.tunnel"
	// Address is the tunnel microservice bind address
	Address = ":8084"
	// Tunnel is the tunnel bind address
	Tunnel = ":9096"
	// Channel is the name of the tunnel session
	Channel = "tunnel"
	// Router is the router gossip bind address
	Router = ":9093"
	// Network is the network id
	Network = "local"
)

// run runs the micro server
func run(ctx *cli.Context, srvOpts ...micro.Option) {
	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	if len(ctx.GlobalString("server_name")) > 0 {
		Name = ctx.GlobalString("server_name")
	}
	if len(ctx.String("address")) > 0 {
		Address = ctx.String("address")
	}
	if len(ctx.String("network_address")) > 0 {
		Network = ctx.String("network")
	}
	if len(ctx.String("tunnel_address")) > 0 {
		Tunnel = ctx.String("tunnel")
	}
	// default gateway address
	var gateway string
	if len(ctx.String("gateway_address")) > 0 {
		gateway = ctx.String("gateway")
	}

	// create a tunnel
	t := tun.NewTunnel(
		tun.Address(Tunnel),
	)

	// connect the tunnel
	if err := t.Connect(); err != nil {
		log.Logf("[tunnel] failed to connect: %s", err)
		os.Exit(1)
	}

	// Initialise service
	service := micro.NewService(
		micro.Name(Name),
		micro.Address(Address),
		micro.RegisterTTL(time.Duration(ctx.GlobalInt("register_ttl"))*time.Second),
		micro.RegisterInterval(time.Duration(ctx.GlobalInt("register_interval"))*time.Second),
	)

	// local tunnel router
	r := router.NewRouter(
		router.Id(service.Server().Options().Id),
		router.Registry(service.Client().Options().Registry),
		router.Address(Router),
		router.Network(Network),
		router.Gateway(gateway),
	)

	// create tunnel client with tunnel transport
	tunTransport := transport.NewTransport(
		transport.WithTunnel(t),
	)

	// local server client talks to tunnel
	localSrvClient := client.NewClient(
		client.Transport(tunTransport),
	)

	// local proxy
	localProxy := mucp.NewProxy(
		options.WithValue("proxy.router", r),
		options.WithValue("proxy.client", localSrvClient),
	)

	// init server
	service.Server().Init(
		server.WithRouter(localProxy),
	)

	// local transport client
	tunSrvClient := client.NewClient(
		client.Transport(service.Options().Transport),
	)

	// local proxy
	tunProxy := mucp.NewProxy(
		options.WithValue("proxy.client", tunSrvClient),
	)

	// create memory registry
	memRegistry := memory.NewRegistry()

	// local server
	tunSrv := server.NewServer(
		server.Transport(tunTransport),
		server.WithRouter(tunProxy),
		server.Registry(memRegistry),
	)

	var wg sync.WaitGroup

	// error channel to collect errors and bail
	errChan := make(chan error, 2)

	wg.Add(1)
	go func() {
		defer wg.Done()
		errChan <- service.Run()
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		errChan <- tunSrv.Start()
	}()

	// we block here until either service or server fails
	if err := <-errChan; err != nil {
		log.Logf("[tunnel] error running the tunnel: %v", err)
	}

	log.Log("[tunnel] attempting to stop the tunnel")

	// stop the router
	if err := r.Stop(); err != nil {
		log.Logf("[tunnel] error stopping tunnel router:%v", err)
	}

	wg.Wait()

	log.Logf("[tunnel] successfully stopped")
}

func Commands(options ...micro.Option) []cli.Command {
	command := cli.Command{
		Name:  "tunnel",
		Usage: "Run the micro network tunnel",
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:   "tunnel_address",
				Usage:  "Set the micro tunnel address :9096",
				EnvVar: "MICRO_TUNNEL_ADDRESS",
			},
			cli.StringFlag{
				Name:   "network_address",
				Usage:  "Set the micro network address: local",
				EnvVar: "MICRO_NETWORK_ADDRESS",
			},
			cli.StringFlag{
				Name:   "gateway_address",
				Usage:  "Set the micro default gateway address :9094",
				EnvVar: "MICRO_GATEWAY_ADDRESS",
			},
		},
		Action: func(ctx *cli.Context) {
			run(ctx, options...)
		},
	}

	for _, p := range Plugins() {
		if cmds := p.Commands(); len(cmds) > 0 {
			command.Subcommands = append(command.Subcommands, cmds...)
		}

		if flags := p.Flags(); len(flags) > 0 {
			command.Flags = append(command.Flags, flags...)
		}
	}

	return []cli.Command{command}
}
<commit_msg>No need to run service in a separate goroutine<commit_after>package tunnel

import (
	"os"
	"time"

	"github.com/micro/cli"
	"github.com/micro/go-micro"
	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/config/options"
	"github.com/micro/go-micro/proxy/mucp"
	"github.com/micro/go-micro/registry/memory"
	"github.com/micro/go-micro/router"
	"github.com/micro/go-micro/server"
	tun "github.com/micro/go-micro/tunnel"
	"github.com/micro/go-micro/tunnel/transport"
	"github.com/micro/go-micro/util/log"
)

var (
	// Name of the router microservice
	Name = "go.micro.tunnel"
	// Address is the tunnel microservice bind address
	Address = ":8084"
	// Tunnel is the tunnel bind address
	Tunnel = ":9096"
	// Channel is the name of the tunnel session
	Channel = "tunnel"
	// Router is the router gossip bind address
	Router = ":9093"
	// Network is the network id
	Network = "local"
)

// run runs the micro server
func run(ctx *cli.Context, srvOpts ...micro.Option) {
	// Init plugins
	for _, p := range Plugins() {
		p.Init(ctx)
	}

	if len(ctx.GlobalString("server_name")) > 0 {
		Name = ctx.GlobalString("server_name")
	}
	if len(ctx.String("address")) > 0 {
		Address = ctx.String("address")
	}
	if len(ctx.String("network_address")) > 0 {
		Network = ctx.String("network")
	}
	if len(ctx.String("tunnel_address")) > 0 {
		Tunnel = ctx.String("tunnel")
	}
	// default gateway address
	var gateway string
	if len(ctx.String("gateway_address")) > 0 {
		gateway = ctx.String("gateway")
	}

	// create a tunnel
	t := tun.NewTunnel(
		tun.Address(Tunnel),
	)

	// connect the tunnel
	if err := t.Connect(); err != nil {
		log.Logf("[tunnel] failed to connect: %s", err)
		os.Exit(1)
	}

	// Initialise service
	service := micro.NewService(
		micro.Name(Name),
		micro.Address(Address),
		micro.RegisterTTL(time.Duration(ctx.GlobalInt("register_ttl"))*time.Second),
		micro.RegisterInterval(time.Duration(ctx.GlobalInt("register_interval"))*time.Second),
	)

	// local tunnel router
	r := router.NewRouter(
		router.Id(service.Server().Options().Id),
		router.Registry(service.Client().Options().Registry),
		router.Address(Router),
		router.Network(Network),
		router.Gateway(gateway),
	)

	// create tunnel client with tunnel transport
	tunTransport := transport.NewTransport(
		transport.WithTunnel(t),
	)

	// local server client talks to tunnel
	localSrvClient := client.NewClient(
		client.Transport(tunTransport),
	)

	// local proxy
	localProxy := mucp.NewProxy(
		options.WithValue("proxy.router", r),
		options.WithValue("proxy.client", localSrvClient),
	)

	// init server
	service.Server().Init(
		server.WithRouter(localProxy),
	)

	// local transport client
	tunSrvClient := client.NewClient(
		client.Transport(service.Options().Transport),
	)

	// local proxy
	tunProxy := mucp.NewProxy(
		options.WithValue("proxy.client", tunSrvClient),
	)

	// create memory registry
	memRegistry := memory.NewRegistry()

	// local server
	tunSrv := server.NewServer(
		server.Transport(tunTransport),
		server.WithRouter(tunProxy),
		server.Registry(memRegistry),
	)

	if err := tunSrv.Start(); err != nil {
		log.Logf("[tunnel] error starting tunnel server: %v", err)
		os.Exit(1)
	}

	if err := service.Run(); err != nil {
		log.Log("[tunnel] %s failed: %v", Name, err)
	}

	// stop the router
	if err := r.Stop(); err != nil {
		log.Logf("[tunnel] error stopping tunnel router: %v", err)
	}

	// stop the server
	if err := tunSrv.Stop(); err != nil {
		log.Logf("[tunnel] error stopping tunnel server: %v", err)
	}

	if err := t.Connect(); err != nil {
		log.Logf("[tunnel] error stopping tunnel: %v", err)
	}

	log.Logf("[tunnel] stopped")
}

func Commands(options ...micro.Option) []cli.Command {
	command := cli.Command{
		Name:  "tunnel",
		Usage: "Run the micro network tunnel",
		Flags: []cli.Flag{
			cli.StringFlag{
				Name:   "tunnel_address",
				Usage:  "Set the micro tunnel address :9096",
				EnvVar: "MICRO_TUNNEL_ADDRESS",
			},
			cli.StringFlag{
				Name:   "network_address",
				Usage:  "Set the micro network address: local",
				EnvVar: "MICRO_NETWORK_ADDRESS",
			},
			cli.StringFlag{
				Name:   "gateway_address",
				Usage:  "Set the micro default gateway address :9094",
				EnvVar: "MICRO_GATEWAY_ADDRESS",
			},
		},
		Action: func(ctx *cli.Context) {
			run(ctx, options...)
		},
	}

	for _, p := range Plugins() {
		if cmds := p.Commands(); len(cmds) > 0 {
			command.Subcommands = append(command.Subcommands, cmds...)
		}

		if flags := p.Flags(); len(flags) > 0 {
			command.Flags = append(command.Flags, flags...)
		}
	}

	return []cli.Command{command}
}
<|endoftext|>


<commit_before>package downloader

import (
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
)

const (
	maxBlockFetch    = 128              // Amount of max blocks to be fetched per chunk
	peerCountTimeout = 12 * time.Second // Amount of time it takes for the peer handler to ignore minDesiredPeerCount
	hashTtl          = 20 * time.Second // The amount of time it takes for a hash request to time out
)

var (
	minDesiredPeerCount = 5                // Amount of peers desired to start syncing
	blockTtl            = 20 * time.Second // The amount of time it takes for a block request to time out

	errLowTd               = errors.New("peer's TD is too low")
	ErrBusy                = errors.New("busy")
	errUnknownPeer         = errors.New("peer's unknown or unhealthy")
	errBadPeer             = errors.New("action from bad peer ignored")
	errNoPeers             = errors.New("no peers to keep download active")
	errPendingQueue        = errors.New("pending items in queue")
	ErrTimeout             = errors.New("timeout")
	errEmptyHashSet        = errors.New("empty hash set by peer")
	errPeersUnavailable    = errors.New("no peers available or all peers tried for block download process")
	errAlreadyInPool       = errors.New("hash already in pool")
	errBlockNumberOverflow = errors.New("received block which overflows")
)

type hashCheckFn func(common.Hash) bool
type getBlockFn func(common.Hash) *types.Block
type chainInsertFn func(types.Blocks) (int, error)
type hashIterFn func() (common.Hash, error)

type blockPack struct {
	peerId string
	blocks []*types.Block
}

type syncPack struct {
	peer          *peer
	hash          common.Hash
	ignoreInitial bool
}

type hashPack struct {
	peerId string
	hashes []common.Hash
}

type Downloader struct {
	mu         sync.RWMutex
	queue      *queue
	peers      peers
	activePeer string

	// Callbacks
	hasBlock hashCheckFn
	getBlock getBlockFn

	// Status
	synchronising int32

	// Channels
	newPeerCh chan *peer
	hashCh    chan hashPack
	blockCh   chan blockPack
}

func New(hasBlock hashCheckFn, getBlock getBlockFn) *Downloader {
	downloader := &Downloader{
		queue:     newQueue(),
		peers:     make(peers),
		hasBlock:  hasBlock,
		getBlock:  getBlock,
		newPeerCh: make(chan *peer, 1),
		hashCh:    make(chan hashPack, 1),
		blockCh:   make(chan blockPack, 1),
	}

	return downloader
}

func (d *Downloader) Stats() (current int, max int) {
	return d.queue.Size()
}

func (d *Downloader) RegisterPeer(id string, hash common.Hash, getHashes hashFetcherFn, getBlocks blockFetcherFn) error {
	d.mu.Lock()
	defer d.mu.Unlock()

	glog.V(logger.Detail).Infoln("Register peer", id)

	// Create a new peer and add it to the list of known peers
	peer := newPeer(id, hash, getHashes, getBlocks)
	// add peer to our peer set
	d.peers[id] = peer
	// broadcast new peer

	return nil
}

// UnregisterPeer unregisters a peer. This will prevent any action from the specified peer.
func (d *Downloader) UnregisterPeer(id string) {
	d.mu.Lock()
	defer d.mu.Unlock()

	glog.V(logger.Detail).Infoln("Unregister peer", id)

	delete(d.peers, id)
}

// Synchronise will select the peer and use it for synchronising. If an empty string is given
// it will use the best peer possible and synchronize if it's TD is higher than our own. If any of the
// checks fail an error will be returned. This method is synchronous
func (d *Downloader) Synchronise(id string, hash common.Hash) error {
	// Make sure only one goroutine is ever allowed past this point at once
	if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
		return ErrBusy
	}
	defer atomic.StoreInt32(&d.synchronising, 0)

	// Abort if the queue still contains some leftover data
	if _, cached := d.queue.Size(); cached > 0 {
		return errPendingQueue
	}
	// Retrieve the origin peer and initiate the downloading process
	p := d.peers[id]
	if p == nil {
		return errUnknownPeer
	}
	return d.getFromPeer(p, hash, false)
}

// TakeBlocks takes blocks from the queue and yields them to the blockTaker handler
// it's possible it yields no blocks
func (d *Downloader) TakeBlocks() types.Blocks {
	// Check that there are blocks available and its parents are known
	head := d.queue.GetHeadBlock()
	if head == nil || !d.hasBlock(head.ParentHash()) {
		return nil
	}
	// Retrieve a full batch of blocks
	return d.queue.TakeBlocks(head)
}

func (d *Downloader) Has(hash common.Hash) bool {
	return d.queue.Has(hash)
}

func (d *Downloader) getFromPeer(p *peer, hash common.Hash, ignoreInitial bool) (err error) {

	d.activePeer = p.id
	defer func() {
		// reset on error
		if err != nil {
			d.queue.Reset()
		}
	}()

	glog.V(logger.Debug).Infoln("Synchronizing with the network using:", p.id)
	// Start the fetcher. This will block the update entirely
	// interupts need to be send to the appropriate channels
	// respectively.
	if err = d.startFetchingHashes(p, hash, ignoreInitial); err != nil {
		return err
	}

	// Start fetching blocks in paralel. The strategy is simple
	// take any available peers, seserve a chunk for each peer available,
	// let the peer deliver the chunkn and periodically check if a peer
	// has timedout.
	if err = d.startFetchingBlocks(p); err != nil {
		return err
	}

	glog.V(logger.Debug).Infoln("Synchronization completed")

	return nil
}

// XXX Make synchronous
func (d *Downloader) startFetchingHashes(p *peer, h common.Hash, ignoreInitial bool) error {
	glog.V(logger.Debug).Infof("Downloading hashes (%x) from %s", h[:4], p.id)

	start := time.Now()

	// We ignore the initial hash in some cases (e.g. we received a block without it's parent)
	// In such circumstances we don't need to download the block so don't add it to the queue.
	if !ignoreInitial {
		// Add the hash to the queue first
		d.queue.Insert([]common.Hash{h})
	}
	// Get the first batch of hashes
	p.getHashes(h)

	var (
		failureResponseTimer = time.NewTimer(hashTtl)
		attemptedPeers       = make(map[string]bool) // attempted peers will help with retries
		activePeer           = p                     // active peer will help determine the current active peer
		hash                 common.Hash             // common and last hash
	)
	attemptedPeers[p.id] = true

out:
	for {
		select {
		case hashPack := <-d.hashCh:
			// Make sure the active peer is giving us the hashes
			if hashPack.peerId != activePeer.id {
				glog.V(logger.Debug).Infof("Received hashes from incorrect peer(%s)\n", hashPack.peerId)
				break
			}

			failureResponseTimer.Reset(hashTtl)

			// Make sure the peer actually gave something valid
			if len(hashPack.hashes) == 0 {
				glog.V(logger.Debug).Infof("Peer (%s) responded with empty hash set\n", activePeer.id)
				d.queue.Reset()

				return errEmptyHashSet
			}
			// Determine if we're done fetching hashes (queue up all pending), and continue if not done
			done, index := false, 0
			for index, hash = range hashPack.hashes {
				if d.hasBlock(hash) || d.queue.GetBlock(hash) != nil {
					glog.V(logger.Debug).Infof("Found common hash %x\n", hash[:4])
					hashPack.hashes = hashPack.hashes[:index]
					done = true
					break
				}
			}
			d.queue.Insert(hashPack.hashes)

			if !done {
				activePeer.getHashes(hash)
				continue
			}
			// We're done, allocate the download cache and proceed pulling the blocks
			offset := 0
			if block := d.getBlock(hash); block != nil {
				offset = int(block.NumberU64() + 1)
			}
			d.queue.Alloc(offset)
			break out

		case <-failureResponseTimer.C:
			glog.V(logger.Debug).Infof("Peer (%s) didn't respond in time for hash request\n", p.id)

			var p *peer // p will be set if a peer can be found
			// Attempt to find a new peer by checking inclusion of peers best hash in our
			// already fetched hash list. This can't guarantee 100% correctness but does
			// a fair job. This is always either correct or false incorrect.
			for id, peer := range d.peers {
				if d.queue.Has(peer.recentHash) && !attemptedPeers[id] {
					p = peer
					break
				}
			}

			// if all peers have been tried, abort the process entirely or if the hash is
			// the zero hash.
			if p == nil || (hash == common.Hash{}) {
				d.queue.Reset()
				return ErrTimeout
			}

			// set p to the active peer. this will invalidate any hashes that may be returned
			// by our previous (delayed) peer.
			activePeer = p
			p.getHashes(hash)
			glog.V(logger.Debug).Infof("Hash fetching switched to new peer(%s)\n", p.id)
		}
	}
	glog.V(logger.Debug).Infof("Downloaded hashes (%d) in %v\n", d.queue.Pending(), time.Since(start))

	return nil
}

func (d *Downloader) startFetchingBlocks(p *peer) error {
	glog.V(logger.Debug).Infoln("Downloading", d.queue.Pending(), "block(s)")

	// Defer the peer reset. This will empty the peer requested set
	// and makes sure there are no lingering peers with an incorrect
	// state
	defer d.peers.reset()

	start := time.Now()

	// default ticker for re-fetching blocks every now and then
	ticker := time.NewTicker(20 * time.Millisecond)
out:
	for {
		select {
		case blockPack := <-d.blockCh:
			// If the peer was previously banned and failed to deliver it's pack
			// in a reasonable time frame, ignore it's message.
			if d.peers[blockPack.peerId] != nil {
				err := d.queue.Deliver(blockPack.peerId, blockPack.blocks)
				if err != nil {
					glog.V(logger.Debug).Infof("deliver failed for peer %s: %v\n", blockPack.peerId, err)
					// FIXME d.UnregisterPeer(blockPack.peerId)
					break
				}

				if glog.V(logger.Debug) {
					glog.Infof("adding %d blocks from: %s\n", len(blockPack.blocks), blockPack.peerId)
				}
				d.peers[blockPack.peerId].promote()
				d.peers.setState(blockPack.peerId, idleState)
			}
		case <-ticker.C:
			// Check for bad peers. Bad peers may indicate a peer not responding
			// to a `getBlocks` message. A timeout of 5 seconds is set. Peers
			// that badly or poorly behave are removed from the peer set (not banned).
			// Bad peers are excluded from the available peer set and therefor won't be
			// reused. XXX We could re-introduce peers after X time.
			badPeers := d.queue.Expire(blockTtl)
			for _, pid := range badPeers {
				// XXX We could make use of a reputation system here ranking peers
				// in their performance
				// 1) Time for them to respond;
				// 2) Measure their speed;
				// 3) Amount and availability.
				if peer := d.peers[pid]; peer != nil {
					peer.demote()
					peer.reset()
				}
			}
			// After removing bad peers make sure we actually have sufficient peer left to keep downloading
			if len(d.peers) == 0 {
				d.queue.Reset()
				return errNoPeers
			}
			// If there are unrequested hashes left start fetching
			// from the available peers.
			if d.queue.Pending() > 0 {
				// Throttle the download if block cache is full and waiting processing
				if d.queue.Throttle() {
					continue
				}

				availablePeers := d.peers.get(idleState)
				for _, peer := range availablePeers {
					// Get a possible chunk. If nil is returned no chunk
					// could be returned due to no hashes available.
					request := d.queue.Reserve(peer, maxBlockFetch)
					if request == nil {
						continue
					}
					// XXX make fetch blocking.
					// Fetch the chunk and check for error. If the peer was somehow
					// already fetching a chunk due to a bug, it will be returned to
					// the queue
					if err := peer.fetch(request); err != nil {
						// log for tracing
						glog.V(logger.Debug).Infof("peer %s received double work (state = %v)\n", peer.id, peer.state)
						d.queue.Cancel(request)
					}
				}
				// make sure that we have peers available for fetching. If all peers have been tried
				// and all failed throw an error
				if d.queue.InFlight() == 0 {
					d.queue.Reset()

					return fmt.Errorf("%v peers avaialable = %d. total peers = %d. hashes needed = %d", errPeersUnavailable, len(availablePeers), len(d.peers), d.queue.Pending())
				}

			} else if d.queue.InFlight() == 0 {
				// When there are no more queue and no more in flight, We can
				// safely assume we're done. Another part of the process will  check
				// for parent errors and will re-request anything that's missing
				break out
			}
		}
	}
	glog.V(logger.Detail).Infoln("Downloaded block(s) in", time.Since(start))

	return nil
}

// Deliver a chunk to the downloader. This is usually done through the BlocksMsg by
// the protocol handler.
func (d *Downloader) DeliverChunk(id string, blocks []*types.Block) {
	d.blockCh <- blockPack{id, blocks}
}

func (d *Downloader) AddHashes(id string, hashes []common.Hash) error {
	// make sure that the hashes that are being added are actually from the peer
	// that's the current active peer. hashes that have been received from other
	// peers are dropped and ignored.
	if d.activePeer != id {
		return fmt.Errorf("received hashes from %s while active peer is %s", id, d.activePeer)
	}

	if glog.V(logger.Debug) && len(hashes) != 0 {
		from, to := hashes[0], hashes[len(hashes)-1]
		glog.V(logger.Debug).Infof("adding %d (T=%d) hashes [ %x / %x ] from: %s\n", len(hashes), d.queue.Pending(), from[:4], to[:4], id)
	}
	d.hashCh <- hashPack{id, hashes}

	return nil
}
<commit_msg>eth/downloader: fix leftover state between syncs<commit_after>package downloader

import (
	"errors"
	"fmt"
	"sync"
	"sync/atomic"
	"time"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/logger/glog"
)

const (
	maxBlockFetch    = 128              // Amount of max blocks to be fetched per chunk
	peerCountTimeout = 12 * time.Second // Amount of time it takes for the peer handler to ignore minDesiredPeerCount
	hashTtl          = 20 * time.Second // The amount of time it takes for a hash request to time out
)

var (
	minDesiredPeerCount = 5                // Amount of peers desired to start syncing
	blockTtl            = 20 * time.Second // The amount of time it takes for a block request to time out

	errLowTd               = errors.New("peer's TD is too low")
	ErrBusy                = errors.New("busy")
	errUnknownPeer         = errors.New("peer's unknown or unhealthy")
	errBadPeer             = errors.New("action from bad peer ignored")
	errNoPeers             = errors.New("no peers to keep download active")
	errPendingQueue        = errors.New("pending items in queue")
	ErrTimeout             = errors.New("timeout")
	errEmptyHashSet        = errors.New("empty hash set by peer")
	errPeersUnavailable    = errors.New("no peers available or all peers tried for block download process")
	errAlreadyInPool       = errors.New("hash already in pool")
	errBlockNumberOverflow = errors.New("received block which overflows")
)

type hashCheckFn func(common.Hash) bool
type getBlockFn func(common.Hash) *types.Block
type chainInsertFn func(types.Blocks) (int, error)
type hashIterFn func() (common.Hash, error)

type blockPack struct {
	peerId string
	blocks []*types.Block
}

type syncPack struct {
	peer          *peer
	hash          common.Hash
	ignoreInitial bool
}

type hashPack struct {
	peerId string
	hashes []common.Hash
}

type Downloader struct {
	mu         sync.RWMutex
	queue      *queue
	peers      peers
	activePeer string

	// Callbacks
	hasBlock hashCheckFn
	getBlock getBlockFn

	// Status
	synchronising int32

	// Channels
	newPeerCh chan *peer
	hashCh    chan hashPack
	blockCh   chan blockPack
}

func New(hasBlock hashCheckFn, getBlock getBlockFn) *Downloader {
	downloader := &Downloader{
		queue:     newQueue(),
		peers:     make(peers),
		hasBlock:  hasBlock,
		getBlock:  getBlock,
		newPeerCh: make(chan *peer, 1),
		hashCh:    make(chan hashPack, 1),
		blockCh:   make(chan blockPack, 1),
	}

	return downloader
}

func (d *Downloader) Stats() (current int, max int) {
	return d.queue.Size()
}

func (d *Downloader) RegisterPeer(id string, hash common.Hash, getHashes hashFetcherFn, getBlocks blockFetcherFn) error {
	d.mu.Lock()
	defer d.mu.Unlock()

	glog.V(logger.Detail).Infoln("Register peer", id)

	// Create a new peer and add it to the list of known peers
	peer := newPeer(id, hash, getHashes, getBlocks)
	// add peer to our peer set
	d.peers[id] = peer
	// broadcast new peer

	return nil
}

// UnregisterPeer unregisters a peer. This will prevent any action from the specified peer.
func (d *Downloader) UnregisterPeer(id string) {
	d.mu.Lock()
	defer d.mu.Unlock()

	glog.V(logger.Detail).Infoln("Unregister peer", id)

	delete(d.peers, id)
}

// Synchronise will select the peer and use it for synchronising. If an empty string is given
// it will use the best peer possible and synchronize if it's TD is higher than our own. If any of the
// checks fail an error will be returned. This method is synchronous
func (d *Downloader) Synchronise(id string, hash common.Hash) error {
	// Make sure only one goroutine is ever allowed past this point at once
	if !atomic.CompareAndSwapInt32(&d.synchronising, 0, 1) {
		return ErrBusy
	}
	defer atomic.StoreInt32(&d.synchronising, 0)

	// Abort if the queue still contains some leftover data
	if _, cached := d.queue.Size(); cached > 0 && d.queue.GetHeadBlock() != nil {
		return errPendingQueue
	}
	// Reset the queue to clean any internal leftover state
	d.queue.Reset()

	// Retrieve the origin peer and initiate the downloading process
	p := d.peers[id]
	if p == nil {
		return errUnknownPeer
	}
	return d.getFromPeer(p, hash, false)
}

// TakeBlocks takes blocks from the queue and yields them to the blockTaker handler
// it's possible it yields no blocks
func (d *Downloader) TakeBlocks() types.Blocks {
	// Check that there are blocks available and its parents are known
	head := d.queue.GetHeadBlock()
	if head == nil || !d.hasBlock(head.ParentHash()) {
		return nil
	}
	// Retrieve a full batch of blocks
	return d.queue.TakeBlocks(head)
}

func (d *Downloader) Has(hash common.Hash) bool {
	return d.queue.Has(hash)
}

func (d *Downloader) getFromPeer(p *peer, hash common.Hash, ignoreInitial bool) (err error) {

	d.activePeer = p.id
	defer func() {
		// reset on error
		if err != nil {
			d.queue.Reset()
		}
	}()

	glog.V(logger.Debug).Infoln("Synchronizing with the network using:", p.id)
	// Start the fetcher. This will block the update entirely
	// interupts need to be send to the appropriate channels
	// respectively.
	if err = d.startFetchingHashes(p, hash, ignoreInitial); err != nil {
		return err
	}

	// Start fetching blocks in paralel. The strategy is simple
	// take any available peers, seserve a chunk for each peer available,
	// let the peer deliver the chunkn and periodically check if a peer
	// has timedout.
	if err = d.startFetchingBlocks(p); err != nil {
		return err
	}

	glog.V(logger.Debug).Infoln("Synchronization completed")

	return nil
}

// XXX Make synchronous
func (d *Downloader) startFetchingHashes(p *peer, h common.Hash, ignoreInitial bool) error {
	glog.V(logger.Debug).Infof("Downloading hashes (%x) from %s", h[:4], p.id)

	start := time.Now()

	// We ignore the initial hash in some cases (e.g. we received a block without it's parent)
	// In such circumstances we don't need to download the block so don't add it to the queue.
	if !ignoreInitial {
		// Add the hash to the queue first
		d.queue.Insert([]common.Hash{h})
	}
	// Get the first batch of hashes
	p.getHashes(h)

	var (
		failureResponseTimer = time.NewTimer(hashTtl)
		attemptedPeers       = make(map[string]bool) // attempted peers will help with retries
		activePeer           = p                     // active peer will help determine the current active peer
		hash                 common.Hash             // common and last hash
	)
	attemptedPeers[p.id] = true

out:
	for {
		select {
		case hashPack := <-d.hashCh:
			// Make sure the active peer is giving us the hashes
			if hashPack.peerId != activePeer.id {
				glog.V(logger.Debug).Infof("Received hashes from incorrect peer(%s)\n", hashPack.peerId)
				break
			}

			failureResponseTimer.Reset(hashTtl)

			// Make sure the peer actually gave something valid
			if len(hashPack.hashes) == 0 {
				glog.V(logger.Debug).Infof("Peer (%s) responded with empty hash set\n", activePeer.id)
				d.queue.Reset()

				return errEmptyHashSet
			}
			// Determine if we're done fetching hashes (queue up all pending), and continue if not done
			done, index := false, 0
			for index, hash = range hashPack.hashes {
				if d.hasBlock(hash) || d.queue.GetBlock(hash) != nil {
					glog.V(logger.Debug).Infof("Found common hash %x\n", hash[:4])
					hashPack.hashes = hashPack.hashes[:index]
					done = true
					break
				}
			}
			d.queue.Insert(hashPack.hashes)

			if !done {
				activePeer.getHashes(hash)
				continue
			}
			// We're done, allocate the download cache and proceed pulling the blocks
			offset := 0
			if block := d.getBlock(hash); block != nil {
				offset = int(block.NumberU64() + 1)
			}
			d.queue.Alloc(offset)
			break out

		case <-failureResponseTimer.C:
			glog.V(logger.Debug).Infof("Peer (%s) didn't respond in time for hash request\n", p.id)

			var p *peer // p will be set if a peer can be found
			// Attempt to find a new peer by checking inclusion of peers best hash in our
			// already fetched hash list. This can't guarantee 100% correctness but does
			// a fair job. This is always either correct or false incorrect.
			for id, peer := range d.peers {
				if d.queue.Has(peer.recentHash) && !attemptedPeers[id] {
					p = peer
					break
				}
			}

			// if all peers have been tried, abort the process entirely or if the hash is
			// the zero hash.
			if p == nil || (hash == common.Hash{}) {
				d.queue.Reset()
				return ErrTimeout
			}

			// set p to the active peer. this will invalidate any hashes that may be returned
			// by our previous (delayed) peer.
			activePeer = p
			p.getHashes(hash)
			glog.V(logger.Debug).Infof("Hash fetching switched to new peer(%s)\n", p.id)
		}
	}
	glog.V(logger.Debug).Infof("Downloaded hashes (%d) in %v\n", d.queue.Pending(), time.Since(start))

	return nil
}

func (d *Downloader) startFetchingBlocks(p *peer) error {
	glog.V(logger.Debug).Infoln("Downloading", d.queue.Pending(), "block(s)")

	// Defer the peer reset. This will empty the peer requested set
	// and makes sure there are no lingering peers with an incorrect
	// state
	defer d.peers.reset()

	start := time.Now()

	// default ticker for re-fetching blocks every now and then
	ticker := time.NewTicker(20 * time.Millisecond)
out:
	for {
		select {
		case blockPack := <-d.blockCh:
			// If the peer was previously banned and failed to deliver it's pack
			// in a reasonable time frame, ignore it's message.
			if d.peers[blockPack.peerId] != nil {
				err := d.queue.Deliver(blockPack.peerId, blockPack.blocks)
				if err != nil {
					glog.V(logger.Debug).Infof("deliver failed for peer %s: %v\n", blockPack.peerId, err)
					// FIXME d.UnregisterPeer(blockPack.peerId)
					break
				}

				if glog.V(logger.Debug) {
					glog.Infof("adding %d blocks from: %s\n", len(blockPack.blocks), blockPack.peerId)
				}
				d.peers[blockPack.peerId].promote()
				d.peers.setState(blockPack.peerId, idleState)
			}
		case <-ticker.C:
			// Check for bad peers. Bad peers may indicate a peer not responding
			// to a `getBlocks` message. A timeout of 5 seconds is set. Peers
			// that badly or poorly behave are removed from the peer set (not banned).
			// Bad peers are excluded from the available peer set and therefor won't be
			// reused. XXX We could re-introduce peers after X time.
			badPeers := d.queue.Expire(blockTtl)
			for _, pid := range badPeers {
				// XXX We could make use of a reputation system here ranking peers
				// in their performance
				// 1) Time for them to respond;
				// 2) Measure their speed;
				// 3) Amount and availability.
				if peer := d.peers[pid]; peer != nil {
					peer.demote()
					peer.reset()
				}
			}
			// After removing bad peers make sure we actually have sufficient peer left to keep downloading
			if len(d.peers) == 0 {
				d.queue.Reset()
				return errNoPeers
			}
			// If there are unrequested hashes left start fetching
			// from the available peers.
			if d.queue.Pending() > 0 {
				// Throttle the download if block cache is full and waiting processing
				if d.queue.Throttle() {
					continue
				}

				availablePeers := d.peers.get(idleState)
				for _, peer := range availablePeers {
					// Get a possible chunk. If nil is returned no chunk
					// could be returned due to no hashes available.
					request := d.queue.Reserve(peer, maxBlockFetch)
					if request == nil {
						continue
					}
					// XXX make fetch blocking.
					// Fetch the chunk and check for error. If the peer was somehow
					// already fetching a chunk due to a bug, it will be returned to
					// the queue
					if err := peer.fetch(request); err != nil {
						// log for tracing
						glog.V(logger.Debug).Infof("peer %s received double work (state = %v)\n", peer.id, peer.state)
						d.queue.Cancel(request)
					}
				}
				// make sure that we have peers available for fetching. If all peers have been tried
				// and all failed throw an error
				if d.queue.InFlight() == 0 {
					d.queue.Reset()

					return fmt.Errorf("%v peers avaialable = %d. total peers = %d. hashes needed = %d", errPeersUnavailable, len(availablePeers), len(d.peers), d.queue.Pending())
				}

			} else if d.queue.InFlight() == 0 {
				// When there are no more queue and no more in flight, We can
				// safely assume we're done. Another part of the process will  check
				// for parent errors and will re-request anything that's missing
				break out
			}
		}
	}
	glog.V(logger.Detail).Infoln("Downloaded block(s) in", time.Since(start))

	return nil
}

// Deliver a chunk to the downloader. This is usually done through the BlocksMsg by
// the protocol handler.
func (d *Downloader) DeliverChunk(id string, blocks []*types.Block) {
	d.blockCh <- blockPack{id, blocks}
}

func (d *Downloader) AddHashes(id string, hashes []common.Hash) error {
	// make sure that the hashes that are being added are actually from the peer
	// that's the current active peer. hashes that have been received from other
	// peers are dropped and ignored.
	if d.activePeer != id {
		return fmt.Errorf("received hashes from %s while active peer is %s", id, d.activePeer)
	}

	if glog.V(logger.Debug) && len(hashes) != 0 {
		from, to := hashes[0], hashes[len(hashes)-1]
		glog.V(logger.Debug).Infof("adding %d (T=%d) hashes [ %x / %x ] from: %s\n", len(hashes), d.queue.Pending(), from[:4], to[:4], id)
	}
	d.hashCh <- hashPack{id, hashes}

	return nil
}
<|endoftext|>


<commit_before>package dao

import "labix.org/v2/mgo/bson"

//------------------------------------------------------------
// DAO update array methods
//------------------------------------------------------------

// Adds pushObj element to array pushTo.
func (dao *DAO) Update_ArrayPush(id bson.ObjectId, pushTo string, pushObj interface{}) (err error) {

	q := M{
		"$push": M{pushTo: pushObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Adds pushObjs elements to array pushTo.
func (dao *DAO) Update_ArrayPushMany(id bson.ObjectId, pushTo string, pushObjs []interface{}) (err error) {

	q := M{
		"$pushAll": M{pushTo: pushObjs},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullObj element from pullFrom array.
// Adds pushObj element to pushTo array.
func (dao *DAO) Update_ArraysPullPush(id bson.ObjectId, pullFrom string, pullObj interface{}, pushTo string, pushObj interface{}) (err error) {

	q := M{
		"$pull": M{pullFrom: pullObj},
		"$push": M{pushTo: pushObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullObjs elements from pullFrom array.
// Adds pushObjs elements to pushTo array.
func (dao *DAO) Update_ArraysPullPushMany(id bson.ObjectId, pullFrom string, pullObjs []interface{}, pushTo string, pushObjs []interface{}) (err error) {

	q := M{
		"$pullAll": M{pullFrom: pullObjs},
		"$pushAll": M{pushTo: pushObjs},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullFrom array element that matches pullObj.
func (dao *DAO) Update_ArrayPull(id bson.ObjectId, pullFrom string, pullObj interface{}) (err error) {

	q := M{
		"$pull": M{pullFrom: pullObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullFrom array elements that matches pullObjs.
func (dao *DAO) Update_ArrayPullMany(id bson.ObjectId, pullFrom string, pullObjs []interface{}) (err error) {

	q := M{
		"$pullAll": M{pullFrom: pullObjs},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}
<commit_msg>$addToSet based arrays update methods<commit_after>package dao

import "labix.org/v2/mgo/bson"

//------------------------------------------------------------
// DAO update array methods
//------------------------------------------------------------

// Adds pushObj element to array pushTo.
func (dao *DAO) Update_ArrayPush(id bson.ObjectId, pushTo string, pushObj interface{}) (err error) {

	q := M{
		"$push": M{pushTo: pushObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Adds pushObjs elements to array pushTo.
func (dao *DAO) Update_ArrayPushMany(id bson.ObjectId, pushTo string, pushObjs []interface{}) (err error) {

	q := M{
		"$pushAll": M{pushTo: pushObjs},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Adds addObj element to array addTo only if it is not already there.
func (dao *DAO) Update_ArrayAdd(id bson.ObjectId, addTo string, addObj interface{}) (err error) {

	q := M{
		"$addToSet": M{addTo: addObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Adds addObjs elements to addTo array only if they are not already there.
func (dao *DAO) Update_ArrayAddMany(id bson.ObjectId, addTo string, addObjs []interface{}) (err error) {

	q := M{
		"$addToSet": M{addTo: M{"$each": addObjs}},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullObj element from pullFrom array.
// Adds pushObj element to pushTo array.
func (dao *DAO) Update_ArraysPullPush(id bson.ObjectId, pullFrom string, pullObj interface{}, pushTo string, pushObj interface{}) (err error) {

	q := M{
		"$pull": M{pullFrom: pullObj},
		"$push": M{pushTo: pushObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullObjs elements from pullFrom array.
// Adds pushObjs elements to pushTo array.
func (dao *DAO) Update_ArraysPullPushMany(id bson.ObjectId, pullFrom string, pullObjs []interface{}, pushTo string, pushObjs []interface{}) (err error) {

	q := M{
		"$pullAll": M{pullFrom: pullObjs},
		"$pushAll": M{pushTo: pushObjs},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullObjs elements from pullFrom array.
// Adds addObjs elements to addTo array only if they are not already there.
func (dao *DAO) Update_ArraysPullAddMany(id bson.ObjectId, pullFrom string, pullObjs []interface{}, addTo string, addObjs []interface{}) (err error) {

	q := M{
		"$pullAll": M{pullFrom: pullObjs},
		"$addToSet": M{addTo: M{"$each": addObjs}},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullFrom array element that matches pullObj.
func (dao *DAO) Update_ArrayPull(id bson.ObjectId, pullFrom string, pullObj interface{}) (err error) {

	q := M{
		"$pull": M{pullFrom: pullObj},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}

// Removes pullFrom array elements that matches pullObjs.
func (dao *DAO) Update_ArrayPullMany(id bson.ObjectId, pullFrom string, pullObjs []interface{}) (err error) {

	q := M{
		"$pullAll": M{pullFrom: pullObjs},
	}
	err = dao.Coll.UpdateId(id, q)
	return
}
<|endoftext|>


<commit_before>package typeinfer

import (
	"go/constant"
	"go/token"

	"golang.org/x/tools/go/ssa"
)

// setLoopIndex handles loop indices (initial value and increment)
func setLoopIndex(instr *ssa.Phi, infer *TypeInfer, f *Function, b *Block, l *Loop) {
	if i, ok := instr.Edges[0].(*ssa.Const); ok && !i.IsNil() && i.Value.Kind() == constant.Int {
		l.SetInit(instr, i.Int64())
		infer.Logger.Printf(f.Sprintf(LoopSymbol+"%s <= i", fmtLoopHL(l.Start)))
	}
	if bin, ok := instr.Edges[1].(*ssa.BinOp); ok {
		switch bin.Op {
		case token.ADD:
			if i, ok := bin.Y.(*ssa.Const); ok && i.Value.Kind() == constant.Int {
				l.SetStep(i.Int64())
			}
			infer.Logger.Printf(f.Sprintf(LoopSymbol+"i += %s", fmtLoopHL(l.Step)))
		case token.SUB:
			if i, ok := bin.Y.(*ssa.Const); ok && i.Value.Kind() == constant.Int {
				l.SetStep(-i.Int64())
			}
			infer.Logger.Printf(f.Sprintf(LoopSymbol+"i -= %s", fmtLoopHL(l.Step)))
		default:
			infer.Logger.Printf("loop index expression not supported %s", bin)
		}
	}
}

func phiDetectLoop(instr *ssa.Phi, infer *TypeInfer, f *Function, b *Block, l *Loop) {
	switch l.State {
	case Enter:
		switch l.Bound {
		case Unknown:
			phiSelectEdge(instr, infer, f, b, l)
			setLoopIndex(instr, infer, f, b, l)
		case Static:
			switch l.Bound {
			case Static:
				phiSelectEdge(instr, infer, f, b, l)
				if instr == l.IndexVar {
					l.Next()
					infer.Logger.Printf(f.Sprintf(LoopSymbol+"Increment %s by %s to %s", l.IndexVar.Name(), fmtLoopHL(l.Step), fmtLoopHL(l.Index)))
				}
			default:
				visitSkip(instr, infer, f, b, l)
			}
		case Dynamic:
			phiSelectEdge(instr, infer, f, b, l)
			infer.Logger.Printf(f.Sprintf(PhiSymbol+"(dynamic bound) %s", instr.String()))
		}
	default:
		phiSelectEdge(instr, infer, f, b, l)
	}
}

// phiSelectEdge selects edge based on predecessor block and returns the edge index.
func phiSelectEdge(instr *ssa.Phi, infer *TypeInfer, f *Function, b *Block, l *Loop) int {
	edge := 0
	for i, pred := range instr.Block().Preds {
		if pred.Index == b.Pred {
			e, ok := f.locals[instr.Edges[i]]
			if !ok {
				c, ok := instr.Edges[i].(*ssa.Const)
				if !ok {
					infer.Logger.Fatalf("phi: create instance Edge[%d]=%s: %s", i, instr.Edges[i].String()+instr.Edges[i].Name(), ErrUnknownValue)
				}
				f.locals[instr], edge = &ConstInstance{c}, pred.Index
				infer.Logger.Printf(f.Sprintf(PhiSymbol+"%s = %s, selected const from block %d", f.locals[instr], instr.String(), edge))
				return edge
			}
			f.locals[instr], edge = e, pred.Index
			infer.Logger.Printf(f.Sprintf(PhiSymbol+"%s = %s, selected from block %d", f.locals[instr], instr.String(), edge))
			return edge
		}
	}
	infer.Logger.Fatalf("phi: %d->%d: %s", b.Pred, instr.Block().Index, ErrPhiUnknownEdge)
	return edge
}
<commit_msg>Phi should also try to copy special instance types<commit_after>package typeinfer

import (
	"go/constant"
	"go/token"

	"golang.org/x/tools/go/ssa"
)

// setLoopIndex handles loop indices (initial value and increment)
func setLoopIndex(instr *ssa.Phi, infer *TypeInfer, f *Function, b *Block, l *Loop) {
	if i, ok := instr.Edges[0].(*ssa.Const); ok && !i.IsNil() && i.Value.Kind() == constant.Int {
		l.SetInit(instr, i.Int64())
		infer.Logger.Printf(f.Sprintf(LoopSymbol+"%s <= i", fmtLoopHL(l.Start)))
	}
	if bin, ok := instr.Edges[1].(*ssa.BinOp); ok {
		switch bin.Op {
		case token.ADD:
			if i, ok := bin.Y.(*ssa.Const); ok && i.Value.Kind() == constant.Int {
				l.SetStep(i.Int64())
			}
			infer.Logger.Printf(f.Sprintf(LoopSymbol+"i += %s", fmtLoopHL(l.Step)))
		case token.SUB:
			if i, ok := bin.Y.(*ssa.Const); ok && i.Value.Kind() == constant.Int {
				l.SetStep(-i.Int64())
			}
			infer.Logger.Printf(f.Sprintf(LoopSymbol+"i -= %s", fmtLoopHL(l.Step)))
		default:
			infer.Logger.Printf("loop index expression not supported %s", bin)
		}
	}
}

func phiDetectLoop(instr *ssa.Phi, infer *TypeInfer, f *Function, b *Block, l *Loop) {
	switch l.State {
	case Enter:
		switch l.Bound {
		case Unknown:
			phiSelectEdge(instr, infer, f, b, l)
			setLoopIndex(instr, infer, f, b, l)
		case Static:
			switch l.Bound {
			case Static:
				phiSelectEdge(instr, infer, f, b, l)
				if instr == l.IndexVar {
					l.Next()
					infer.Logger.Printf(f.Sprintf(LoopSymbol+"Increment %s by %s to %s", l.IndexVar.Name(), fmtLoopHL(l.Step), fmtLoopHL(l.Index)))
				}
			default:
				visitSkip(instr, infer, f, b, l)
			}
		case Dynamic:
			phiSelectEdge(instr, infer, f, b, l)
			infer.Logger.Printf(f.Sprintf(PhiSymbol+"(dynamic bound) %s", instr.String()))
		}
	default:
		phiSelectEdge(instr, infer, f, b, l)
	}
}

// phiSelectEdge selects edge based on predecessor block and returns the edge index.
func phiSelectEdge(instr *ssa.Phi, infer *TypeInfer, f *Function, b *Block, l *Loop) int {
	edge := 0
	for i, pred := range instr.Block().Preds {
		if pred.Index == b.Pred {
			e, ok := f.locals[instr.Edges[i]]
			if !ok {
				c, ok := instr.Edges[i].(*ssa.Const)
				if !ok {
					infer.Logger.Fatalf("phi: create instance Edge[%d]=%s: %s", i, instr.Edges[i].String()+instr.Edges[i].Name(), ErrUnknownValue)
				}
				f.locals[instr], edge = &ConstInstance{c}, pred.Index
				infer.Logger.Printf(f.Sprintf(PhiSymbol+"%s/%s = %s, selected const from block %d", instr.Name(), f.locals[instr], instr.String(), edge))
				if a, ok := f.arrays[e]; ok {
					f.arrays[f.locals[instr]] = a
				}
				if s, ok := f.structs[e]; ok {
					f.structs[f.locals[instr]] = s
				}
				return edge
			}
			f.locals[instr], edge = e, pred.Index
			infer.Logger.Printf(f.Sprintf(PhiSymbol+"%s/%s = %s, selected from block %d", instr.Name(), f.locals[instr], instr.String(), edge))
			if a, ok := f.arrays[e]; ok {
				f.arrays[f.locals[instr]] = a
			}
			if s, ok := f.structs[e]; ok {
				f.structs[f.locals[instr]] = s
			}
			return edge
		}
	}
	infer.Logger.Fatalf("phi: %d->%d: %s", b.Pred, instr.Block().Index, ErrPhiUnknownEdge)
	return edge
}
<|endoftext|>


<commit_before>/*
Copyright IBM Corp 2016 All Rights Reserved.

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

		 http://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 main

import (
	"errors"
	"fmt"
	"sort"
	// "strconv"
	"encoding/json"
	// "time"
	// "strings"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

type Option struct {
	Id int `json:"id"`
	Name string `json:"name"`
}

type Vote struct {
	Token string `json:"token"`
	OptionId int `json:"optionId"`
	ReceiptId string `json:"receiptId"`
}

type OptionTotal struct {
  OptionId int `json:"optionId"`
  Total int `json:"total"`
}

type Tally struct {
	VoteCount int `json:"votecount"`
	OptionTotals []OptionTotal `json:"tally"`
}

type Election struct {
	Id string `json:"id"`
	Name string `json:"name"`
	Question string `json:"question"`
	Options []Option  `json:"options"`
	Tokens []string `json:"tokens"`
	Votes []Vote `json:"vote"`
	Tally Tally `json:"tally"`
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	return nil, nil
}

// Invoke isur entry point to invoke a chaincode function
func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)

	// Handle different functions
	if function == "init" {
		return t.Init(stub, "init", args)
	} else if function == "createElection" {
		return t.createElection(stub, args)
	} else if function == "vote" {
		return t.vote(stub, args)
	} else if function == "tally" {
		return t.vote(stub, args)
	}

	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation")
}

// Query is our entry point for queries
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)

	if function == "getElection" {
		election, err := t.getElection(stub, args[0])
		if err != nil {
			return nil, err
		}
		// hide some of the other data
		election.Votes = make([]Vote, 0)
		election.Tokens = make([]string, 0)
		return json.Marshal(&election)
	} else if function == "hasVote" {
		election, err := t.getElection(stub, args[0])
		if err != nil {
			return nil, err
		}
		receiptId := args[1]
		for _,element := range election.Votes {
			if receiptId == element.ReceiptId {
				return json.Marshal("1")
			}
		}
		response, err := json.Marshal("0")
		return response, errors.New("Vote with receipt " + receiptId + " not found")
	}

	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query '" + function + "'")
}

func (t *SimpleChaincode) saveElection(stub *shim.ChaincodeStub, election Election) (error) {

		var err error

		electionWriteBytes, err := json.Marshal(&election)
		if err != nil {
			fmt.Println("Error marshalling election: " + err.Error());
			return errors.New("Error creating election")
		}

		err = stub.PutState(election.Id, electionWriteBytes)

		if err != nil {
			fmt.Println("Error saving election");
			return errors.New("Error saving election")
		}

		return nil
}

func (t *SimpleChaincode) createElection(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	if len(args) != 1 {
			fmt.Println("error invalid arguments")
			return nil, errors.New("Incorrect number of arguments. Expecting election record")
		}

		var election Election
		var err error

		fmt.Println("Unmarshalling Election");
		err = json.Unmarshal([]byte(args[0]), &election)
		if err != nil {
			fmt.Println("error unmarshalling election")
			return nil, errors.New("Invalid election: " + err.Error())
		}

    election.Tally = Tally{}

		err = t.saveElection(stub, election)

		return nil, err
}

func (t *SimpleChaincode) getElection(stub *shim.ChaincodeStub, electionId string) (Election, error){
	var err error
	var election  Election

	if electionId == "" {
			fmt.Println("error invalid arguments")
			return election, errors.New("Incorrect number of arguments. Expecting electionId record")
	}

	fmt.Println("Getting election state");

	electionBytes, err := stub.GetState(electionId)

  err = json.Unmarshal(electionBytes, &election)
	if err != nil {
		fmt.Println("Error unmarshalling election: " + err.Error());
		return election, errors.New("Error unmarshalling election: " + err.Error())
	}

	return election, nil
}

  func (t *SimpleChaincode) vote(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	  if len(args) != 2 {
			fmt.Println("error invalid arguments")
			return nil, errors.New("Incorrect number of arguments. Expecting electionId and vote record")
		}

		var vote Vote
		var election Election
		var err error

		election, err = t.getElection(stub, args[0])

		fmt.Println("Unmarshalling Vote");
		err = json.Unmarshal([]byte(args[1]), &vote)
		if err != nil {
			fmt.Println("error vote")
			return nil, errors.New("Invalid vote")
		}

    token := vote.Token
		for _,element := range election.Votes {
			if token == element.Token {
				return nil, errors.New("Duplicate vote attempt detected")
			}
		}

		election.Votes = append(election.Votes, vote)

		election.Tally.VoteCount = election.Tally.VoteCount + 1

		err = t.saveElection(stub, election)

		if err != nil {
			fmt.Println("Error voting");
			return nil, errors.New("Error voting")
		}

		return nil, nil
	}

	  func (t *SimpleChaincode) tally(stub *shim.ChaincodeStub, args []string) ([]byte, error) {

		  if len(args) != 1 {
				fmt.Println("error invalid arguments")
				return nil, errors.New("Incorrect number of arguments. Expecting electionId")
			}

			var vote Vote
			var election Election
			var err error

			election, err = t.getElection(stub, args[0])

			fmt.Println("Unmarshalling Election");
			err = json.Unmarshal([]byte(args[0]), &vote)
			if err != nil {
				fmt.Println("error unmarshalling election")
				return nil, errors.New("Invalid election")
			}

			election.Tally.VoteCount = 0
			election.Tally.OptionTotals = make([]OptionTotal, 0)

			var counts map[int]int

      counts[-1] = 0

			for _,element := range election.Options {
				counts[element.Id] = 0
			}

			for _,element := range election.Votes {
				election.Tally.VoteCount = election.Tally.VoteCount + 1
        counts[element.OptionId] = counts[element.OptionId] + 1
			}

			var keys []int
			for k := range counts {
			    keys = append(keys, k)
			}
			sort.Ints(keys)
			for _, k := range keys {
				election.Tally.OptionTotals = append(election.Tally.OptionTotals, OptionTotal{k, counts[k]})
			}

			err = t.saveElection(stub, election)

			if err != nil {
				fmt.Println("Error tallying");
				return nil, errors.New("Error tallying")
			}

			return nil, nil
		}
<commit_msg>fix to tally<commit_after>/*
Copyright IBM Corp 2016 All Rights Reserved.

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

		 http://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 main

import (
	"errors"
	"fmt"
	"sort"
	// "strconv"
	"encoding/json"
	// "time"
	// "strings"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

type Option struct {
	Id int `json:"id"`
	Name string `json:"name"`
}

type Vote struct {
	Token string `json:"token"`
	OptionId int `json:"optionId"`
	ReceiptId string `json:"receiptId"`
}

type OptionTotal struct {
  OptionId int `json:"optionId"`
  Total int `json:"total"`
}

type Tally struct {
	VoteCount int `json:"votecount"`
	OptionTotals []OptionTotal `json:"tally"`
}

type Election struct {
	Id string `json:"id"`
	Name string `json:"name"`
	Question string `json:"question"`
	Options []Option  `json:"options"`
	Tokens []string `json:"tokens"`
	Votes []Vote `json:"vote"`
	Tally Tally `json:"tally"`
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}

// Init resets all the things
func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	return nil, nil
}

// Invoke isur entry point to invoke a chaincode function
func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	fmt.Println("invoke is running " + function)

	// Handle different functions
	if function == "init" {
		return t.Init(stub, "init", args)
	} else if function == "createElection" {
		return t.createElection(stub, args)
	} else if function == "vote" {
		return t.vote(stub, args)
	} else if function == "tally" {
		return t.vote(stub, args)
	}

	fmt.Println("invoke did not find func: " + function)

	return nil, errors.New("Received unknown function invocation")
}

// Query is our entry point for queries
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	fmt.Println("query is running " + function)

	if function == "getElection" {
		election, err := t.getElection(stub, args[0])
		if err != nil {
			return nil, err
		}
		// hide some of the other data
		election.Votes = make([]Vote, 0)
		election.Tokens = make([]string, 0)
		return json.Marshal(&election)
	} else if function == "hasVote" {
		election, err := t.getElection(stub, args[0])
		if err != nil {
			return nil, err
		}
		receiptId := args[1]
		for _,element := range election.Votes {
			if receiptId == element.ReceiptId {
				return json.Marshal("1")
			}
		}
		response, err := json.Marshal("0")
		return response, errors.New("Vote with receipt " + receiptId + " not found")
	}

	fmt.Println("query did not find func: " + function)

	return nil, errors.New("Received unknown function query '" + function + "'")
}

func (t *SimpleChaincode) saveElection(stub *shim.ChaincodeStub, election Election) (error) {

		var err error

		electionWriteBytes, err := json.Marshal(&election)
		if err != nil {
			fmt.Println("Error marshalling election: " + err.Error());
			return errors.New("Error creating election")
		}

		err = stub.PutState(election.Id, electionWriteBytes)

		if err != nil {
			fmt.Println("Error saving election");
			return errors.New("Error saving election")
		}

		return nil
}

func (t *SimpleChaincode) createElection(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	if len(args) != 1 {
			fmt.Println("error invalid arguments")
			return nil, errors.New("Incorrect number of arguments. Expecting election record")
		}

		var election Election
		var err error

		fmt.Println("Unmarshalling Election");
		err = json.Unmarshal([]byte(args[0]), &election)
		if err != nil {
			fmt.Println("error unmarshalling election")
			return nil, errors.New("Invalid election: " + err.Error())
		}

    election.Tally = Tally{}

		err = t.saveElection(stub, election)

		return nil, err
}

func (t *SimpleChaincode) getElection(stub *shim.ChaincodeStub, electionId string) (Election, error){
	var err error
	var election  Election

	if electionId == "" {
			fmt.Println("error invalid arguments")
			return election, errors.New("Incorrect number of arguments. Expecting electionId record")
	}

	fmt.Println("Getting election state");

	electionBytes, err := stub.GetState(electionId)

  err = json.Unmarshal(electionBytes, &election)
	if err != nil {
		fmt.Println("Error unmarshalling election: " + err.Error());
		return election, errors.New("Error unmarshalling election: " + err.Error())
	}

	return election, nil
}

  func (t *SimpleChaincode) vote(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	  if len(args) != 2 {
			fmt.Println("error invalid arguments")
			return nil, errors.New("Incorrect number of arguments. Expecting electionId and vote record")
		}

		var vote Vote
		var election Election
		var err error

		election, err = t.getElection(stub, args[0])

		fmt.Println("Unmarshalling Vote");
		err = json.Unmarshal([]byte(args[1]), &vote)
		if err != nil {
			fmt.Println("error vote")
			return nil, errors.New("Invalid vote")
		}

    token := vote.Token
		for _,element := range election.Votes {
			if token == element.Token {
				return nil, errors.New("Duplicate vote attempt detected")
			}
		}

		election.Votes = append(election.Votes, vote)

		election.Tally.VoteCount = election.Tally.VoteCount + 1

		err = t.saveElection(stub, election)

		if err != nil {
			fmt.Println("Error voting");
			return nil, errors.New("Error voting")
		}

		return nil, nil
	}

	  func (t *SimpleChaincode) tally(stub *shim.ChaincodeStub, args []string) ([]byte, error) {

		  if len(args) != 1 {
				fmt.Println("error invalid arguments")
				return nil, errors.New("Incorrect number of arguments. Expecting electionId")
			}

			var election Election
			var err error

			election, err = t.getElection(stub, args[0])

			election.Tally.VoteCount = 0
			election.Tally.OptionTotals = make([]OptionTotal, 0)

			var counts map[int]int

      counts[-1] = 0

			for _,element := range election.Options {
				counts[element.Id] = 0
			}

			for _,element := range election.Votes {
				election.Tally.VoteCount = election.Tally.VoteCount + 1
        counts[element.OptionId] = counts[element.OptionId] + 1
			}

			var keys []int
			for k := range counts {
			    keys = append(keys, k)
			}
			sort.Ints(keys)
			for _, k := range keys {
				election.Tally.OptionTotals = append(election.Tally.OptionTotals, OptionTotal{k, counts[k]})
			}

			err = t.saveElection(stub, election)

			if err != nil {
				fmt.Println("Error tallying");
				return nil, errors.New("Error tallying")
			}

			return nil, nil
		}
<|endoftext|>


<commit_before>package main

// Given a file with filenames, this times how fast we can stat them
// in parallel.  This is useful for benchmarking purposes.

import (
	"github.com/hanwen/go-fuse/fuse"
	"os"
	"flag"
	"time"
	"fmt"
	"encoding/line"
	"runtime"
)

func main() {
	threads := flag.Int("threads", 0, "number of parallel threads in a run. If 0, use CPU count.")
	sleepTime := flag.Float64("sleep", 4.0, "amount of sleep between runs.")
	runs := flag.Int("runs", 10, "number of runs.")

	flag.Parse()
	if *threads == 0 {
		*threads = fuse.CountCpus()
		runtime.GOMAXPROCS(*threads)
	}
	filename := flag.Args()[0]
	f, err := os.Open(filename)
	if err != nil {
		panic("err" + err.String())
	}

	linelen := 1000
	reader := line.NewReader(f, linelen)

	files := make([]string, 0)
	for {
		l, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		files = append(files, string(l))
	}

	tot := 0.0
	totalRuns := *runs + 1

	for j := 0; j < totalRuns; j++ {
		result := BulkStat(*threads, files)
		if j > 0 {
			tot += result
		} else {
			fmt.Println("Ignoring first run to preheat caches.")
		}
		if j < totalRuns-1 {
			fmt.Printf("Sleeping %.2f seconds\n", *sleepTime)
			time.Sleep(int64(*sleepTime * 1e9))
		}
	}

	fmt.Printf("Average of %d runs: %f ms\n", *runs, tot/float64(*runs))
}

func BulkStat(parallelism int, files []string) float64 {
	todo := make(chan string, len(files))
	dts := make(chan int64, parallelism)

	allStart := time.Nanoseconds()

	fmt.Printf("Statting %d files with %d threads\n", len(files), parallelism)
	for i := 0; i < parallelism; i++ {
		go func() {
			for {
				fn := <-todo
				if fn == "" {
					break
				}

				t := time.Nanoseconds()
				os.Lstat(fn)
				dts <- time.Nanoseconds() - t
			}
		}()
	}

	for _, v := range files {
		todo <- v
	}

	total := 0.0
	for i := 0; i < len(files); i++ {
		total += float64(<-dts) * 1e-6
	}

	allEnd := time.Nanoseconds()
	avg := total / float64(len(files))

	fmt.Printf("Elapsed: %f sec. Average stat %f ms\n",
		float64(allEnd-allStart)*1e-9, avg)

	return avg
}
<commit_msg>Compute stddev, median and 10/90 percentile stats as well.<commit_after>package main

// Given a file with filenames, this times how fast we can stat them
// in parallel.  This is useful for benchmarking purposes.

import (
	"encoding/line"
	"flag"
	"fmt"
	"github.com/hanwen/go-fuse/fuse"
	"math"
	"os"
	"runtime"
	"sort"
	"time"
)

func main() {
	threads := flag.Int("threads", 0, "number of parallel threads in a run. If 0, use CPU count.")
	sleepTime := flag.Float64("sleep", 4.0, "amount of sleep between runs.")
	runs := flag.Int("runs", 10, "number of runs.")

	flag.Parse()
	if *threads == 0 {
		*threads = fuse.CountCpus()
		runtime.GOMAXPROCS(*threads)
	}
	filename := flag.Args()[0]
	f, err := os.Open(filename)
	if err != nil {
		panic("err" + err.String())
	}

	linelen := 1000
	reader := line.NewReader(f, linelen)

	files := make([]string, 0)
	for {
		l, _, err := reader.ReadLine()
		if err != nil {
			break
		}
		files = append(files, string(l))
	}

	totalRuns := *runs + 1

	results := make([]float64, 0)
	for j := 0; j < totalRuns; j++ {
		result := BulkStat(*threads, files)
		if j > 0 {
			results = append(results, result)
		} else {
			fmt.Println("Ignoring first run to preheat caches.")
		}

		if j < totalRuns-1 {
			fmt.Printf("Sleeping %.2f seconds\n", *sleepTime)
			time.Sleep(int64(*sleepTime * 1e9))
		}
	}

	Analyze(results)
}

func Analyze(times []float64) {
	sorted := sort.Float64Array(times)
	sorted.Sort()

	tot := 0.0
	for _, v := range times {
		tot += v
	}
	n := float64(len(times))

	avg := tot / n
	variance := 0.0
	for _, v := range times {
		variance += (v - avg)*(v - avg)
	}
	variance /= n

	stddev := math.Sqrt(variance)

	median := sorted[len(times)/2]
	perc90 := sorted[int(n * 0.9)]
	perc10 := sorted[int(n * 0.1)]

	fmt.Printf(
		"%d samples\n" +
		"avg %.2f ms 2sigma %.2f " +
		"median %.2fms\n"  +
		"10%%tile %.2fms, 90%%tile %.2fms\n",
		len(times), avg, 2*stddev, median, perc10, perc90)
}

// Returns milliseconds.
func BulkStat(parallelism int, files []string) float64 {
	todo := make(chan string, len(files))
	dts := make(chan int64, parallelism)

	allStart := time.Nanoseconds()

	fmt.Printf("Statting %d files with %d threads\n", len(files), parallelism)
	for i := 0; i < parallelism; i++ {
		go func() {
			for {
				fn := <-todo
				if fn == "" {
					break
				}

				t := time.Nanoseconds()
				os.Lstat(fn)
				dts <- time.Nanoseconds() - t
			}
		}()
	}

	for _, v := range files {
		todo <- v
	}

	total := 0.0
	for i := 0; i < len(files); i++ {
		total += float64(<-dts) * 1e-6
	}

	allEnd := time.Nanoseconds()
	avg := total / float64(len(files))

	fmt.Printf("Elapsed: %f sec. Average stat %f ms\n",
		float64(allEnd-allStart)*1e-9, avg)

	return avg
}
<|endoftext|>


<commit_before>package geocodio

// Geocodio is the base struct
type Geocodio struct {
	APIKey string
}

type Address struct {
	Components   Components `json:"address_components"`
	Formatted    string     `json:"formatted_address"`
	Location     Location   `json:"location"`
	Accuracy     float64    `json:"accuracy"`
	AccuracyType string     `json:"accuracy_type"`
	Source       string     `json:"source"`
	Fields       Fields     `json:"fields,omitempty"`
}

type Components struct {
	Number          string `json:"number"`
	Street          string `json:"street"`
	Suffix          string `json:"suffix"`
	SecondaryNumber string `json:"secondarynumber"`
	SecondaryUnit   string `json:"secondaryunit"`
	PostDirectional string `json:"postdirectional"`
	FormattedStreet string `json:"formatted_street"`
	City            string `json:"city"`
	State           string `json:"state"`
	Zip             string `json:"zip"`
	County          string `json:"county"`
	Country         string `json:"country"`
	PreDirectional  string `json:"PreDirectional"`
	Prefix          string `json:"Prefix"`
}

type Location struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
}

// Fields
type Fields struct {
	Timezone                  Timezone                  `json:"timezone,omitempty"`
	CongressionalDistrict     CongressionalDistrict     `json:"congressional_district,omitempty"`
	StateLegislativeDistricts StateLegislativeDistricts `json:"state_legislative_districts,omitempty"`
}

type Timezone struct {
	Name        string `json:"name"`
	UTCOffset   int    `json:"utc_offset"`
	ObservesDST bool   `json:"observes_dst"`
}

type CongressionalDistrict struct {
	Name           string `json:"name"`
	DistrictNumber int    `json:"district_number"`
	CongressNumber string `json:"congress_number"`
	CongressYears  string `json:"congress_years"`
}

type StateLegislativeDistricts struct {
	House  StateLegislativeDistrict `json:"house"`
	Senate StateLegislativeDistrict `json:"senate"`
}

type StateLegislativeDistrict struct {
	Name           string `json:"name"`
	DistrictNumber string `json:"district_number"`
}

// GeocodeResponse
type GeocodeResult struct {
	Input struct {
		AddressComponents Components `json:"address_components"`
	} `json:"input,omitempty"`
	Results []Address `json:"results"`
	Debug   struct {
		RawResponse  []byte `json:"-"`
		RequestedURL string `json:"requested_url"`
		Status       string `json:"status"`
		StatusCode   int    `json:"status_code"`
	} `json:"-"`
}

func (self *GeocodeResult) ResponseAsString() string {
	return string(self.Debug.RawResponse)
}
<commit_msg>Add initial census support, legislator, and 1.4 support<commit_after>package geocodio

// Geocodio is the base struct
type Geocodio struct {
	APIKey string
}

type Address struct {
	Components   Components `json:"address_components"`
	Formatted    string     `json:"formatted_address"`
	Location     Location   `json:"location"`
	Accuracy     float64    `json:"accuracy"`
	AccuracyType string     `json:"accuracy_type"`
	Source       string     `json:"source"`
	Fields       Fields     `json:"fields,omitempty"`
}

// Components
/*
	"address_components": {
		"number": "1109",
		"predirectional": "N",
		"street": "Highland",
		"suffix": "St",
		"formatted_street": "N Highland St",
		"city": "Arlington",
		"county": "Arlington County",
		"state": "VA",
		"zip": "22201",
		"country": "US"
	},
*/
type Components struct {
	Number          string `json:"number"`
	Street          string `json:"street"`
	Suffix          string `json:"suffix"`
	SecondaryNumber string `json:"secondarynumber"`
	SecondaryUnit   string `json:"secondaryunit"`
	PostDirectional string `json:"postdirectional"`
	FormattedStreet string `json:"formatted_street"`
	City            string `json:"city"`
	State           string `json:"state"`
	Zip             string `json:"zip"`
	County          string `json:"county"`
	Country         string `json:"country"`
	PreDirectional  string `json:"predirectional"`
	Prefix          string `json:"prefix"`
}

type Location struct {
	Latitude  float64 `json:"lat"`
	Longitude float64 `json:"lng"`
}

// Fields
type Fields struct {
	Timezone                  Timezone                  `json:"timezone,omitempty"`
	CongressionalDistrict     CongressionalDistrict     `json:"congressional_district,omitempty"`  // v1.0
	CongressionalDistricts    []CongressionalDistrict   `json:"congressional_districts,omitempty"` // v1.1+
	StateLegislativeDistricts StateLegislativeDistricts `json:"state_legislative_districts,omitempty"`
	SchoolDistricts           SchoolDistricts           `json:"school_districts,omitempty"`
	Census                    Census                    `json:"census,omitempty"`
	ACS                       CensusACS                 `json:"acs,omitempty"`
}

// Timezone based on this payload
/*
	"timezone": {
    "name": "America/New_York",
    "utc_offset": -5,
    "observes_dst": true,
    "abbreviation": "EST",
    "source": "© OpenStreetMap contributors"
  }
*/

type Timezone struct {
	Name         string `json:"name"`
	Abbreviation string `json:"abbreviation"` // v1.3+
	UTCOffset    int    `json:"utc_offset"`
	ObservesDST  bool   `json:"observes_dst"`
	Source       string `json:"source"`
}

// Congressional District field
/*
"name": "Congressional District 8",
"district_number": 8,
"congress_number": "116th",
"congress_years": "2019-2021",
"proportion": 1,
"current_legislators": [...]
*/
type CongressionalDistrict struct {
	Name               string       `json:"name"`
	DistrictNumber     int          `json:"district_number"`
	CongressNumber     string       `json:"congress_number"`
	CongressYears      string       `json:"congress_years"`
	Proportion         int          `json:"congress_years"`
	CurrentLegislators []Legislator `json:"current_legislators"` // v1.2+
}

// Legislator field
/*
{
	"type": "representative",
	"bio": {...},
	"contact": {...},
	"social": {...},
	"references": {...},
	"source": "Legislator data is originally collected and aggregated by https://github.com/unitedstates/"
}
*/
type Legislator struct {
	Type       string     `json:"type"`
	Bio        Bio        `json:"bio"`
	Contact    Contact    `json:"contact"`
	Social     Social     `json:"social"`
	References References `json:"references"`
	Source     string     `json:"source"`
}

// Bio field
/*
	"bio": {
		"last_name": "Beyer",
		"first_name": "Donald",
		"birthday": "1950-06-20",
		"gender": "M",
		"party": "Democrat"
	}
*/
type Bio struct {
	LastName  string `json:"last_name"`
	FirstName string `json:"first_name"`
	Birthday  string `json:"birthday"`
	Gender    string `json:"gender"`
	Party     string `json:"party"`
}

// Contact field
/*
"contact": {
	"url": "https://beyer.house.gov",
	"address": "1119 Longworth House Office Building Washington DC 20515-4608",
	"phone": "(202) 225-4376",
	"contact_form": null
}
*/
type Contact struct {
	URL         string `json:"url"`
	Address     string `json:"address"`
	Phone       string `json:"phone"`
	ContactForm string `json:"contact_form"`
}

// Social field
/*
"social": {
	"rss_url": null,
	"twitter": "RepDonBeyer",
	"facebook": "RepDonBeyer",
	"youtube": null,
	"youtube_id": "UCPJGVbOVcAVGiBwq8qr_T9w"
}
*/
type Social struct {
	RSSURL    string `json:"rss_url"`
	Twitter   string `json:"twitter"`
	Facebook  string `json:"facebook"`
	YouTube   string `json:"youtube"`
	YouTubeID string `json:"youtube_id"`
}

// References field
/*
"references": {
	"bioguide_id": "B001292",
	"thomas_id": "02272",
	"opensecrets_id": "N00036018",
	"lis_id": null,
	"cspan_id": "21141",
	"govtrack_id": "412657",
	"votesmart_id": "1707",
	"ballotpedia_id": null,
	"washington_post_id": null,
	"icpsr_id": "21554",
	"wikipedia_id": "Don Beyer"
}
*/
type References struct {
	BioguideID       string `json:"bioguide_id"`
	ThomasID         string `json:"thomas_id"`
	OpenSecretsID    string `json:"opensecrets_id"`
	LISID            string `json:"lis_id"`
	CSPANID          string `json:"cspan_id"`
	GovTrackID       string `json:"govtrack_id"`
	VoteSmartID      string `json:"votesmart_id"`
	BallotpediaID    string `json:"ballotpedia_id"`
	WashingtonPostID string `json:"washington_post_id"`
	ICPSRID          string `json:"icpsr_id"`
	WikipediaID      string `json:"wikipedia_id"`
}

type StateLegislativeDistricts struct {
	House  StateLegislativeDistrict `json:"house"`
	Senate StateLegislativeDistrict `json:"senate"`
}

type StateLegislativeDistrict struct {
	Name           string `json:"name"`
	DistrictNumber string `json:"district_number"`
}

type SchoolDistricts struct {
	Unified    SchoolDistrict `json:"unified"`
	Elementary SchoolDistrict `json:"elementary"`
	Secondar   SchoolDistrict `json:"secondary"`
}

// SchoolDistrict field
/*
{
	"name": "Desert Sands Unified School District",
	"lea_code": "11110",
	"grade_low": "KG",
	"grade_high": "12"
}
*/
type SchoolDistrict struct {
	Name      string `json:"name"`
	LEACode   string `json:"lea_code"`
	GradeLow  string `json:"grade_low"`
	GradeHigh string `json:"grade_high"`
}

type CensusResults struct {
	Census2010 *Census `json:"2010,omitempty"`
	Census2011 *Census `json:"2011,omitempty"`
	Census2012 *Census `json:"2012,omitempty"`
	Census2013 *Census `json:"2013,omitempty"`
	Census2014 *Census `json:"2014,omitempty"`
	Census2015 *Census `json:"2015,omitempty"`
	Census2016 *Census `json:"2016,omitempty"`
	Census2017 *Census `json:"2017,omitempty"`
	Census2018 *Census `json:"2018,omitempty"`
	Census2019 *Census `json:"2019,omitempty"`
	Census2020 *Census `json:"2020,omitempty"`
}

// Census field
/*
{
	"census_year": 2010,
	"state_fips": "51",
	"county_fips": "51013",
	"tract_code": "101801",
	"block_code": "1004",
	"block_group": "1",
	"full_fips": "510131018011004",
	"place": {
		"name": "Arlington",
		"fips": "5103000"
	},
	"metro_micro_statistical_area": {
		"name": "Washington-Arlington-Alexandria, DC-VA-MD-WV",
		"area_code": "47900",
		"type": "metropolitan"
	},
	"combined_statistical_area": {
		"name": "Washington-Baltimore-Northern Virginia, DC-MD-VA-WV",
		"area_code": "51548"
	},
	"metropolitan_division": {
		"name": "Washington-Arlington-Alexandria, DC-VA-MD-WV",
		"area_code": "47894"
	},
	"source": "US Census Bureau"
}
*/
type Census struct {
	Year                      int             `json:"census_year"`
	StateFIPS                 string          `json:"state_fips"`
	CountyFIPS                string          `json:"county_fips"`
	TractCode                 string          `json:"tract_code"`
	BlockCode                 string          `json:"block_code"`
	BlockGroup                string          `json:"block_group"`
	FullFIPS                  string          `json:"full_fips"`
	Place                     Place           `json:"place"`
	MetroMicroStatisticalArea StatisticalArea `json:"metro_micro_statistical_area"`
	CombinedStatisticalArea   StatisticalArea `json:"combined_statistical_area"`
	MetropolitanDivision      StatisticalArea `json:"metropolitan_division"`
	Source                    string          `json:"source"`
}

type Place struct {
	Name string `json:"name"`
	FIPS string `json:"fips"`
}

type StatisticalArea struct {
	Name     string `json:"name"`
	AreaCode string `json:"area_code"`
	Type     string `json:"type,omitempty"`
}

type CensusACS struct {
	Meta         CensusMeta  `json:"meta"`
	Demographics Demographic `json:"demographics"`
	Economics    Economics   `json:"economics`
}

type Economics struct {
	NumberOfHouseholds    struct{}              `json:"Number of households"`
	MedianHouseholdIncome MedianHouseholdIncome `json:"Median household income"`
	HouseholdIncome       HouseholdIncome       `json:"Household income"`
}

type NumberOfHouseholds struct {
	Meta  CensusMeta      `json:"meta"`
	Total CensusDataPoint `json:"Total"`
}

type MedianHouseholdIncome struct {
	Meta  CensusMeta      `json:"meta"`
	Total CensusDataPoint `json:"Total"`
}

type HouseholdIncome struct {
	Meta                 CensusMeta      `json:"meta"`
	LessThan10000        CensusDataPoint `json:"Less than $10,000"`
	Income10000to14999   CensusDataPoint `json:"$10,000 to $14,999"`
	Income15000to19999   CensusDataPoint `json:"$15,000 to $19,999"`
	Income20000to24999   CensusDataPoint `json:"$20,000 to $24,999"`
	Income25000to29999   CensusDataPoint `json:"$25,000 to $29,999"`
	Income30000to34999   CensusDataPoint `json:"$30,000 to $34,999"`
	Income35000to39999   CensusDataPoint `json:"$35,000 to $39,999"`
	Income40000to44999   CensusDataPoint `json:"$40,000 to $44,999"`
	Income45000to49999   CensusDataPoint `json:"$45,000 to $49,999"`
	Income50000to59000   CensusDataPoint `json:"$50,000 to $59,999"`
	Income60000to74999   CensusDataPoint `json:"$60,000 to $74,999"`
	Income75000to99999   CensusDataPoint `json:"$75,000 to $99,999"`
	Income100000to124999 CensusDataPoint `json:"$100,000 to $124,999"`
	Income125000to149000 CensusDataPoint `json:"$125,000 to $149,999"`
	Income150000to199999 CensusDataPoint `json:"$150,000 to $199,999"`
	Income200000orMore   CensusDataPoint `json:"$200,000 or more"`
}

type Demographic struct {
	MedianAge            map[string]CensusDataPoint `json:"Median age"`
	PopulationByAgeRange map[string]CensusDataPoint `json:"Population by age range"`
	Sex                  map[string]CensusDataPoint `json:"Sex"`
	RaceAndEthnicity     map[string]CensusDataPoint `json:"Race and ethnicity"`
}

type CensusMeta struct {
	Source              string `json:"source"`
	SurveyYears         string `json:"survey_years"`
	SurveyDurationYears string `json:"survey_duration_years"`
	TableID             string `json:"table_id"`
	Universe            string `json:"universe"`
}

type CensusDataPoint struct {
	Value         float64 `json:"value"`
	MarginOfError float64 `json:"margin_of_error"`
	Percentage    float64 `json:"percentage"`
	TableID       string  `json:"table_id"`
	Universe      string  `json:"universe"`
}

type Input struct {
	AddressComponents Components `json:"address_components"`
	FormattedAddress  string     `json:"formatted_address"`
}

// GeocodeResponse
type GeocodeResult struct {
	Input   Input     `json:"input,omitempty"`
	Results []Address `json:"results"`
	Debug   struct {
		RawResponse  []byte `json:"-"`
		RequestedURL string `json:"requested_url"`
		Status       string `json:"status"`
		StatusCode   int    `json:"status_code"`
	} `json:"-"`
}

func (self *GeocodeResult) ResponseAsString() string {
	return string(self.Debug.RawResponse)
}
<|endoftext|>


<commit_before>package expr

import (
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

var (
	ErrMissingArg          = errors.New("argument missing")
	ErrTooManyArg          = errors.New("too many arguments")
	ErrMissingTimeseries   = errors.New("missing time series argument")
	ErrWildcardNotAllowed  = errors.New("found wildcard where series expected")
	ErrMissingExpr         = errors.New("missing expression")
	ErrMissingComma        = errors.New("missing comma")
	ErrMissingQuote        = errors.New("missing quote")
	ErrUnexpectedCharacter = errors.New("unexpected character")
	ErrIllegalCharacter    = errors.New("illegal character for function name")
)

type ErrBadArgument struct {
	exp reflect.Type
	got reflect.Type
}

func (e ErrBadArgument) Error() string {
	return fmt.Sprintf("argument bad type. expected %s - got %s", e.exp, e.got)
}

type ErrBadArgumentStr struct {
	exp string
	got string
}

func (e ErrBadArgumentStr) Error() string {
	return fmt.Sprintf("argument bad type. expected %s - got %s", e.exp, e.got)
}

type ErrUnknownFunction string

func (e ErrUnknownFunction) Error() string {
	return fmt.Sprintf("unknown function %q", string(e))
}

type ErrUnknownKwarg struct {
	key string
}

func (e ErrUnknownKwarg) Error() string {
	return fmt.Sprintf("unknown keyword argument %q", e)
}

type ErrBadKwarg struct {
	key string
	exp Arg
	got exprType
}

func (e ErrBadKwarg) Error() string {
	return fmt.Sprintf("keyword argument %q bad type. expected %T - got %s", e.key, e.exp, e.got)
}

type ErrKwargSpecifiedTwice struct {
	key string
}

func (e ErrKwargSpecifiedTwice) Error() string {
	return fmt.Sprintf("keyword argument %q specified twice", e.key)
}

type MetricRequest struct {
	Metric string
	From   int32
	Until  int32
}

// ParseMany parses a slice of strings into a slice of expressions (recursively)
// not included: validation that requested functions exist, correct args are passed, etc.
func ParseMany(targets []string) ([]*expr, error) {
	var out []*expr
	for _, target := range targets {
		e, leftover, err := Parse(target)
		if err != nil {
			return nil, err
		}
		if leftover != "" {
			return nil, fmt.Errorf("failed to parse %q fully. got leftover %q", target, leftover)
		}
		out = append(out, e)
	}
	return out, nil
}

// Parses an expression string and turns it into an expression
// also returns any leftover data that could not be parsed
func Parse(e string) (*expr, string, error) {
	// skip whitespace
	for len(e) > 1 && e[0] == ' ' {
		e = e[1:]
	}

	if len(e) == 0 {
		return nil, "", ErrMissingExpr
	}

	if '0' <= e[0] && e[0] <= '9' || e[0] == '-' || e[0] == '+' {
		return parseConst(e)
	}

	if strings.HasPrefix(e, "True") || strings.HasPrefix(e, "true") {
		return &expr{bool: true, str: e[:4], etype: etBool}, e[4:], nil
	}

	if strings.HasPrefix(e, "False") || strings.HasPrefix(e, "false") {
		return &expr{bool: false, str: e[:5], etype: etBool}, e[5:], nil
	}

	if e[0] == '\'' || e[0] == '"' {
		val, e, err := parseString(e)
		return &expr{str: val, etype: etString}, e, err
	}

	name, e := parseName(e)

	if name == "" {
		return nil, e, ErrMissingArg
	}

	if e != "" && e[0] == '(' {
		for i := range name {
			if !isFnChar(name[i]) {
				return nil, "", ErrIllegalCharacter
			}
		}

		exp := &expr{str: name, etype: etFunc}

		ArgString, posArgs, namedArgs, e, err := parseArgList(e)
		exp.argsStr = ArgString
		exp.args = posArgs
		exp.namedArgs = namedArgs

		return exp, e, err
	}

	return &expr{str: name, etype: etName}, e, nil
}

// caller must assure s starts with opening paren
func parseArgList(e string) (string, []*expr, map[string]*expr, string, error) {

	var (
		posArgs   []*expr
		namedArgs map[string]*expr
	)

	if e[0] != '(' {
		panic("arg list should start with paren. calling code should have asserted this")
	}

	ArgString := e[1:]

	e = e[1:]

	for {
		var arg *expr
		var err error
		arg, e, err = Parse(e)
		if err != nil {
			return "", nil, nil, e, err
		}

		if e == "" {
			return "", nil, nil, "", ErrMissingComma
		}

		// we now know we're parsing a key-value pair
		if arg.etype == etName && e[0] == '=' {
			e = e[1:]
			argCont, eCont, errCont := Parse(e)
			if errCont != nil {
				return "", nil, nil, eCont, errCont
			}

			if eCont == "" {
				return "", nil, nil, "", ErrMissingComma
			}

			if argCont.etype != etInt && argCont.etype != etFloat && argCont.etype != etName && argCont.etype != etString && argCont.etype != etBool {
				return "", nil, nil, eCont, ErrBadArgumentStr{"int, float, name, bool or string", string(argCont.etype)}
			}

			if namedArgs == nil {
				namedArgs = make(map[string]*expr)
			}

			namedArgs[arg.str] = argCont

			e = eCont
		} else {
			posArgs = append(posArgs, arg)
		}

		// after the argument, trim any trailing spaces
		for len(e) > 0 && e[0] == ' ' {
			e = e[1:]
		}

		if e[0] == ')' {
			return ArgString[:len(ArgString)-len(e)], posArgs, namedArgs, e[1:], nil
		}

		if e[0] != ',' && e[0] != ' ' {
			return "", nil, nil, "", ErrUnexpectedCharacter
		}

		e = e[1:]
	}
}

func isNameChar(r byte) bool {
	return false ||
		'a' <= r && r <= 'z' ||
		'A' <= r && r <= 'Z' ||
		'0' <= r && r <= '9' ||
		r == '.' || r == '_' || r == '-' || r == '*' || r == '?' || r == ':' ||
		r == '[' || r == ']' ||
		r == '<' || r == '>'
}

func isFnChar(r byte) bool {
	return false ||
		'a' <= r && r <= 'z' ||
		'A' <= r && r <= 'Z' ||
		'0' <= r && r <= '9'
}

func isDigit(r byte) bool {
	return '0' <= r && r <= '9'
}

func parseConst(s string) (*expr, string, error) {

	var i int
	var float bool
	// All valid characters for a floating-point constant
	// Just slurp them all in and let ParseFloat sort 'em out
	for i < len(s) && (isDigit(s[i]) || s[i] == '.' || s[i] == '+' || s[i] == '-' || s[i] == 'e' || s[i] == 'E') {
		// note that exponent syntax results into a float value.
		// so even values like 1e3 (1000) or 2000e-3 (2) which can be expressed as integers,
		// are considered floating point values.  if a function expets an int, then just don't use 'e' syntax.
		if s[i] == '.' || s[i] == 'e' || s[i] == 'E' {
			float = true
		}
		i++
	}

	if float {
		v, err := strconv.ParseFloat(s[:i], 64)
		return &expr{float: v, str: s[:i], etype: etFloat}, s[i:], err
	}
	v, err := strconv.ParseInt(s[:i], 10, 64)
	return &expr{int: v, str: s[:i], etype: etInt}, s[i:], err
}

func parseName(s string) (string, string) {

	var i int

FOR:
	for braces := 0; i < len(s); i++ {

		if isNameChar(s[i]) {
			continue
		}

		switch s[i] {
		case '{':
			braces++
		case '}':
			if braces == 0 {
				break FOR

			}
			braces--
		case ',':
			if braces == 0 {
				break FOR
			}
		default:
			break FOR
		}

	}

	if i == len(s) {
		return s, ""
	}

	return s[:i], s[i:]
}

// caller must assure s starts with a single or double quote
func parseString(s string) (string, string, error) {

	if s[0] != '\'' && s[0] != '"' {
		panic("string should start with open quote. calling code should have asserted this")
	}

	match := s[0]

	s = s[1:]

	var i int
	for i < len(s) && s[i] != match {
		i++
	}

	if i == len(s) {
		return "", "", ErrMissingQuote

	}

	return s[:i], s[i+1:], nil
}

// exctractMetric searches for a metric name in `m'
// metric name is defined to be a series of name characters terminated by a comma
func extractMetric(m string) string {
	start := 0
	end := 0
	curlyBraces := 0
	for end < len(m) {
		if m[end] == '{' {
			curlyBraces++
		} else if m[end] == '}' {
			curlyBraces--
		} else if m[end] == ')' || (m[end] == ',' && curlyBraces == 0) {
			return m[start:end]
		} else if !(isNameChar(m[end]) || m[end] == ',') {
			start = end + 1
		}

		end++
	}

	return m[start:end]
}
<commit_msg>support the full char set that graphite supports for metric names<commit_after>package expr

import (
	"errors"
	"fmt"
	"reflect"
	"strconv"
	"strings"
)

var (
	ErrMissingArg          = errors.New("argument missing")
	ErrTooManyArg          = errors.New("too many arguments")
	ErrMissingTimeseries   = errors.New("missing time series argument")
	ErrWildcardNotAllowed  = errors.New("found wildcard where series expected")
	ErrMissingExpr         = errors.New("missing expression")
	ErrMissingComma        = errors.New("missing comma")
	ErrMissingQuote        = errors.New("missing quote")
	ErrUnexpectedCharacter = errors.New("unexpected character")
	ErrIllegalCharacter    = errors.New("illegal character for function name")
)

type ErrBadArgument struct {
	exp reflect.Type
	got reflect.Type
}

func (e ErrBadArgument) Error() string {
	return fmt.Sprintf("argument bad type. expected %s - got %s", e.exp, e.got)
}

type ErrBadArgumentStr struct {
	exp string
	got string
}

func (e ErrBadArgumentStr) Error() string {
	return fmt.Sprintf("argument bad type. expected %s - got %s", e.exp, e.got)
}

type ErrUnknownFunction string

func (e ErrUnknownFunction) Error() string {
	return fmt.Sprintf("unknown function %q", string(e))
}

type ErrUnknownKwarg struct {
	key string
}

func (e ErrUnknownKwarg) Error() string {
	return fmt.Sprintf("unknown keyword argument %q", e)
}

type ErrBadKwarg struct {
	key string
	exp Arg
	got exprType
}

func (e ErrBadKwarg) Error() string {
	return fmt.Sprintf("keyword argument %q bad type. expected %T - got %s", e.key, e.exp, e.got)
}

type ErrKwargSpecifiedTwice struct {
	key string
}

func (e ErrKwargSpecifiedTwice) Error() string {
	return fmt.Sprintf("keyword argument %q specified twice", e.key)
}

type MetricRequest struct {
	Metric string
	From   int32
	Until  int32
}

// ParseMany parses a slice of strings into a slice of expressions (recursively)
// not included: validation that requested functions exist, correct args are passed, etc.
func ParseMany(targets []string) ([]*expr, error) {
	var out []*expr
	for _, target := range targets {
		e, leftover, err := Parse(target)
		if err != nil {
			return nil, err
		}
		if leftover != "" {
			return nil, fmt.Errorf("failed to parse %q fully. got leftover %q", target, leftover)
		}
		out = append(out, e)
	}
	return out, nil
}

// Parses an expression string and turns it into an expression
// also returns any leftover data that could not be parsed
func Parse(e string) (*expr, string, error) {
	// skip whitespace
	for len(e) > 1 && e[0] == ' ' {
		e = e[1:]
	}

	if len(e) == 0 {
		return nil, "", ErrMissingExpr
	}

	if '0' <= e[0] && e[0] <= '9' || e[0] == '-' || e[0] == '+' {
		return parseConst(e)
	}

	if strings.HasPrefix(e, "True") || strings.HasPrefix(e, "true") {
		return &expr{bool: true, str: e[:4], etype: etBool}, e[4:], nil
	}

	if strings.HasPrefix(e, "False") || strings.HasPrefix(e, "false") {
		return &expr{bool: false, str: e[:5], etype: etBool}, e[5:], nil
	}

	if e[0] == '\'' || e[0] == '"' {
		val, e, err := parseString(e)
		return &expr{str: val, etype: etString}, e, err
	}

	name, e := parseName(e)

	if name == "" {
		return nil, e, ErrMissingArg
	}

	if e != "" && e[0] == '(' {
		for i := range name {
			if !isFnChar(name[i]) {
				return nil, "", ErrIllegalCharacter
			}
		}

		exp := &expr{str: name, etype: etFunc}

		ArgString, posArgs, namedArgs, e, err := parseArgList(e)
		exp.argsStr = ArgString
		exp.args = posArgs
		exp.namedArgs = namedArgs

		return exp, e, err
	}

	return &expr{str: name, etype: etName}, e, nil
}

// caller must assure s starts with opening paren
func parseArgList(e string) (string, []*expr, map[string]*expr, string, error) {

	var (
		posArgs   []*expr
		namedArgs map[string]*expr
	)

	if e[0] != '(' {
		panic("arg list should start with paren. calling code should have asserted this")
	}

	ArgString := e[1:]

	e = e[1:]

	for {
		var arg *expr
		var err error
		arg, e, err = Parse(e)
		if err != nil {
			return "", nil, nil, e, err
		}

		if e == "" {
			return "", nil, nil, "", ErrMissingComma
		}

		// we now know we're parsing a key-value pair
		if arg.etype == etName && e[0] == '=' {
			e = e[1:]
			argCont, eCont, errCont := Parse(e)
			if errCont != nil {
				return "", nil, nil, eCont, errCont
			}

			if eCont == "" {
				return "", nil, nil, "", ErrMissingComma
			}

			if argCont.etype != etInt && argCont.etype != etFloat && argCont.etype != etName && argCont.etype != etString && argCont.etype != etBool {
				return "", nil, nil, eCont, ErrBadArgumentStr{"int, float, name, bool or string", string(argCont.etype)}
			}

			if namedArgs == nil {
				namedArgs = make(map[string]*expr)
			}

			namedArgs[arg.str] = argCont

			e = eCont
		} else {
			posArgs = append(posArgs, arg)
		}

		// after the argument, trim any trailing spaces
		for len(e) > 0 && e[0] == ' ' {
			e = e[1:]
		}

		if e[0] == ')' {
			return ArgString[:len(ArgString)-len(e)], posArgs, namedArgs, e[1:], nil
		}

		if e[0] != ',' && e[0] != ' ' {
			return "", nil, nil, "", ErrUnexpectedCharacter
		}

		e = e[1:]
	}
}

var nameChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&*+-/:;<>?@[]^_|~."

func isNameChar(r byte) bool {
	return strings.IndexByte(nameChar, r) >= 0
}

func isFnChar(r byte) bool {
	return false ||
		'a' <= r && r <= 'z' ||
		'A' <= r && r <= 'Z' ||
		'0' <= r && r <= '9'
}

func isDigit(r byte) bool {
	return '0' <= r && r <= '9'
}

func parseConst(s string) (*expr, string, error) {

	var i int
	var float bool
	// All valid characters for a floating-point constant
	// Just slurp them all in and let ParseFloat sort 'em out
	for i < len(s) && (isDigit(s[i]) || s[i] == '.' || s[i] == '+' || s[i] == '-' || s[i] == 'e' || s[i] == 'E') {
		// note that exponent syntax results into a float value.
		// so even values like 1e3 (1000) or 2000e-3 (2) which can be expressed as integers,
		// are considered floating point values.  if a function expets an int, then just don't use 'e' syntax.
		if s[i] == '.' || s[i] == 'e' || s[i] == 'E' {
			float = true
		}
		i++
	}

	if float {
		v, err := strconv.ParseFloat(s[:i], 64)
		return &expr{float: v, str: s[:i], etype: etFloat}, s[i:], err
	}
	v, err := strconv.ParseInt(s[:i], 10, 64)
	return &expr{int: v, str: s[:i], etype: etInt}, s[i:], err
}

func parseName(s string) (string, string) {

	var i int

FOR:
	for braces := 0; i < len(s); i++ {

		if isNameChar(s[i]) {
			continue
		}

		switch s[i] {
		case '{':
			braces++
		case '}':
			if braces == 0 {
				break FOR

			}
			braces--
		case ',':
			if braces == 0 {
				break FOR
			}
		default:
			break FOR
		}

	}

	if i == len(s) {
		return s, ""
	}

	return s[:i], s[i:]
}

// caller must assure s starts with a single or double quote
func parseString(s string) (string, string, error) {

	if s[0] != '\'' && s[0] != '"' {
		panic("string should start with open quote. calling code should have asserted this")
	}

	match := s[0]

	s = s[1:]

	var i int
	for i < len(s) && s[i] != match {
		i++
	}

	if i == len(s) {
		return "", "", ErrMissingQuote

	}

	return s[:i], s[i+1:], nil
}

// exctractMetric searches for a metric name in `m'
// metric name is defined to be a series of name characters terminated by a comma
func extractMetric(m string) string {
	start := 0
	end := 0
	curlyBraces := 0
	for end < len(m) {
		if m[end] == '{' {
			curlyBraces++
		} else if m[end] == '}' {
			curlyBraces--
		} else if m[end] == ')' || (m[end] == ',' && curlyBraces == 0) {
			return m[start:end]
		} else if !(isNameChar(m[end]) || m[end] == ',') {
			start = end + 1
		}

		end++
	}

	return m[start:end]
}
<|endoftext|>