<commit_before>package models

import (
	"encoding/json"
	"errors"
	"fmt"
	"sort"

	"github.com/bitrise-io/go-utils/parseutil"
	"github.com/bitrise-io/go-utils/pointers"
)

const (
	// OptionsKey ...
	OptionsKey = "opts"
)

const (
	// DefaultIsExpand ...
	DefaultIsExpand = true
	// DefaultIsSensitive ...
	DefaultIsSensitive = false
	// DefaultSkipIfEmpty ...
	DefaultSkipIfEmpty = false

	//DefaultIsRequired ...
	DefaultIsRequired = false
	// DefaultIsDontChangeValue ...
	DefaultIsDontChangeValue = false
	// DefaultIsTemplate ...
	DefaultIsTemplate = false
	// DefaultUnset ...
	DefaultUnset = false
)

// NewEnvJSONList ...
func NewEnvJSONList(jsonStr string) (EnvsJSONListModel, error) {
	list := EnvsJSONListModel{}
	if err := json.Unmarshal([]byte(jsonStr), &list); err != nil {
		return EnvsJSONListModel{}, err
	}
	return list, nil
}

// GetKeyValuePair ...
func (env EnvironmentItemModel) GetKeyValuePair() (string, string, error) {
	// Collect keys and values
	keys := []string{}
	values := []interface{}{}

	for key, value := range env {
		keys = append(keys, key)
		values = append(values, value)
	}

	if len(keys) == 0 {
		return "", "", errors.New("no environment key specified")
	} else if len(keys) > 2 {
		sort.Strings(keys)
		return "", "", fmt.Errorf("more than 2 keys specified: %v", keys)
	}

	// Collect env key and value
	key := ""
	var value interface{}
	optionsFound := false

	for i := 0; i < len(keys); i++ {
		k := keys[i]
		if k != OptionsKey {
			key = k
			value = values[i]
		} else {
			optionsFound = true
		}
	}

	if key == "" {
		sort.Strings(keys)
		return "", "", fmt.Errorf("no environment key found, keys: %v", keys)
	}
	if len(keys) > 1 && !optionsFound {
		sort.Strings(keys)
		return "", "", fmt.Errorf("more than 1 environment key specified: %v", keys)
	}

	// Cast env value to string
	valueStr := ""

	if value != nil {
		if str, ok := value.(string); ok {
			valueStr = str
		} else if str := parseutil.CastToString(value); str != "" {
			valueStr = str
		} else {
			return "", "", fmt.Errorf("value (%#v) is not a string for key (%s)", value, key)
		}
	}

	return key, valueStr, nil
}

// ParseFromInterfaceMap ...
func (envSerModel *EnvironmentItemOptionsModel) ParseFromInterfaceMap(input map[string]interface{}) error {
	for keyStr, value := range input {

		switch keyStr {
		case "title":
			envSerModel.Title = parseutil.CastToStringPtr(value)
		case "description":
			envSerModel.Description = parseutil.CastToStringPtr(value)
		case "summary":
			envSerModel.Summary = parseutil.CastToStringPtr(value)
		case "category":
			envSerModel.Category = parseutil.CastToStringPtr(value)
		case "value_options":
			castedValue, ok := value.([]string)
			if !ok {
				// try with []interface{} instead and cast the
				//  items to string
				castedValue = []string{}
				interfArr, ok := value.([]interface{})
				if !ok {
					return fmt.Errorf("invalid value type (%#v) for key: %s", value, keyStr)
				}
				for _, interfItm := range interfArr {
					castedItm, ok := interfItm.(string)
					if !ok {
						castedItm = parseutil.CastToString(interfItm)
						if castedItm == "" {
							return fmt.Errorf("not a string value (%#v) in value_options", interfItm)
						}
					}
					castedValue = append(castedValue, castedItm)
				}
			}
			envSerModel.ValueOptions = castedValue
		case "is_required":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsRequired = castedBoolPtr
		case "is_expand":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsExpand = castedBoolPtr
		case "is_sensitive":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsSensitive = castedBoolPtr
		case "is_dont_change_value":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsDontChangeValue = castedBoolPtr
		case "is_template":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsTemplate = castedBoolPtr
		case "skip_if_empty":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.SkipIfEmpty = castedBoolPtr
		case "unset":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.Unset = castedBoolPtr
		case "meta":
			castedMapStringInterface, ok := parseutil.CastToMapStringInterface(value)
			if !ok {
				return fmt.Errorf("failed to parse map[string]interface{} value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.Meta = castedMapStringInterface
		default:
			// intentional no-op case -- we just ignore unrecognized fields
		}
	}
	return nil
}

// GetOptions ...
func (env EnvironmentItemModel) GetOptions() (EnvironmentItemOptionsModel, error) {
	value, found := env[OptionsKey]
	if !found {
		return EnvironmentItemOptionsModel{}, nil
	}

	envItmCasted, ok := value.(EnvironmentItemOptionsModel)
	if ok {
		return envItmCasted, nil
	}

	// if it's read from a file (YAML/JSON) then it's most likely not the proper type
	//  so cast it from the generic interface-interface map
	normalizedOptsInterfaceMap := make(map[string]interface{})
	isNormalizeOK := false
	if optionsInterfaceMap, ok := value.(map[interface{}]interface{}); ok {
		// Try to normalize every key to String
		for key, value := range optionsInterfaceMap {
			keyStr, ok := key.(string)
			if !ok {
				return EnvironmentItemOptionsModel{}, fmt.Errorf("failed to cask options key (%#v) to string", key)
			}
			normalizedOptsInterfaceMap[keyStr] = value
		}
		isNormalizeOK = true
	} else {
		if castedTmp, ok := value.(map[string]interface{}); ok {
			normalizedOptsInterfaceMap = castedTmp
			isNormalizeOK = true
		}
	}

	if isNormalizeOK {
		options := EnvironmentItemOptionsModel{}
		err := options.ParseFromInterfaceMap(normalizedOptsInterfaceMap)
		if err != nil {
			return EnvironmentItemOptionsModel{}, err
		}

		return options, nil
	}

	return EnvironmentItemOptionsModel{}, fmt.Errorf("failed to cast options value: (%#v)", value)
}

// Normalize ...
func (env *EnvironmentItemModel) Normalize() error {
	opts, err := env.GetOptions()
	if err != nil {
		return err
	}
	(*env)[OptionsKey] = opts
	return nil
}

// Normalize - if successful this makes the model JSON serializable.
// Without this, if the object was created with e.g. a YAML parser,
// the type of `opts` might be map[interface]interface, which is not JSON serializable.
// After this call it's ensured that the type of objects is map[string]interface,
// which is JSON serializable.
func (envsSerializeObj *EnvsSerializeModel) Normalize() error {
	for _, envObj := range envsSerializeObj.Envs {
		if err := envObj.Normalize(); err != nil {
			return err
		}
	}
	return nil
}

// FillMissingDefaults ...
func (env *EnvironmentItemModel) FillMissingDefaults() error {
	options, err := env.GetOptions()
	if err != nil {
		return err
	}
	if options.Title == nil {
		options.Title = pointers.NewStringPtr("")
	}
	if options.Description == nil {
		options.Description = pointers.NewStringPtr("")
	}
	if options.Summary == nil {
		options.Summary = pointers.NewStringPtr("")
	}
	if options.Category == nil {
		options.Category = pointers.NewStringPtr("")
	}
	if options.ValueOptions == nil {
		options.ValueOptions = []string{}
	}
	if options.IsRequired == nil {
		options.IsRequired = pointers.NewBoolPtr(DefaultIsRequired)
	}
	if options.IsExpand == nil {
		options.IsExpand = pointers.NewBoolPtr(DefaultIsExpand)
	}
	if options.IsSensitive == nil {
		options.IsSensitive = pointers.NewBoolPtr(DefaultIsSensitive)
	}
	if options.IsDontChangeValue == nil {
		options.IsDontChangeValue = pointers.NewBoolPtr(DefaultIsDontChangeValue)
	}
	if options.IsTemplate == nil {
		options.IsTemplate = pointers.NewBoolPtr(DefaultIsTemplate)
	}
	if options.SkipIfEmpty == nil {
		options.SkipIfEmpty = pointers.NewBoolPtr(DefaultSkipIfEmpty)
	}
	if options.Meta == nil {
		options.Meta = map[string]interface{}{}
	}
	if options.Unset == nil {
		options.Unset = pointers.NewBoolPtr(DefaultUnset)
	}

	(*env)[OptionsKey] = options
	return nil
}

// Validate ...
func (env EnvironmentItemModel) Validate() error {
	key, _, err := env.GetKeyValuePair()
	if err != nil {
		return err
	}
	if key == "" {
		return errors.New("no environment key found")
	}
	_, err = env.GetOptions()
	if err != nil {
		return err
	}
	return nil
}

// NormalizeValidateFillDefaults ...
func (env EnvironmentItemModel) NormalizeValidateFillDefaults() error {
	if err := env.Normalize(); err != nil {
		return err
	}

	if err := env.Validate(); err != nil {
		return err
	}

	return env.FillMissingDefaults()
}
<commit_msg>Remove duplicated env key validation. (#202)<commit_after>package models

import (
	"encoding/json"
	"errors"
	"fmt"
	"sort"

	"github.com/bitrise-io/go-utils/parseutil"
	"github.com/bitrise-io/go-utils/pointers"
)

const (
	// OptionsKey ...
	OptionsKey = "opts"
)

const (
	// DefaultIsExpand ...
	DefaultIsExpand = true
	// DefaultIsSensitive ...
	DefaultIsSensitive = false
	// DefaultSkipIfEmpty ...
	DefaultSkipIfEmpty = false

	//DefaultIsRequired ...
	DefaultIsRequired = false
	// DefaultIsDontChangeValue ...
	DefaultIsDontChangeValue = false
	// DefaultIsTemplate ...
	DefaultIsTemplate = false
	// DefaultUnset ...
	DefaultUnset = false
)

// NewEnvJSONList ...
func NewEnvJSONList(jsonStr string) (EnvsJSONListModel, error) {
	list := EnvsJSONListModel{}
	if err := json.Unmarshal([]byte(jsonStr), &list); err != nil {
		return EnvsJSONListModel{}, err
	}
	return list, nil
}

// GetKeyValuePair ...
func (env EnvironmentItemModel) GetKeyValuePair() (string, string, error) {
	// Collect keys and values
	keys := []string{}
	values := []interface{}{}

	for key, value := range env {
		keys = append(keys, key)
		values = append(values, value)
	}

	if len(keys) == 0 {
		return "", "", errors.New("no environment key specified")
	} else if len(keys) > 2 {
		sort.Strings(keys)
		return "", "", fmt.Errorf("more than 2 keys specified: %v", keys)
	}

	// Collect env key and value
	key := ""
	var value interface{}
	optionsFound := false

	for i := 0; i < len(keys); i++ {
		k := keys[i]
		if k != OptionsKey {
			key = k
			value = values[i]
		} else {
			optionsFound = true
		}
	}

	if key == "" {
		sort.Strings(keys)
		return "", "", fmt.Errorf("no environment key found, keys: %v", keys)
	}
	if len(keys) > 1 && !optionsFound {
		sort.Strings(keys)
		return "", "", fmt.Errorf("more than 1 environment key specified: %v", keys)
	}

	// Cast env value to string
	valueStr := ""

	if value != nil {
		if str, ok := value.(string); ok {
			valueStr = str
		} else if str := parseutil.CastToString(value); str != "" {
			valueStr = str
		} else {
			return "", "", fmt.Errorf("value (%#v) is not a string for key (%s)", value, key)
		}
	}

	return key, valueStr, nil
}

// ParseFromInterfaceMap ...
func (envSerModel *EnvironmentItemOptionsModel) ParseFromInterfaceMap(input map[string]interface{}) error {
	for keyStr, value := range input {

		switch keyStr {
		case "title":
			envSerModel.Title = parseutil.CastToStringPtr(value)
		case "description":
			envSerModel.Description = parseutil.CastToStringPtr(value)
		case "summary":
			envSerModel.Summary = parseutil.CastToStringPtr(value)
		case "category":
			envSerModel.Category = parseutil.CastToStringPtr(value)
		case "value_options":
			castedValue, ok := value.([]string)
			if !ok {
				// try with []interface{} instead and cast the
				//  items to string
				castedValue = []string{}
				interfArr, ok := value.([]interface{})
				if !ok {
					return fmt.Errorf("invalid value type (%#v) for key: %s", value, keyStr)
				}
				for _, interfItm := range interfArr {
					castedItm, ok := interfItm.(string)
					if !ok {
						castedItm = parseutil.CastToString(interfItm)
						if castedItm == "" {
							return fmt.Errorf("not a string value (%#v) in value_options", interfItm)
						}
					}
					castedValue = append(castedValue, castedItm)
				}
			}
			envSerModel.ValueOptions = castedValue
		case "is_required":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsRequired = castedBoolPtr
		case "is_expand":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsExpand = castedBoolPtr
		case "is_sensitive":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsSensitive = castedBoolPtr
		case "is_dont_change_value":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsDontChangeValue = castedBoolPtr
		case "is_template":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.IsTemplate = castedBoolPtr
		case "skip_if_empty":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.SkipIfEmpty = castedBoolPtr
		case "unset":
			castedBoolPtr, ok := parseutil.CastToBoolPtr(value)
			if !ok {
				return fmt.Errorf("failed to parse bool value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.Unset = castedBoolPtr
		case "meta":
			castedMapStringInterface, ok := parseutil.CastToMapStringInterface(value)
			if !ok {
				return fmt.Errorf("failed to parse map[string]interface{} value (%#v) for key (%s)", value, keyStr)
			}
			envSerModel.Meta = castedMapStringInterface
		default:
			// intentional no-op case -- we just ignore unrecognized fields
		}
	}
	return nil
}

// GetOptions ...
func (env EnvironmentItemModel) GetOptions() (EnvironmentItemOptionsModel, error) {
	value, found := env[OptionsKey]
	if !found {
		return EnvironmentItemOptionsModel{}, nil
	}

	envItmCasted, ok := value.(EnvironmentItemOptionsModel)
	if ok {
		return envItmCasted, nil
	}

	// if it's read from a file (YAML/JSON) then it's most likely not the proper type
	//  so cast it from the generic interface-interface map
	normalizedOptsInterfaceMap := make(map[string]interface{})
	isNormalizeOK := false
	if optionsInterfaceMap, ok := value.(map[interface{}]interface{}); ok {
		// Try to normalize every key to String
		for key, value := range optionsInterfaceMap {
			keyStr, ok := key.(string)
			if !ok {
				return EnvironmentItemOptionsModel{}, fmt.Errorf("failed to cask options key (%#v) to string", key)
			}
			normalizedOptsInterfaceMap[keyStr] = value
		}
		isNormalizeOK = true
	} else {
		if castedTmp, ok := value.(map[string]interface{}); ok {
			normalizedOptsInterfaceMap = castedTmp
			isNormalizeOK = true
		}
	}

	if isNormalizeOK {
		options := EnvironmentItemOptionsModel{}
		err := options.ParseFromInterfaceMap(normalizedOptsInterfaceMap)
		if err != nil {
			return EnvironmentItemOptionsModel{}, err
		}

		return options, nil
	}

	return EnvironmentItemOptionsModel{}, fmt.Errorf("failed to cast options value: (%#v)", value)
}

// Normalize ...
func (env *EnvironmentItemModel) Normalize() error {
	opts, err := env.GetOptions()
	if err != nil {
		return err
	}
	(*env)[OptionsKey] = opts
	return nil
}

// Normalize - if successful this makes the model JSON serializable.
// Without this, if the object was created with e.g. a YAML parser,
// the type of `opts` might be map[interface]interface, which is not JSON serializable.
// After this call it's ensured that the type of objects is map[string]interface,
// which is JSON serializable.
func (envsSerializeObj *EnvsSerializeModel) Normalize() error {
	for _, envObj := range envsSerializeObj.Envs {
		if err := envObj.Normalize(); err != nil {
			return err
		}
	}
	return nil
}

// FillMissingDefaults ...
func (env *EnvironmentItemModel) FillMissingDefaults() error {
	options, err := env.GetOptions()
	if err != nil {
		return err
	}
	if options.Title == nil {
		options.Title = pointers.NewStringPtr("")
	}
	if options.Description == nil {
		options.Description = pointers.NewStringPtr("")
	}
	if options.Summary == nil {
		options.Summary = pointers.NewStringPtr("")
	}
	if options.Category == nil {
		options.Category = pointers.NewStringPtr("")
	}
	if options.ValueOptions == nil {
		options.ValueOptions = []string{}
	}
	if options.IsRequired == nil {
		options.IsRequired = pointers.NewBoolPtr(DefaultIsRequired)
	}
	if options.IsExpand == nil {
		options.IsExpand = pointers.NewBoolPtr(DefaultIsExpand)
	}
	if options.IsSensitive == nil {
		options.IsSensitive = pointers.NewBoolPtr(DefaultIsSensitive)
	}
	if options.IsDontChangeValue == nil {
		options.IsDontChangeValue = pointers.NewBoolPtr(DefaultIsDontChangeValue)
	}
	if options.IsTemplate == nil {
		options.IsTemplate = pointers.NewBoolPtr(DefaultIsTemplate)
	}
	if options.SkipIfEmpty == nil {
		options.SkipIfEmpty = pointers.NewBoolPtr(DefaultSkipIfEmpty)
	}
	if options.Meta == nil {
		options.Meta = map[string]interface{}{}
	}
	if options.Unset == nil {
		options.Unset = pointers.NewBoolPtr(DefaultUnset)
	}

	(*env)[OptionsKey] = options
	return nil
}

// Validate ...
func (env EnvironmentItemModel) Validate() error {
	_, _, err := env.GetKeyValuePair()
	if err != nil {
		return err
	}
	_, err = env.GetOptions()
	if err != nil {
		return err
	}
	return nil
}

// NormalizeValidateFillDefaults ...
func (env EnvironmentItemModel) NormalizeValidateFillDefaults() error {
	if err := env.Normalize(); err != nil {
		return err
	}

	if err := env.Validate(); err != nil {
		return err
	}

	return env.FillMissingDefaults()
}
<|endoftext|>


<commit_before>package eureka

import (
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/hudl/fargo"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
)

// Matches official Netflix Java client default.
const defaultRenewalInterval = 30 * time.Second

// The methods of fargo.Connection used in this package.
type fargoConnection interface {
	RegisterInstance(instance *fargo.Instance) error
	DeregisterInstance(instance *fargo.Instance) error
	ReregisterInstance(instance *fargo.Instance) error
	HeartBeatInstance(instance *fargo.Instance) error
	ScheduleAppUpdates(name string, await bool, done <-chan struct{}) <-chan fargo.AppUpdate
	GetApp(name string) (*fargo.Application, error)
}

type fargoUnsuccessfulHTTPResponse struct {
	statusCode    int
	messagePrefix string
}

// Registrar maintains service instance liveness information in Eureka.
type Registrar struct {
	conn     fargoConnection
	instance *fargo.Instance
	logger   log.Logger
	quitc    chan chan struct{}
	sync.Mutex
}

var _ sd.Registrar = (*Registrar)(nil)

// NewRegistrar returns an Eureka Registrar acting on behalf of the provided
// Fargo connection and instance. See the integration test for usage examples.
func NewRegistrar(conn fargoConnection, instance *fargo.Instance, logger log.Logger) *Registrar {
	return &Registrar{
		conn:     conn,
		instance: instance,
		logger:   log.With(logger, "service", instance.App, "address", fmt.Sprintf("%s:%d", instance.IPAddr, instance.Port)),
	}
}

// Register implements sd.Registrar.
func (r *Registrar) Register() {
	r.Lock()
	defer r.Unlock()

	if r.quitc != nil {
		return // Already in the registration loop.
	}

	if err := r.conn.RegisterInstance(r.instance); err != nil {
		r.logger.Log("during", "Register", "err", err)
	}

	r.quitc = make(chan chan struct{})
	go r.loop()
}

// Deregister implements sd.Registrar.
func (r *Registrar) Deregister() {
	r.Lock()
	defer r.Unlock()

	if r.quitc == nil {
		return // Already deregistered.
	}

	q := make(chan struct{})
	r.quitc <- q
	<-q
	r.quitc = nil
}

func (r *Registrar) loop() {
	var renewalInterval time.Duration
	if r.instance.LeaseInfo.RenewalIntervalInSecs > 0 {
		renewalInterval = time.Duration(r.instance.LeaseInfo.RenewalIntervalInSecs) * time.Second
	} else {
		renewalInterval = defaultRenewalInterval
	}
	ticker := time.NewTicker(renewalInterval)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			if err := r.heartbeat(); err != nil {
				r.logger.Log("during", "heartbeat", "err", err)
			}

		case q := <-r.quitc:
			if err := r.conn.DeregisterInstance(r.instance); err != nil {
				r.logger.Log("during", "Deregister", "err", err)
			}
			close(q)
			return
		}
	}
}

func (r *Registrar) heartbeat() error {
	err := r.conn.HeartBeatInstance(r.instance)
	if err != nil {
		if u, ok := err.(*fargoUnsuccessfulHTTPResponse); ok && u.statusCode == http.StatusNotFound {
			// Instance expired (e.g. network partition). Re-register.
			r.logger.Log("during", "heartbeat", err.Error())
			return r.conn.ReregisterInstance(r.instance)
		}
	}
	return err
}

func (u *fargoUnsuccessfulHTTPResponse) Error() string {
	return fmt.Sprintf("err=%s code=%d", u.messagePrefix, u.statusCode)
}
<commit_msg>Detect when a fargo error indicates not found<commit_after>package eureka

import (
	"fmt"
	"net/http"
	"sync"
	"time"

	"github.com/hudl/fargo"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd"
)

// Matches official Netflix Java client default.
const defaultRenewalInterval = 30 * time.Second

// The methods of fargo.Connection used in this package.
type fargoConnection interface {
	RegisterInstance(instance *fargo.Instance) error
	DeregisterInstance(instance *fargo.Instance) error
	ReregisterInstance(instance *fargo.Instance) error
	HeartBeatInstance(instance *fargo.Instance) error
	ScheduleAppUpdates(name string, await bool, done <-chan struct{}) <-chan fargo.AppUpdate
	GetApp(name string) (*fargo.Application, error)
}

type fargoUnsuccessfulHTTPResponse struct {
	statusCode    int
	messagePrefix string
}

func (u *fargoUnsuccessfulHTTPResponse) Error() string {
	return fmt.Sprintf("err=%s code=%d", u.messagePrefix, u.statusCode)
}

// Registrar maintains service instance liveness information in Eureka.
type Registrar struct {
	conn     fargoConnection
	instance *fargo.Instance
	logger   log.Logger
	quitc    chan chan struct{}
	sync.Mutex
}

var _ sd.Registrar = (*Registrar)(nil)

// NewRegistrar returns an Eureka Registrar acting on behalf of the provided
// Fargo connection and instance. See the integration test for usage examples.
func NewRegistrar(conn fargoConnection, instance *fargo.Instance, logger log.Logger) *Registrar {
	return &Registrar{
		conn:     conn,
		instance: instance,
		logger:   log.With(logger, "service", instance.App, "address", fmt.Sprintf("%s:%d", instance.IPAddr, instance.Port)),
	}
}

// Register implements sd.Registrar.
func (r *Registrar) Register() {
	r.Lock()
	defer r.Unlock()

	if r.quitc != nil {
		return // Already in the registration loop.
	}

	if err := r.conn.RegisterInstance(r.instance); err != nil {
		r.logger.Log("during", "Register", "err", err)
	}

	r.quitc = make(chan chan struct{})
	go r.loop()
}

// Deregister implements sd.Registrar.
func (r *Registrar) Deregister() {
	r.Lock()
	defer r.Unlock()

	if r.quitc == nil {
		return // Already deregistered.
	}

	q := make(chan struct{})
	r.quitc <- q
	<-q
	r.quitc = nil
}

func (r *Registrar) loop() {
	var renewalInterval time.Duration
	if r.instance.LeaseInfo.RenewalIntervalInSecs > 0 {
		renewalInterval = time.Duration(r.instance.LeaseInfo.RenewalIntervalInSecs) * time.Second
	} else {
		renewalInterval = defaultRenewalInterval
	}
	ticker := time.NewTicker(renewalInterval)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			if err := r.heartbeat(); err != nil {
				r.logger.Log("during", "heartbeat", "err", err)
			}

		case q := <-r.quitc:
			if err := r.conn.DeregisterInstance(r.instance); err != nil {
				r.logger.Log("during", "Deregister", "err", err)
			}
			close(q)
			return
		}
	}
}

func httpResponseStatusCode(err error) (code int, present bool) {
	if code, ok := fargo.HTTPResponseStatusCode(err); ok {
		return code, true
	}
	// Allow injection of errors for testing.
	if u, ok := err.(*fargoUnsuccessfulHTTPResponse); ok {
		return u.statusCode, true
	}
	return 0, false
}

func isNotFound(err error) bool {
	code, ok := httpResponseStatusCode(err)
	return ok && code == http.StatusNotFound
}

func (r *Registrar) heartbeat() error {
	err := r.conn.HeartBeatInstance(r.instance)
	if err == nil {
		return nil
	}
	if isNotFound(err) {
		// Instance expired (e.g. network partition). Re-register.
		return r.conn.ReregisterInstance(r.instance)
	}
	return err
}
<|endoftext|>


<commit_before>// Package errors provides a way to return detailed information
// for an RPC request error. The error is normally JSON encoded.
package errors

import (
	"encoding/json"
	"fmt"
	"net/http"
)

//go:generate protoc -I. --go_out=paths=source_relative:. errors.proto

func (e *Error) Error() string {
	b, _ := json.Marshal(e)
	return string(b)
}

// New generates a custom error.
func New(id, detail string, code int32) error {
	return &Error{
		Id:     id,
		Code:   code,
		Detail: detail,
		Status: http.StatusText(int(code)),
	}
}

// Parse tries to parse a JSON string into an error. If that
// fails, it will set the given string as the error detail.
func Parse(err string) *Error {
	e := new(Error)
	errr := json.Unmarshal([]byte(err), e)
	if errr != nil {
		e.Detail = err
	}
	return e
}

// BadRequest generates a 400 error.
func BadRequest(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   400,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(400),
	}
}

// Unauthorized generates a 401 error.
func Unauthorized(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   401,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(401),
	}
}

// Forbidden generates a 403 error.
func Forbidden(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   403,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(403),
	}
}

// NotFound generates a 404 error.
func NotFound(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   404,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(404),
	}
}

// MethodNotAllowed generates a 405 error.
func MethodNotAllowed(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   405,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(405),
	}
}

// Timeout generates a 408 error.
func Timeout(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   408,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(408),
	}
}

// Conflict generates a 409 error.
func Conflict(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   409,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(409),
	}
}

// InternalServerError generates a 500 error.
func InternalServerError(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   500,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(500),
	}
}

// Equal tries to compare errors
func Equal(err1 error, err2 error) bool {
	verr1, ok1 := err1.(*Error)
	verr2, ok2 := err2.(*Error)

	if ok1 != ok2 {
		return false
	}

	if !ok1 {
		return err1 == err2
	}

	if verr1.Code != verr2.Code {
		return false
	}

	return true
}

// FromError try to convert go error to *Error
func FromError(err error) *Error {
	if verr, ok := err.(*Error); ok && verr != nil {
		return verr
	}

	return Parse(err.Error())
}
<commit_msg>feat(errors): add gateway, service error (#1797)<commit_after>// Package errors provides a way to return detailed information
// for an RPC request error. The error is normally JSON encoded.
package errors

import (
	"encoding/json"
	"fmt"
	"net/http"
)

//go:generate protoc -I. --go_out=paths=source_relative:. errors.proto

func (e *Error) Error() string {
	b, _ := json.Marshal(e)
	return string(b)
}

// New generates a custom error.
func New(id, detail string, code int32) error {
	return &Error{
		Id:     id,
		Code:   code,
		Detail: detail,
		Status: http.StatusText(int(code)),
	}
}

// Parse tries to parse a JSON string into an error. If that
// fails, it will set the given string as the error detail.
func Parse(err string) *Error {
	e := new(Error)
	errr := json.Unmarshal([]byte(err), e)
	if errr != nil {
		e.Detail = err
	}
	return e
}

// BadRequest generates a 400 error.
func BadRequest(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   400,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(400),
	}
}

// Unauthorized generates a 401 error.
func Unauthorized(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   401,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(401),
	}
}

// Forbidden generates a 403 error.
func Forbidden(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   403,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(403),
	}
}

// NotFound generates a 404 error.
func NotFound(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   404,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(404),
	}
}

// MethodNotAllowed generates a 405 error.
func MethodNotAllowed(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   405,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(405),
	}
}

// Timeout generates a 408 error.
func Timeout(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   408,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(408),
	}
}

// Conflict generates a 409 error.
func Conflict(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   409,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(409),
	}
}

// InternalServerError generates a 500 error.
func InternalServerError(id, format string, a ...interface{}) error {
	return &Error{
		Id:     id,
		Code:   500,
		Detail: fmt.Sprintf(format, a...),
		Status: http.StatusText(500),
	}
}

// NotImplemented generates a 501 error
func NotImplemented(id, format string, a ...interface{}) error {
	return &Error{
		Id:                   id,
		Code:                 501,
		Detail:               fmt.Sprintf(format, a...),
		Status:               http.StatusText(501),
	}
}

// BadGateway generates a 502 error
func BadGateway(id, format string, a ...interface{}) error {
	return &Error{
		Id:                   id,
		Code:                 502,
		Detail:               fmt.Sprintf(format, a...),
		Status:               http.StatusText(502),
	}
}

// ServiceUnavailable generates a 503 error
func ServiceUnavailable(id, format string, a ...interface{}) error {
	return &Error{
		Id:                   id,
		Code:                 503,
		Detail:               fmt.Sprintf(format, a...),
		Status:               http.StatusText(503),
	}
}

// GatewayTimeout generates a 504 error
func GatewayTimeout(id, format string, a ...interface{}) error {
	return &Error{
		Id:                   id,
		Code:                 504,
		Detail:               fmt.Sprintf(format, a...),
		Status:               http.StatusText(504),
	}
}

// Equal tries to compare errors
func Equal(err1 error, err2 error) bool {
	verr1, ok1 := err1.(*Error)
	verr2, ok2 := err2.(*Error)

	if ok1 != ok2 {
		return false
	}

	if !ok1 {
		return err1 == err2
	}

	if verr1.Code != verr2.Code {
		return false
	}

	return true
}

// FromError try to convert go error to *Error
func FromError(err error) *Error {
	if verr, ok := err.(*Error); ok && verr != nil {
		return verr
	}

	return Parse(err.Error())
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"

	"github.com/nsf/termbox-go"
)

type Command struct {
	key         string
	description string
}

type AboutScreen int

func drawCommandsAtPoint(commands []Command, x int, y int, style Style) {
	x_pos, y_pos := x, y
	longest_key_len := 1
	for _, cmd := range commands {
		if len(cmd.key) > longest_key_len {
			longest_key_len = len(cmd.key)
		}
	}
	for index, cmd := range commands {
		drawStringAtPoint(fmt.Sprintf("%[2]*[1]s", cmd.key, longest_key_len), x_pos, y_pos, style.default_fg, style.default_bg)
		drawStringAtPoint(cmd.description, x_pos+longest_key_len+2, y_pos, style.default_fg, style.default_bg)
		y_pos++
		if index > 2 && index%2 == 1 {
			y_pos++
		}
	}
}

func (screen *AboutScreen) receiveEvents(input <-chan termbox.Event, output chan<- int, quit <-chan bool) {
	for {
		do_quit := false
		select {
		case <-input:
			output <- DATA_SCREEN_INDEX
		case <-quit:
			do_quit = true
		}
		if do_quit {
			break
		}
	}
}

func (screen *AboutScreen) performLayout() {
}

func (screen *AboutScreen) drawScreen(style Style) {
	default_fg := style.default_fg
	default_bg := style.default_bg
	width, height := termbox.Size()
	template := [...]string{
		"                              ############################",
		"                              ##The#hex#editor#from#hell##",
		"                              ############################",
		"                                      ####            #   ",
		"#### #### ########  #####      ###    #### ########   #   ",
		"#### #### ####### #########  #######  #### ########  #### ",
		"#### #### ####    #### #### #### #### #### ####     ##x#x ",
		"#### #### ####    ####      #### #### #### ####       #   ",
		"######### ####### ####      ######### #### #######   ###  ",
		"######### ####### ####      ######### #### #######  # # # ",
		"#### #### ####    ####      #### #### #### ####    #  #  #",
		"#### #### ####    ####      #### #### #### ####      # #  ",
		"#### #### ####    #### #### #### #### #### ####     #   # ",
		"#### #### ####### ######### #### #### #### ####### #     #",
		"#### #### ########  #####   #### #### #### ########       ",
	}
	commands1 := [...]Command{
		{"h", "left"},
		{"j", "down"},
		{"k", "up"},
		{"l", "right"},

		{"b", "left 4 bytes"},
		{"w", "right 4 bytes"},

		{"g", "first byte"},
		{"G", "last byte"},

		{":", "jump to byte"},
		{"x", "toggle hex"},

		{"/", "search file"},
		{"n", "next match"},
	}

	commands2 := [...]Command{
		{"t", "text mode"},
		{"p", "bit pattern mode"},
		{"i", "integer mode"},
		{"f", "float mode"},

		{"e", "toggle endianness"},
		{"u", "toggle signedness"},

		{"H", "shrink cursor"},
		{"L", "grow cursor"},

		{"D", "date decoding"},
		{"@", "set date epoch"},

		{"?", "this screen"},
		{"q", "quit program"},
	}

	commands3 := [...]Command{
		{"ctrl-j", "show tabs"},
		{"ctrl-k", "hide tabs"},
		{"ctrl-t", "new tab"},
		{"ctrl-w", "close tab"},

		{"ctrl-h", "previous tab"},
		{"ctrl-l", "next tab"},

		{"ctrl-e", "scroll down"},
		{"ctrl-y", "scroll up"},

		{"ctrl-f", "page down"},
		{"ctrl-b", "page up"},
	}

	first_line := template[0]
	start_x := (width - len(first_line)) / 2
	start_y := (height-len(template)-2-len(commands2)/2*3-1)/2 + 1
	x_pos := start_x
	y_pos := start_y
	for _, line := range template {
		x_pos = start_x
		for _, runeValue := range line {
			bg := default_bg
			displayRune := ' '
			if runeValue != ' ' {
				bg = style.about_logo_bg
				if runeValue != '#' {
					displayRune = runeValue
				}
				termbox.SetCell(x_pos, y_pos, displayRune, default_fg, bg)
			}
			x_pos++
		}
		y_pos++
	}
	x_pos = start_x
	y_pos++

	drawCommandsAtPoint(commands1[:], x_pos, y_pos+1, style)
	drawCommandsAtPoint(commands2[:], x_pos+19, y_pos+1, style)
	drawCommandsAtPoint(commands3[:], x_pos+42, y_pos+1, style)
}
<commit_msg>Tweak command list<commit_after>package main

import (
	"fmt"

	"github.com/nsf/termbox-go"
)

type Command struct {
	key         string
	description string
}

type AboutScreen int

func drawCommandsAtPoint(commands []Command, x int, y int, style Style) {
	x_pos, y_pos := x, y
	longest_key_len := 1
	for _, cmd := range commands {
		if len(cmd.key) > longest_key_len {
			longest_key_len = len(cmd.key)
		}
	}
	for index, cmd := range commands {
		drawStringAtPoint(fmt.Sprintf("%[2]*[1]s", cmd.key, longest_key_len), x_pos, y_pos, style.default_fg, style.default_bg)
		drawStringAtPoint(cmd.description, x_pos+longest_key_len+2, y_pos, style.default_fg, style.default_bg)
		y_pos++
		if index > 2 && index%2 == 1 {
			y_pos++
		}
	}
}

func (screen *AboutScreen) receiveEvents(input <-chan termbox.Event, output chan<- int, quit <-chan bool) {
	for {
		do_quit := false
		select {
		case <-input:
			output <- DATA_SCREEN_INDEX
		case <-quit:
			do_quit = true
		}
		if do_quit {
			break
		}
	}
}

func (screen *AboutScreen) performLayout() {
}

func (screen *AboutScreen) drawScreen(style Style) {
	default_fg := style.default_fg
	default_bg := style.default_bg
	width, height := termbox.Size()
	template := [...]string{
		"                              ############################",
		"                              ##The#hex#editor#from#hell##",
		"                              ############################",
		"                                      ####            #   ",
		"#### #### ########  #####      ###    #### ########   #   ",
		"#### #### ####### #########  #######  #### ########  #### ",
		"#### #### ####    #### #### #### #### #### ####     ##x#x ",
		"#### #### ####    ####      #### #### #### ####       #   ",
		"######### ####### ####      ######### #### #######   ###  ",
		"######### ####### ####      ######### #### #######  # # # ",
		"#### #### ####    ####      #### #### #### ####    #  #  #",
		"#### #### ####    ####      #### #### #### ####      # #  ",
		"#### #### ####    #### #### #### #### #### ####     #   # ",
		"#### #### ####### ######### #### #### #### ####### #     #",
		"#### #### ########  #####   #### #### #### ########       ",
	}
	commands1 := [...]Command{
		{"h", "left"},
		{"j", "down"},
		{"k", "up"},
		{"l", "right"},

		{"b", "left 4 bytes"},
		{"w", "right 4 bytes"},

		{"^", "line start"},
		{"$", "line end"},

		{"g", "file start"},
		{"G", "file end"},

		{":", "jump to byte"},
		{"x", "toggle hex"},
	}

	commands2 := [...]Command{
		{"t", "text mode"},
		{"p", "bit pattern mode"},
		{"i", "integer mode"},
		{"f", "float mode"},

		{"H", "shrink cursor"},
		{"L", "grow cursor"},

		{"e", "toggle endianness"},
		{"u", "toggle signedness"},

		{"D", "date decoding"},
		{"@", "set date epoch"},

		{"/", "search file"},
		{"n", "next match"},
	}

	commands3 := [...]Command{
		{"ctrl-j", "show tabs"},
		{"ctrl-k", "hide tabs"},
		{"ctrl-t", "new tab"},
		{"ctrl-w", "close tab"},

		{"ctrl-h", "previous tab"},
		{"ctrl-l", "next tab"},

		{"ctrl-e", "scroll down"},
		{"ctrl-y", "scroll up"},

		{"ctrl-f", "page down"},
		{"ctrl-b", "page up"},

		{"?", "this screen"},
		{"q", "quit program"},
	}

	first_line := template[0]
	start_x := (width - len(first_line)) / 2
	start_y := (height-len(template)-2-len(commands2)/2*3-1)/2 + 1
	x_pos := start_x
	y_pos := start_y
	for _, line := range template {
		x_pos = start_x
		for _, runeValue := range line {
			bg := default_bg
			displayRune := ' '
			if runeValue != ' ' {
				bg = style.about_logo_bg
				if runeValue != '#' {
					displayRune = runeValue
				}
				termbox.SetCell(x_pos, y_pos, displayRune, default_fg, bg)
			}
			x_pos++
		}
		y_pos++
	}
	x_pos = start_x
	y_pos++

	drawCommandsAtPoint(commands1[:], x_pos, y_pos+1, style)
	drawCommandsAtPoint(commands2[:], x_pos+19, y_pos+1, style)
	drawCommandsAtPoint(commands3[:], x_pos+42, y_pos+1, style)
}
<|endoftext|>


<commit_before>package missinggo

import (
	"fmt"
	"io"
)

type sectionReadSeeker struct {
	base      io.ReadSeeker
	off, size int64
}

// Returns a ReadSeeker on a section of another ReadSeeker.
func NewSectionReadSeeker(base io.ReadSeeker, off, size int64) (ret io.ReadSeeker) {
	ret = &sectionReadSeeker{
		base: base,
		off:  off,
		size: size,
	}
	seekOff, err := ret.Seek(0, io.SeekStart)
	if err != nil {
		panic(err)
	}
	if seekOff != 0 {
		panic(seekOff)
	}
	return
}

func (me *sectionReadSeeker) Seek(off int64, whence int) (ret int64, err error) {
	switch whence {
	case io.SeekStart:
		off += me.off
	case io.SeekCurrent:
	case io.SeekEnd:
		off += me.off + me.size
		whence = io.SeekStart
	default:
		err = fmt.Errorf("unhandled whence: %d", whence)
		return
	}
	ret, err = me.base.Seek(off, whence)
	ret -= me.off
	return
}

func (me *sectionReadSeeker) Read(b []byte) (n int, err error) {
	off, err := me.Seek(0, io.SeekCurrent)
	if err != nil {
		return
	}
	left := me.size - off
	if left <= 0 {
		err = io.EOF
		return
	}
	if int64(len(b)) > left {
		b = b[:left]
	}
	return me.base.Read(b)
}
<commit_msg>Add ReadSeekContexter interface and support ReadContext in SectionReadSeeker<commit_after>package missinggo

import (
	"context"
	"fmt"
	"io"
)

type sectionReadSeeker struct {
	base      io.ReadSeeker
	off, size int64
}

type ReadSeekContexter interface {
	io.ReadSeeker
	ReadContexter
}

// Returns a ReadSeeker on a section of another ReadSeeker.
func NewSectionReadSeeker(base io.ReadSeeker, off, size int64) (ret ReadSeekContexter) {
	ret = &sectionReadSeeker{
		base: base,
		off:  off,
		size: size,
	}
	seekOff, err := ret.Seek(0, io.SeekStart)
	if err != nil {
		panic(err)
	}
	if seekOff != 0 {
		panic(seekOff)
	}
	return
}

func (me *sectionReadSeeker) Seek(off int64, whence int) (ret int64, err error) {
	switch whence {
	case io.SeekStart:
		off += me.off
	case io.SeekCurrent:
	case io.SeekEnd:
		off += me.off + me.size
		whence = io.SeekStart
	default:
		err = fmt.Errorf("unhandled whence: %d", whence)
		return
	}
	ret, err = me.base.Seek(off, whence)
	ret -= me.off
	return
}

func (me *sectionReadSeeker) ReadContext(ctx context.Context, b []byte) (int, error) {
	off, err := me.Seek(0, io.SeekCurrent)
	if err != nil {
		return 0, err
	}
	left := me.size - off
	if left <= 0 {
		return 0, io.EOF
	}
	b = LimitLen(b, left)
	if rc, ok := me.base.(ReadContexter); ok {
		return rc.ReadContext(ctx, b)
	}
	if ctx != context.Background() {
		// Can't handle cancellation.
		panic(ctx)
	}
	return me.base.Read(b)
}

func (me *sectionReadSeeker) Read(b []byte) (int, error) {
	return me.ReadContext(context.Background(), b)
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)

package memfs

import (
	"fmt"
	"os"
	"time"

	"github.com/jacobsa/fuse"
	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcloud/syncutil"
	"github.com/jacobsa/gcsfuse/timeutil"
	"golang.org/x/net/context"
)

type memFS struct {
	fuseutil.NotImplementedFileSystem

	/////////////////////////
	// Dependencies
	/////////////////////////

	clock timeutil.Clock

	/////////////////////////
	// Mutable state
	/////////////////////////

	// When acquiring this lock, the caller must hold no inode locks.
	mu syncutil.InvariantMutex

	// The collection of live inodes, indexed by ID. IDs of free inodes that may
	// be re-used have nil entries. No ID less than fuse.RootInodeID is ever used.
	//
	// INVARIANT: len(inodes) > fuse.RootInodeID
	// INVARIANT: For all i < fuse.RootInodeID, inodes[i] == nil
	// INVARIANT: inodes[fuse.RootInodeID] != nil
	// INVARIANT: inodes[fuse.RootInodeID].dir is true
	inodes []*inode // GUARDED_BY(mu)

	// A list of inode IDs within inodes available for reuse, not including the
	// reserved IDs less than fuse.RootInodeID.
	//
	// INVARIANT: This is all and only indices i of 'inodes' such that i >
	// fuse.RootInodeID and inodes[i] == nil
	freeInodes []fuse.InodeID // GUARDED_BY(mu)
}

// Create a file system that stores data and metadata in memory.
func NewMemFS(
	clock timeutil.Clock) fuse.FileSystem {
	// Set up the basic struct.
	fs := &memFS{
		clock:  clock,
		inodes: make([]*inode, fuse.RootInodeID+1),
	}

	// Set up the root inode.
	fs.inodes[fuse.RootInodeID] = newInode(0777 | os.ModeDir)

	// Set up invariant checking.
	fs.mu = syncutil.NewInvariantMutex(fs.checkInvariants)

	return fs
}

func (fs *memFS) checkInvariants() {
	// Check reserved inodes.
	for i := 0; i < fuse.RootInodeID; i++ {
		if fs.inodes[i] != nil {
			panic(fmt.Sprintf("Non-nil inode for ID: %v", i))
		}
	}

	// Check the root inode.
	if !fs.inodes[fuse.RootInodeID].dir {
		panic("Expected root to be a directory.")
	}

	// Build our own list of free IDs.
	freeIDsEncountered := make(map[fuse.InodeID]struct{})
	for i := fuse.RootInodeID + 1; i < len(fs.inodes); i++ {
		inode := fs.inodes[i]
		if inode == nil {
			freeIDsEncountered[fuse.InodeID(i)] = struct{}{}
			continue
		}
	}

	// Check fs.freeInodes.
	if len(fs.freeInodes) != len(freeIDsEncountered) {
		panic(
			fmt.Sprintf(
				"Length mismatch: %v vs. %v",
				len(fs.freeInodes),
				len(freeIDsEncountered)))
	}

	for _, id := range fs.freeInodes {
		if _, ok := freeIDsEncountered[id]; !ok {
			panic(fmt.Sprintf("Unexected free inode ID: %v", id))
		}
	}
}

func (fs *memFS) Init(
	ctx context.Context,
	req *fuse.InitRequest) (resp *fuse.InitResponse, err error) {
	resp = &fuse.InitResponse{}
	return
}

// Find the supplied inode and return it with its lock held for reading. Panic
// if it doesn't exist.
//
// SHARED_LOCKS_REQUIRED(fs.mu)
// SHARED_LOCK_FUNCTION(inode.mu)
func (fs *memFS) getInodeForReadingOrDie(id fuse.InodeID) (inode *inode) {
	inode = fs.inodes[id]
	if inode == nil {
		panic(fmt.Sprintf("Unknown inode: %v", id))
	}

	inode.mu.RLock()
	return
}

func (fs *memFS) LookUpInode(
	ctx context.Context,
	req *fuse.LookUpInodeRequest) (resp *fuse.LookUpInodeResponse, err error) {
	resp = &fuse.LookUpInodeResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// Grab the parent directory.
	inode := fs.getInodeForReadingOrDie(req.Parent)
	defer inode.mu.RUnlock()

	// Does the directory have an entry with the given name?
	childID, ok := inode.LookUpChild(req.Name)
	if !ok {
		err = fuse.ENOENT
		return
	}

	// Grab the child.
	child := fs.getInodeForReadingOrDie(childID)
	defer child.mu.RUnlock()

	// Fill in the response.
	resp.Entry.Attributes = child.attributes

	// We don't spontaneously mutate, so the kernel can cache as long as it wants
	// (since it also handles invalidation).
	resp.Entry.AttributesExpiration = fs.clock.Now().Add(365 * 24 * time.Hour)
	resp.Entry.EntryExpiration = resp.Entry.EntryExpiration

	return
}

func (fs *memFS) GetInodeAttributes(
	ctx context.Context,
	req *fuse.GetInodeAttributesRequest) (
	resp *fuse.GetInodeAttributesResponse, err error) {
	resp = &fuse.GetInodeAttributesResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// Grab the inode.
	inode := fs.getInodeForReadingOrDie(req.Inode)
	defer inode.mu.RUnlock()

	// Fill in the response.
	resp.Attributes = inode.attributes

	// We don't spontaneously mutate, so the kernel can cache as long as it wants
	// (since it also handles invalidation).
	resp.AttributesExpiration = fs.clock.Now().Add(365 * 24 * time.Hour)

	return
}

func (fs *memFS) OpenDir(
	ctx context.Context,
	req *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {
	resp = &fuse.OpenDirResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// We don't mutate spontaneosuly, so if the VFS layer has asked for an
	// inode that doesn't exist, something screwed up earlier (a lookup, a
	// cache invalidation, etc.).
	inode := fs.getInodeForReadingOrDie(req.Inode)
	defer inode.mu.RUnlock()

	if !inode.dir {
		panic("Found non-dir.")
	}

	return
}

func (fs *memFS) ReadDir(
	ctx context.Context,
	req *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {
	resp = &fuse.ReadDirResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// Grab the directory.
	inode := fs.getInodeForReadingOrDie(req.Inode)
	defer inode.mu.RUnlock()

	// Serve the request.
	resp.Data, err = inode.ReadDir(int(req.Offset), req.Size)
	if err != nil {
		err = fmt.Errorf("inode.ReadDir: %v", err)
		return
	}

	return
}
<commit_msg>Began on memFS.MkDir.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
// Author: jacobsa@google.com (Aaron Jacobs)

package memfs

import (
	"fmt"
	"os"
	"time"

	"github.com/jacobsa/fuse"
	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcloud/syncutil"
	"github.com/jacobsa/gcsfuse/timeutil"
	"golang.org/x/net/context"
)

type memFS struct {
	fuseutil.NotImplementedFileSystem

	/////////////////////////
	// Dependencies
	/////////////////////////

	clock timeutil.Clock

	/////////////////////////
	// Mutable state
	/////////////////////////

	// When acquiring this lock, the caller must hold no inode locks.
	mu syncutil.InvariantMutex

	// The collection of live inodes, indexed by ID. IDs of free inodes that may
	// be re-used have nil entries. No ID less than fuse.RootInodeID is ever used.
	//
	// INVARIANT: len(inodes) > fuse.RootInodeID
	// INVARIANT: For all i < fuse.RootInodeID, inodes[i] == nil
	// INVARIANT: inodes[fuse.RootInodeID] != nil
	// INVARIANT: inodes[fuse.RootInodeID].dir is true
	inodes []*inode // GUARDED_BY(mu)

	// A list of inode IDs within inodes available for reuse, not including the
	// reserved IDs less than fuse.RootInodeID.
	//
	// INVARIANT: This is all and only indices i of 'inodes' such that i >
	// fuse.RootInodeID and inodes[i] == nil
	freeInodes []fuse.InodeID // GUARDED_BY(mu)
}

// Create a file system that stores data and metadata in memory.
func NewMemFS(
	clock timeutil.Clock) fuse.FileSystem {
	// Set up the basic struct.
	fs := &memFS{
		clock:  clock,
		inodes: make([]*inode, fuse.RootInodeID+1),
	}

	// Set up the root inode.
	fs.inodes[fuse.RootInodeID] = newInode(0777 | os.ModeDir)

	// Set up invariant checking.
	fs.mu = syncutil.NewInvariantMutex(fs.checkInvariants)

	return fs
}

func (fs *memFS) checkInvariants() {
	// Check reserved inodes.
	for i := 0; i < fuse.RootInodeID; i++ {
		if fs.inodes[i] != nil {
			panic(fmt.Sprintf("Non-nil inode for ID: %v", i))
		}
	}

	// Check the root inode.
	if !fs.inodes[fuse.RootInodeID].dir {
		panic("Expected root to be a directory.")
	}

	// Build our own list of free IDs.
	freeIDsEncountered := make(map[fuse.InodeID]struct{})
	for i := fuse.RootInodeID + 1; i < len(fs.inodes); i++ {
		inode := fs.inodes[i]
		if inode == nil {
			freeIDsEncountered[fuse.InodeID(i)] = struct{}{}
			continue
		}
	}

	// Check fs.freeInodes.
	if len(fs.freeInodes) != len(freeIDsEncountered) {
		panic(
			fmt.Sprintf(
				"Length mismatch: %v vs. %v",
				len(fs.freeInodes),
				len(freeIDsEncountered)))
	}

	for _, id := range fs.freeInodes {
		if _, ok := freeIDsEncountered[id]; !ok {
			panic(fmt.Sprintf("Unexected free inode ID: %v", id))
		}
	}
}

func (fs *memFS) Init(
	ctx context.Context,
	req *fuse.InitRequest) (resp *fuse.InitResponse, err error) {
	resp = &fuse.InitResponse{}
	return
}

// Find the supplied inode and return it with its lock held for reading. Panic
// if it doesn't exist.
//
// SHARED_LOCKS_REQUIRED(fs.mu)
// SHARED_LOCK_FUNCTION(inode.mu)
func (fs *memFS) getInodeForReadingOrDie(id fuse.InodeID) (inode *inode) {
	inode = fs.inodes[id]
	if inode == nil {
		panic(fmt.Sprintf("Unknown inode: %v", id))
	}

	inode.mu.RLock()
	return
}

func (fs *memFS) LookUpInode(
	ctx context.Context,
	req *fuse.LookUpInodeRequest) (resp *fuse.LookUpInodeResponse, err error) {
	resp = &fuse.LookUpInodeResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// Grab the parent directory.
	inode := fs.getInodeForReadingOrDie(req.Parent)
	defer inode.mu.RUnlock()

	// Does the directory have an entry with the given name?
	childID, ok := inode.LookUpChild(req.Name)
	if !ok {
		err = fuse.ENOENT
		return
	}

	// Grab the child.
	child := fs.getInodeForReadingOrDie(childID)
	defer child.mu.RUnlock()

	// Fill in the response.
	resp.Entry.Attributes = child.attributes

	// We don't spontaneously mutate, so the kernel can cache as long as it wants
	// (since it also handles invalidation).
	resp.Entry.AttributesExpiration = fs.clock.Now().Add(365 * 24 * time.Hour)
	resp.Entry.EntryExpiration = resp.Entry.EntryExpiration

	return
}

func (fs *memFS) GetInodeAttributes(
	ctx context.Context,
	req *fuse.GetInodeAttributesRequest) (
	resp *fuse.GetInodeAttributesResponse, err error) {
	resp = &fuse.GetInodeAttributesResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// Grab the inode.
	inode := fs.getInodeForReadingOrDie(req.Inode)
	defer inode.mu.RUnlock()

	// Fill in the response.
	resp.Attributes = inode.attributes

	// We don't spontaneously mutate, so the kernel can cache as long as it wants
	// (since it also handles invalidation).
	resp.AttributesExpiration = fs.clock.Now().Add(365 * 24 * time.Hour)

	return
}

func (fs *memFS) MkDir(
	ctx context.Context,
	req *fuse.MkDirRequest) (resp *fuse.MkDirResponse, err error) {
	resp = &fuse.MkDirResponse{}

	fs.mu.Lock()
	defer fs.mu.Unlock()

	panic("TODO")
}

func (fs *memFS) OpenDir(
	ctx context.Context,
	req *fuse.OpenDirRequest) (resp *fuse.OpenDirResponse, err error) {
	resp = &fuse.OpenDirResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// We don't mutate spontaneosuly, so if the VFS layer has asked for an
	// inode that doesn't exist, something screwed up earlier (a lookup, a
	// cache invalidation, etc.).
	inode := fs.getInodeForReadingOrDie(req.Inode)
	defer inode.mu.RUnlock()

	if !inode.dir {
		panic("Found non-dir.")
	}

	return
}

func (fs *memFS) ReadDir(
	ctx context.Context,
	req *fuse.ReadDirRequest) (resp *fuse.ReadDirResponse, err error) {
	resp = &fuse.ReadDirResponse{}

	fs.mu.RLock()
	defer fs.mu.RUnlock()

	// Grab the directory.
	inode := fs.getInodeForReadingOrDie(req.Inode)
	defer inode.mu.RUnlock()

	// Serve the request.
	resp.Data, err = inode.ReadDir(int(req.Offset), req.Size)
	if err != nil {
		err = fmt.Errorf("inode.ReadDir: %v", err)
		return
	}

	return
}
<|endoftext|>


<commit_before>package missinggo

import (
	"fmt"
	"io"
	"os"
)

type sectionReadSeeker struct {
	base      io.ReadSeeker
	off, size int64
}

func NewSectionReadSeeker(base io.ReadSeeker, off, size int64) (ret io.ReadSeeker) {
	ret = &sectionReadSeeker{
		base: base,
		off:  off,
		size: size,
	}
	seekOff, err := ret.Seek(0, os.SEEK_SET)
	if err != nil {
		panic(err)
	}
	if seekOff != 0 {
		panic(seekOff)
	}
	return
}

func (me *sectionReadSeeker) Seek(off int64, whence int) (ret int64, err error) {
	switch whence {
	case os.SEEK_SET:
		off += me.off
	case os.SEEK_CUR:
	case os.SEEK_END:
		off += me.off + me.size
		whence = os.SEEK_SET
	default:
		err = fmt.Errorf("unhandled whence: %d", whence)
		return
	}
	ret, err = me.base.Seek(off, whence)
	ret -= me.off
	return
}

func (me *sectionReadSeeker) Read(b []byte) (n int, err error) {
	off, err := me.Seek(0, os.SEEK_CUR)
	if err != nil {
		return
	}
	left := me.off + me.size - off
	if left <= 0 {
		err = io.EOF
		return
	}
	if int64(len(b)) > left {
		b = b[:left]
	}
	return me.base.Read(b)
}
<commit_msg>SectionReadSeeker: would read past end of section if section offset > 0<commit_after>package missinggo

import (
	"fmt"
	"io"
	"os"
)

type sectionReadSeeker struct {
	base      io.ReadSeeker
	off, size int64
}

func NewSectionReadSeeker(base io.ReadSeeker, off, size int64) (ret io.ReadSeeker) {
	ret = &sectionReadSeeker{
		base: base,
		off:  off,
		size: size,
	}
	seekOff, err := ret.Seek(0, os.SEEK_SET)
	if err != nil {
		panic(err)
	}
	if seekOff != 0 {
		panic(seekOff)
	}
	return
}

func (me *sectionReadSeeker) Seek(off int64, whence int) (ret int64, err error) {
	switch whence {
	case os.SEEK_SET:
		off += me.off
	case os.SEEK_CUR:
	case os.SEEK_END:
		off += me.off + me.size
		whence = os.SEEK_SET
	default:
		err = fmt.Errorf("unhandled whence: %d", whence)
		return
	}
	ret, err = me.base.Seek(off, whence)
	ret -= me.off
	return
}

func (me *sectionReadSeeker) Read(b []byte) (n int, err error) {
	off, err := me.Seek(0, os.SEEK_CUR)
	if err != nil {
		return
	}
	left := me.size - off
	if left <= 0 {
		err = io.EOF
		return
	}
	if int64(len(b)) > left {
		b = b[:left]
	}
	return me.base.Read(b)
}
<|endoftext|>


<commit_before>package numbers

import (
	"errors"
	"reflect"
	"testing"
)

// TestFactorsList unit test FactorsList function.
func TestFactorsList(t *testing.T) {
	testCases := []struct {
		input    int
		expected []int
		err      error
	}{
		{2, []int{2}, nil},
		{15, []int{3, 5}, nil},
		{26, []int{2, 13}, nil},
		{37, []int{37}, nil},
		{42, []int{2, 3, 7}, nil},
		{-1, []int(nil), errors.New("no prime factors for numbers below two. received '-1'")},
	}
	for _, test := range testCases {
		observed, err := FactorsList(test.input)
		if err != nil {
			if test.err.Error() != err.Error() {
				t.Error(err)
			}
		}
		if !reflect.DeepEqual(observed, test.expected) {
			t.Errorf("for input '%d', expected '%v', got '%v'",
				test.input, test.expected, observed)
		}
	}
}

// BenchmarkFactorList benchmark FactorsList function.
func BenchmarkFactorList(b *testing.B) {
	for i := 0; i <= b.N; i++ {
		_, err := FactorsList(1000)
		if err != nil {
			b.Error(err)
		}
	}
}

// TestIsPrime unit test IsPrime function.
func TestIsPrime(t *testing.T) {
	testCases := []struct {
		input    int
		expected bool
	}{
		{-5, false},
		{0, false},
		{2, true},
		{6, false},
		{13, true},
	}
	for _, test := range testCases {
		observed := IsPrime(test.input)
		if observed != test.expected {
			t.Errorf("for input '%d', expected '%t', got '%t'",
				test.input, test.expected, observed)
		}
	}
}

// BenchmarkIsPrime benchmark IsPrime function.
func BenchmarkIsPrime(b *testing.B) {
	for i := 0; i <= b.N; i++ {
		_ = IsPrime(1728459)
	}
}

// TestFibonacciGen unit test FibonacciGen function.
func TestFibonacciGen(t *testing.T) {
	testCases := []struct {
		input, expected int
	}{
		{1, 0},
		{2, 1},
		{3, 1},
		{4, 2},
		{5, 3},
		{8, 13},
		{10, 34},
		{12, 89},
	}
	for _, test := range testCases {
		var observed int
		c := FibonacciGen()
		for n := 0; n < test.input; n++ {
			observed = <-c
		}
		if observed != test.expected {
			t.Errorf("for input '%d', expected '%d', got '%d'", test.input, test.expected, observed)
		}
	}
}
<commit_msg>Add benchmark test for FibonacciGen function<commit_after>package numbers

import (
	"errors"
	"reflect"
	"testing"
)

// TestFactorsList unit test FactorsList function.
func TestFactorsList(t *testing.T) {
	testCases := []struct {
		input    int
		expected []int
		err      error
	}{
		{2, []int{2}, nil},
		{15, []int{3, 5}, nil},
		{26, []int{2, 13}, nil},
		{37, []int{37}, nil},
		{42, []int{2, 3, 7}, nil},
		{-1, []int(nil), errors.New("no prime factors for numbers below two. received '-1'")},
	}
	for _, test := range testCases {
		observed, err := FactorsList(test.input)
		if err != nil {
			if test.err.Error() != err.Error() {
				t.Error(err)
			}
		}
		if !reflect.DeepEqual(observed, test.expected) {
			t.Errorf("for input '%d', expected '%v', got '%v'",
				test.input, test.expected, observed)
		}
	}
}

// BenchmarkFactorList benchmark FactorsList function.
func BenchmarkFactorList(b *testing.B) {
	for i := 0; i <= b.N; i++ {
		_, err := FactorsList(1000)
		if err != nil {
			b.Error(err)
		}
	}
}

// TestIsPrime unit test IsPrime function.
func TestIsPrime(t *testing.T) {
	testCases := []struct {
		input    int
		expected bool
	}{
		{-5, false},
		{0, false},
		{2, true},
		{6, false},
		{13, true},
	}
	for _, test := range testCases {
		observed := IsPrime(test.input)
		if observed != test.expected {
			t.Errorf("for input '%d', expected '%t', got '%t'",
				test.input, test.expected, observed)
		}
	}
}

// BenchmarkIsPrime benchmark IsPrime function.
func BenchmarkIsPrime(b *testing.B) {
	for i := 0; i <= b.N; i++ {
		_ = IsPrime(1728459)
	}
}

// TestFibonacciGen unit test FibonacciGen function.
func TestFibonacciGen(t *testing.T) {
	testCases := []struct {
		input, expected int
	}{
		{1, 0},
		{2, 1},
		{3, 1},
		{4, 2},
		{5, 3},
		{8, 13},
		{10, 34},
		{12, 89},
	}
	for _, test := range testCases {
		var observed int
		c := FibonacciGen()
		for n := 0; n < test.input; n++ {
			observed = <-c
		}
		if observed != test.expected {
			t.Errorf("for input '%d', expected '%d', got '%d'", test.input, test.expected, observed)
		}
	}
}

// BenchmarkFibonacciGen benchmark FibonacciGen function.
func BenchmarkFibonacciGen(b *testing.B) {
	for i := 0; i <= b.N; i++ {
		c := FibonacciGen()
		for n := 0; n < 10000; n++ {
			_ = <-c
		}
	}
}
<|endoftext|>


<commit_before>package dbr

import (
	"database/sql"
)

type Eq map[string]interface{}

type Connection struct {
	Db *sql.DB
	EventReceiver
}

type Session struct {
	cxn *Connection
	EventReceiver
}

type SessionRunner interface {
	Select(cols ...string) *SelectBuilder
	SelectBySql(sql string, args ...interface{}) *SelectBuilder

	InsertInto(into string) *InsertBuilder
	Update(table string) *UpdateBuilder
	DeleteFrom(from string) *DeleteBuilder
}

type runner interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

func NewConnection(db *sql.DB, log EventReceiver) *Connection {
	if log == nil {
		log = nullReceiver
	}

	return &Connection{Db: db, EventReceiver: log}
}

func (cxn *Connection) NewSession(log EventReceiver) *Session {
	if log == nil {
		log = cxn.EventReceiver // Use parent instrumentation
	}
	return &Session{cxn: cxn, EventReceiver: log}
}
<commit_msg>WIP for user story testing<commit_after>package dbr

import (
	"database/sql"
)

type Eq map[string]interface{}

type Connection struct {
	Db *sql.DB
	EventReceiver
}

type Session struct {
	cxn *Connection
	EventReceiver
}

// A SessionRunner can do anything that a Session can except start a transaction.
type SessionRunner interface {
	Select(cols ...string) *SelectBuilder
	SelectBySql(sql string, args ...interface{}) *SelectBuilder

	InsertInto(into string) *InsertBuilder
	Update(table string) *UpdateBuilder
	DeleteFrom(from string) *DeleteBuilder
}

type runner interface {
	Exec(query string, args ...interface{}) (sql.Result, error)
	Query(query string, args ...interface{}) (*sql.Rows, error)
}

func NewConnection(db *sql.DB, log EventReceiver) *Connection {
	if log == nil {
		log = nullReceiver
	}

	return &Connection{Db: db, EventReceiver: log}
}

func (cxn *Connection) NewSession(log EventReceiver) *Session {
	if log == nil {
		log = cxn.EventReceiver // Use parent instrumentation
	}
	return &Session{cxn: cxn, EventReceiver: log}
}
<|endoftext|>


<commit_before>package dmm

import (
	"github.com/DMMcomLabo/dmm-go-sdk/api"
)

// Client for DMM services
//
// DMMサービス接続のためのClient
type Client struct {
	AffiliateID string
	ApiID       string

	// services
	Actress *api.ActressService
	Author  *api.AuthorService
	Floor   *api.FloorService
	Genre   *api.GenreService
	Maker   *api.MakerService
	Product *api.ProductService
	Series  *api.SeriesService
}

// New creates client
//
// Clientの新規作成
func New(affiliateID, apiID string) *Client {
	c := &Client{
		ApiID:       apiID,
		AffiliateID: affiliateID,
	}
	c.Actress = api.NewActressService(affiliateID, apiID)
	c.Author = api.NewAuthorService(affiliateID, apiID)
	c.Floor = api.NewFloorService(affiliateID, apiID)
	c.Genre = api.NewGenreService(affiliateID, apiID)
	c.Maker = api.NewMakerService(affiliateID, apiID)
	c.Product = api.NewProductService(affiliateID, apiID)
	c.Series = api.NewSeriesService(affiliateID, apiID)
	return c
}
<commit_msg>fix import due to change organaization name<commit_after>package dmm

import (
	"github.com/dmmlabo/dmm-go-sdk/api"
)

// Client for DMM services
//
// DMMサービス接続のためのClient
type Client struct {
	AffiliateID string
	ApiID       string

	// services
	Actress *api.ActressService
	Author  *api.AuthorService
	Floor   *api.FloorService
	Genre   *api.GenreService
	Maker   *api.MakerService
	Product *api.ProductService
	Series  *api.SeriesService
}

// New creates client
//
// Clientの新規作成
func New(affiliateID, apiID string) *Client {
	c := &Client{
		ApiID:       apiID,
		AffiliateID: affiliateID,
	}
	c.Actress = api.NewActressService(affiliateID, apiID)
	c.Author = api.NewAuthorService(affiliateID, apiID)
	c.Floor = api.NewFloorService(affiliateID, apiID)
	c.Genre = api.NewGenreService(affiliateID, apiID)
	c.Maker = api.NewMakerService(affiliateID, apiID)
	c.Product = api.NewProductService(affiliateID, apiID)
	c.Series = api.NewSeriesService(affiliateID, apiID)
	return c
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/abh/dns"
	"log"
	"net"
)

func setupSOA() *dns.SOA {

	s := *flagdomain + ". 3600 IN SOA " +
		primaryNsList[0] + " hostmaster " +
		"1 5400 5400 2419200 300"

	rr, err := dns.NewRR(s)

	if err != nil {
		log.Println("SOA Error", err)
		panic("Could not setup SOA")
	}

	return rr.(*dns.SOA)
}

func setupNS() []dns.RR {

	nsList := make([]dns.RR, 0)

	for _, ns := range primaryNsList {
		s := *flagdomain + ". 20800 IN NS " + ns + "."

		rr, err := dns.NewRR(s)

		if err != nil {
			log.Println("NS Error", err)
			panic("Could not setup NS")
		}
		nsList = append(nsList, rr)
	}

	return nsList
}

func getEdnsSubNet(req *dns.Msg) (ip string, rr *dns.OPT, edns *dns.EDNS0_SUBNET) {

	for _, extra := range req.Extra {
		// log.Println("Extra:", extra)
		for _, o := range extra.(*dns.OPT).Option {
			// opt_rr = extra.(*dns.OPT)
			switch e := o.(type) {
			case *dns.EDNS0_NSID:
				// do stuff with e.Nsid
			case *dns.EDNS0_SUBNET:
				// log.Println("Got edns", e.Address, e.Family, e.SourceNetmask, e.SourceScope)
				if e.Address != nil {
					edns = e
					rr = extra.(*dns.OPT)
					ip = e.Address.String()
				}
			}
		}
	}
	return
}

func setupServerFunc() func(dns.ResponseWriter, *dns.Msg) {

	soa := setupSOA()
	ns := setupNS()

	h := &dns.RR_Header{Ttl: 10, Class: dns.ClassINET, Rrtype: dns.TypeA}
	a := &dns.A{Hdr: *h, A: net.ParseIP(*flagip)}

	return func(w dns.ResponseWriter, req *dns.Msg) {

		m := new(dns.Msg)
		m.SetReply(req)
		if e := m.IsEdns0(); e != nil {
			m.SetEdns0(4096, e.Do())
		}
		m.Authoritative = true

		uuid := getUuidFromDomain(req.Question[0].Name)

		qtype := req.Question[0].Qtype

		if qtype == dns.TypeNS && len(uuid) == 0 {
			m.Answer = ns
			w.WriteMsg(m)
			return
		}

		// we only know how to do A records
		if qtype != dns.TypeA {
			m.Ns = []dns.RR{soa}
			w.WriteMsg(m)
			return
		}

		log.Println("uuid", uuid)

		if len(uuid) > 0 {

			ednsIP, extraRr, edns := getEdnsSubNet(req)
			ip, _, _ := net.SplitHostPort(w.RemoteAddr().String())

			log.Println("Setting answer for ip:", ip)
			a.Header().Name = req.Question[0].Name
			m.Answer = []dns.RR{a}

			Redis.SetEx("dns-"+uuid, 10, ip)
			if len(ednsIP) > 0 {
				Redis.SetEx("dnsedns-"+uuid, 10, ednsIP)

				if edns != nil {
					// log.Println("family", edns.Family)
					if edns.Family != 0 {
						edns.SourceScope = 24
						m.Extra = append(m.Extra, extraRr)
					}
				}

			}
		} else {
			// NOERROR
			w.WriteMsg(m)
			return
		}

		if len(m.Answer) == 0 {
			// return NXDOMAIN
			m.SetRcode(req, dns.RcodeNameError)
			m.Authoritative = true
			m.Ns = []dns.RR{soa}
		}

		log.Println("Returning", m)

		w.WriteMsg(m)
		return
	}

}

func listenAndServeDNS(ip string) {

	prots := []string{"udp", "tcp"}

	for _, prot := range prots {
		go func(p string) {
			server := &dns.Server{Addr: ip, Net: p}

			log.Printf("Opening on %s %s", ip, p)
			if err := server.ListenAndServe(); err != nil {
				log.Fatalf("geodns: failed to setup %s %s: %s", ip, p, err)
			}
			log.Fatalf("geodns: ListenAndServe unexpectedly returned")
		}(prot)
	}

}
<commit_msg>Report EDNS-SUBNET with netmask<commit_after>package main

import (
	"fmt"
	"github.com/abh/dns"
	"log"
	"net"
)

func setupSOA() *dns.SOA {

	s := *flagdomain + ". 3600 IN SOA " +
		primaryNsList[0] + " hostmaster " +
		"1 5400 5400 2419200 300"

	rr, err := dns.NewRR(s)

	if err != nil {
		log.Println("SOA Error", err)
		panic("Could not setup SOA")
	}

	return rr.(*dns.SOA)
}

func setupNS() []dns.RR {

	nsList := make([]dns.RR, 0)

	for _, ns := range primaryNsList {
		s := *flagdomain + ". 20800 IN NS " + ns + "."

		rr, err := dns.NewRR(s)

		if err != nil {
			log.Println("NS Error", err)
			panic("Could not setup NS")
		}
		nsList = append(nsList, rr)
	}

	return nsList
}

func getEdnsSubNet(req *dns.Msg) (enum string, rr *dns.OPT, edns *dns.EDNS0_SUBNET) {

	for _, extra := range req.Extra {
		// log.Println("Extra:", extra)
		for _, o := range extra.(*dns.OPT).Option {
			// opt_rr = extra.(*dns.OPT)
			switch e := o.(type) {
			case *dns.EDNS0_NSID:
				// do stuff with e.Nsid
			case *dns.EDNS0_SUBNET:
				// log.Println("Got edns", e.Address, e.Family, e.SourceNetmask, e.SourceScope)
				if e.Address != nil {
					edns = e
					rr = extra.(*dns.OPT)
					enum = fmt.Sprintf("%s/%d", e.Address.String(), e.SourceNetmask)
				}
			}
		}
	}
	return
}

func setupServerFunc() func(dns.ResponseWriter, *dns.Msg) {

	soa := setupSOA()
	ns := setupNS()

	h := &dns.RR_Header{Ttl: 10, Class: dns.ClassINET, Rrtype: dns.TypeA}
	a := &dns.A{Hdr: *h, A: net.ParseIP(*flagip)}

	return func(w dns.ResponseWriter, req *dns.Msg) {

		m := new(dns.Msg)
		m.SetReply(req)
		if e := m.IsEdns0(); e != nil {
			m.SetEdns0(4096, e.Do())
		}
		m.Authoritative = true

		uuid := getUuidFromDomain(req.Question[0].Name)

		qtype := req.Question[0].Qtype

		if qtype == dns.TypeNS && len(uuid) == 0 {
			m.Answer = ns
			w.WriteMsg(m)
			return
		}

		// we only know how to do A records
		if qtype != dns.TypeA {
			m.Ns = []dns.RR{soa}
			w.WriteMsg(m)
			return
		}

		log.Println("uuid", uuid)

		if len(uuid) > 0 {

			ednsIP, extraRr, edns := getEdnsSubNet(req)
			ip, _, _ := net.SplitHostPort(w.RemoteAddr().String())

			log.Println("Setting answer for ip:", ip)
			a.Header().Name = req.Question[0].Name
			m.Answer = []dns.RR{a}

			Redis.SetEx("dns-"+uuid, 10, ip)
			if len(ednsIP) > 0 {
				Redis.SetEx("dnsedns-"+uuid, 10, ednsIP)

				if edns != nil {
					// log.Println("family", edns.Family)
					if edns.Family != 0 {
						edns.SourceScope = 24
						m.Extra = append(m.Extra, extraRr)
					}
				}

			}
		} else {
			// NOERROR
			w.WriteMsg(m)
			return
		}

		if len(m.Answer) == 0 {
			// return NXDOMAIN
			m.SetRcode(req, dns.RcodeNameError)
			m.Authoritative = true
			m.Ns = []dns.RR{soa}
		}

		log.Println("Returning", m)

		w.WriteMsg(m)
		return
	}

}

func listenAndServeDNS(ip string) {

	prots := []string{"udp", "tcp"}

	for _, prot := range prots {
		go func(p string) {
			server := &dns.Server{Addr: ip, Net: p}

			log.Printf("Opening on %s %s", ip, p)
			if err := server.ListenAndServe(); err != nil {
				log.Fatalf("geodns: failed to setup %s %s: %s", ip, p, err)
			}
			log.Fatalf("geodns: ListenAndServe unexpectedly returned")
		}(prot)
	}

}
<|endoftext|>


<commit_before>/*
Shrike

Simple memory based key value store goshire service. Shrike uses the STREST protocal and by default
is configured to enable http, json and binary listeners.

Persistance:

Shrike is primarily an in memory store but by setting a data_dir value in your config file, Shrike
will dump all data on interupt or sigterm to a backup file which it will load back in next time you
start it.

Install:

go get github.com/pmylund/go-cache
go get github.com/trendrr/goshire
go get github.com/mdennebaum/shrike

Checkout or download shrike to a directory in your gopath.

Config:

Edit the config.yaml file to match with your settings.

Run:

Once you've edited the config.yaml to your liking run the following.

go run main.go -config=/path/to/config.yaml

Alternatively if your config folder is located in the same dir as the executable you can omit the
-config flag

go run main.go

Then you should be able to point your browser at http://localhost:8010/ping to make sure its working

Client:
Goshire comes with a bundled client that supports the binary and json protocols.

More:

For more info on how to use the goshire framework checkout https://github.com/trendrr/goshire.
If there are any issues please submit an ticket.
*/
package main
<commit_msg>updated docs<commit_after>/*
Shrike is a simple memory based key value store goshire service. Shrike uses the STREST protocal and by default
is configured to enable http, json and binary listeners.

Shrike is primarily an in memory store but by setting a data_dir value in your config file, Shrike
will dump all data on interupt or sigterm to a backup file which it will load back in next time you
start it.

Goshire comes with a bundled client that supports the binary and json protocols.

For more info on how to use the goshire framework checkout https://github.com/trendrr/goshire.
If there are any issues please submit an ticket.
*/
package main
<|endoftext|>


<commit_before>/*

Travel is an HTTP router that provides routing similar to the "traversal" system from the Pyramid web framework in Python.

For details on the original traversal system please read: http://docs.pylonsproject.org/docs/pyramid/en/latest/narr/traversal.html

Simply put, traversal allows you to dynamically route HTTP requests by providing a nested map[string]interface{} object called the
"root tree" (Pyramid calls this the *resource tree*). Request URLs are tokenized and recursive lookup is performed on the root
tree object.

Example:

If the request URL is "/foo/bar/baz/123", it is tokenized to the following:

   ["foo", "bar", "baz", "123"]

The equivalent of the following lookup is performed:

   root_tree["foo"]["bar"]["baz"]["123"]

The object that results from this lookup is the "current object" (Pyramid calls this the "context"--travel provides a context object that
contains the current object).

How this maps to handlers (in Pyramid terminology: "views") depends upon the options passed when creating the router. Under traditional
traversal, if the lookup fully succeeded (no missing key errors), the name of the handler would be the empty string ("") which is considered
the default handler. If the lookup failed at any point, the handler name would be the token that failed and any remainder of the URL would
be passed to the handler as the "subpath" (see original traversal documentation linked above for more details).

Usage:

	func defaultHandler(w http.ResponseWriter, r *http.Request, c *travel.Context) {
		// handler code here
	}

	func errorHandler(w http.ResponseWriter, r *http.Request, err travel.TraversalError) {
		// HTTP error handler code here
		http.Error(w, err.Error(), err.Code())
	}

	func getRootTree() {
	  // Fetch root tree here
	}

	handlerMap := map[string]TravelHandler {
		"": defaultHandler,
	}

	options := travel.TravelOptions{
		StrictTraversal:   true,
		SubpathMaxLength: map[string]int{
			"GET":    travel.UnlimitedSubpath,
			"PUT":    0,
			"POST":   0,
			"DELETE": 0,
		},
	}
	r, err := travel.NewRouter(getRootTree, hm, errorHandler, &options)
	if err != nil {
		log.Fatalf("Error creating Travel router: %v\n", err)
	}
	http.Handle("/", r)
	http.ListenAndServe("127.0.0.1:8000", nil)

Travel provides additional options to modify normal traversal semantincs:

Strict vs. Permissive

"Strict" means to follow Pyramid traversal semantics -- handler name can only be "" (empty string) or the latest token in path when
root tree lookup failed (everything beyond that is the subpath). Note that this can be modified with handler name overrides in the
root tree object.

Non-strict (permissive) means that the handler name is always the latest token in the path (regardless if lookup fully succeeds).

Strict setting has no effect on the following options (they can be used to modify "strict" traversal as needed). Handler names
can always be overridden by embedding handler keys within the root tree ('%handler' key within the object, value must be a string).

Handler Overrides

Any level of the root tree can contain a special key "%handler", mapping to a handler name string that will be invoked instead of
whatever traversal would otherwise dictate. Handler overrides take precedence over strict/permissive mode rules.

Default Handler

The optional DefaultHandler is used to execute a fallback handler when traversal succeeds but the handler name returned is not
found within the handler map. Otherwise a 501 Not Implemented error is returned. As with handler overrides, the DefaultHandler
setting is respected regardless of strict/permissive setting.

Subpath Max Length

SubpathMaxLength is a map of method verb (all caps) to an integer representing the allowed number of subpath tokens. If the subpath
length is less than or equal to this limit, the request succeeds and the handler is executed per traversal semantics. If the subpath
exceeds this limit a 404 Not Found is returned. Traditional Pyramid traversal has an unlimited subpath max length. That can be emulated by setting SubpathMaxLength[verb] to
UnlimitedSubpath.

*/<commit_msg>missing package declaration<commit_after>/*
Travel is an HTTP router that provides routing similar to the "traversal" system from the Pyramid web framework in Python.

For details on the original traversal system please read: http://docs.pylonsproject.org/docs/pyramid/en/latest/narr/traversal.html

Simply put, traversal allows you to dynamically route HTTP requests by providing a nested map[string]interface{} object called the
"root tree" (Pyramid calls this the *resource tree*). Request URLs are tokenized and recursive lookup is performed on the root
tree object.

Example:

If the request URL is "/foo/bar/baz/123", it is tokenized to the following:

   ["foo", "bar", "baz", "123"]

The equivalent of the following lookup is performed:

   root_tree["foo"]["bar"]["baz"]["123"]

The object that results from this lookup is the "current object" (Pyramid calls this the "context"--travel provides a context object that
contains the current object).

How this maps to handlers (in Pyramid terminology: "views") depends upon the options passed when creating the router. Under traditional
traversal, if the lookup fully succeeded (no missing key errors), the name of the handler would be the empty string ("") which is considered
the default handler. If the lookup failed at any point, the handler name would be the token that failed and any remainder of the URL would
be passed to the handler as the "subpath" (see original traversal documentation linked above for more details).

Usage:

	func defaultHandler(w http.ResponseWriter, r *http.Request, c *travel.Context) {
		// handler code here
	}

	func errorHandler(w http.ResponseWriter, r *http.Request, err travel.TraversalError) {
		// HTTP error handler code here
		http.Error(w, err.Error(), err.Code())
	}

	func getRootTree() {
	  // Fetch root tree here
	}

	handlerMap := map[string]TravelHandler {
		"": defaultHandler,
	}

	options := travel.TravelOptions{
		StrictTraversal:   true,
		SubpathMaxLength: map[string]int{
			"GET":    travel.UnlimitedSubpath,
			"PUT":    0,
			"POST":   0,
			"DELETE": 0,
		},
	}
	r, err := travel.NewRouter(getRootTree, hm, errorHandler, &options)
	if err != nil {
		log.Fatalf("Error creating Travel router: %v\n", err)
	}
	http.Handle("/", r)
	http.ListenAndServe("127.0.0.1:8000", nil)

Travel provides additional options to modify normal traversal semantincs:

Strict vs. Permissive

"Strict" means to follow Pyramid traversal semantics -- handler name can only be "" (empty string) or the latest token in path when
root tree lookup failed (everything beyond that is the subpath). Note that this can be modified with handler name overrides in the
root tree object.

Non-strict (permissive) means that the handler name is always the latest token in the path (regardless if lookup fully succeeds).

Strict setting has no effect on the following options (they can be used to modify "strict" traversal as needed). Handler names
can always be overridden by embedding handler keys within the root tree ('%handler' key within the object, value must be a string).

Handler Overrides

Any level of the root tree can contain a special key "%handler", mapping to a handler name string that will be invoked instead of
whatever traversal would otherwise dictate. Handler overrides take precedence over strict/permissive mode rules.

Default Handler

The optional DefaultHandler is used to execute a fallback handler when traversal succeeds but the handler name returned is not
found within the handler map. Otherwise a 501 Not Implemented error is returned. As with handler overrides, the DefaultHandler
setting is respected regardless of strict/permissive setting.

Subpath Max Length

SubpathMaxLength is a map of method verb (all caps) to an integer representing the allowed number of subpath tokens. If the subpath
length is less than or equal to this limit, the request succeeds and the handler is executed per traversal semantics. If the subpath
exceeds this limit a 404 Not Found is returned. Traditional Pyramid traversal has an unlimited subpath max length. That can be emulated by setting SubpathMaxLength[verb] to
UnlimitedSubpath.
*/

package travel
<|endoftext|>


<commit_before>// Copyright 2016-2017 Liam Stanley <me@liamstanley.io>. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

// Package girc provides a high level, yet flexible IRC library for use with
// interacting with IRC servers. girc has support for user/channel tracking,
// as well as a few other neat features (like auto-reconnect).
//
// Much of what girc can do, can also be disabled. The goal is to provide a
// solid API that you don't necessarily have to work with out of the box if
// you don't want to.
//
// See "examples/simple/main.go" for a brief and very useful example taking
// advantage of girc, that should give you a general idea of how the API
// works.
package girc
<commit_msg>update examples link<commit_after>// Copyright 2016-2017 Liam Stanley <me@liamstanley.io>. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

// Package girc provides a high level, yet flexible IRC library for use with
// interacting with IRC servers. girc has support for user/channel tracking,
// as well as a few other neat features (like auto-reconnect).
//
// Much of what girc can do, can also be disabled. The goal is to provide a
// solid API that you don't necessarily have to work with out of the box if
// you don't want to.
//
// See https://github.com/lrstanley/girc#examples for a few brief and useful
// examples taking advantage of girc, which should give you a general idea
// of how the API works.
package girc
<|endoftext|>


<commit_before>// Copyright (c) 2013, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

//
// Package pr implements functions for pretty printing of information.
//
// Example
//
//  import (
//  	"bufio"
//  	"flag"
//  	"fmt"
//  	"io"
//  	"os"
//  	"strings"
//
//  	"github.com/goulash/pr"
//  )
//
//  func main() {
//  	reader := bufio.NewReader(os.Stdin)
//  	buffer := make([]string, 0, 32)
//
//  	for {
//  		line, err := reader.ReadString('\n')
//  		if err != nil {
//  			if err != io.EOF {
//  				fmt.Errorf("error: %s\n", err)
//  			}
//  			break
//  		}
//
//  		buffer = append(buffer, strings.TrimSpace(line))
//  	}
//
//  	width := flag.Int("width", -1, "width of the terminal")
//  	flag.Parse()
//
//  	pr.PrintAutoGrid(buffer, *width)
//  }
package pr
<commit_msg>Updating documention<commit_after>// Copyright (c) 2013, Ben Morgan. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.

/*
Package pr implements functions for pretty printing of information.

Currently, it is not in a usable state, but this will change very
soon!

Example

	import (
		"bufio"
		"flag"
		"fmt"
		"io"
		"os"
		"strings"

		"github.com/goulash/pr"
	)

	func main() {
		reader := bufio.NewReader(os.Stdin)
		buffer := make([]string, 0, 32)

		for {
			line, err := reader.ReadString('\n')
			if err != nil {
				if err != io.EOF {
					fmt.Errorf("error: %s\n", err)
				}
				break
			}

			buffer = append(buffer, strings.TrimSpace(line))
		}

		width := flag.Int("width", -1, "width of the terminal")
		flag.Parse()

		pr.PrintAutoGrid(buffer, *width)
	}

*/
package pr
<|endoftext|>


<commit_before>// The go-rpcgen project is an attempt to create an easy-to-use, open source
// protobuf service binding for the standard Go RPC package.  It provides a
// protoc-gen-go (based on the standard "main" from goprotobuf and leveraging
// its libraries) which has a plugin added to also output RPC stub code.
//
// Prerequisites
//
// You will need the protobuf compiler for your operating system of choice.
// You can retrieve this from http://code.google.com/p/protobuf/downloads/list
// if you do not have it already.  As this package builds a plugin for the
// protoc from that package, you will need to have your $GOPATH/bin in your
// path when you run protoc.
//
// Installation
//
// To install, run the following command:
//   go get -v -u github.com/kylelemons/go-rpcgen/protoc-gen-go
//
// Usage
//
// Usage of the package is pretty straightforward.  Once you have installed the
// protoc-gen-go plugin, you can compile protobufs with the following command
// (where file.proto is the protocol buffer file(s) in question):
//   protoc --go_out=. file.proto
//
// This will generate a file named like file.pb.go which contains, in addition
// to the usual Go bindings for the messages, an interface for each service
// containing the methods for that service and functions for creating and using
// them with the RPC package and a webrpc package.
//
// Configuration
//
// By default, protoc-gen-go will generate both RPC and web-based stubs,
// but this can be configured by setting the GO_STUBS environment variable.
// This variable is a comma-separated list of the stubs to generate.  The known
// stubs are:
//
//   rpc // Generate stubs for net/rpc
//   web // Generate stubs for direct HTTP access, e.g. via AppEngine
//
// Generated Code for RPC
//
// Given the following basic .proto definition:
//
//   package echoservice;
//   message payload {
//       required string message = 1;
//   }
//   service echo_service {
//       rpc echo (payload) returns (payload);
//   }
//
// The protoc-gen-go plugin will generate a service definition similar to below:
//
//   // EchoService is an interface satisfied by the generated client and
//   // which must be implemented by the object wrapped by the server.
//   type EchoService interface {
//       Echo(in *Payload, out *Payload) error
//   }
//
//   // DialEchoService returns a EchoService for calling the EchoService servince.
//   func DialEchoService(addr string) (EchoService, error) {
//
//   // NewEchoServiceClient returns an *rpc.Client wrapper for calling the methods
//   // of EchoService remotely.
//   func NewEchoServiceClient(conn net.Conn) EchoService
//
//   // ListenAndServeEchoService serves the given EchoService backend implementation
//   // on all connections accepted as a result of listening on addr (TCP).
//   func ListenAndServeEchoService(addr string, backend EchoService) error
//
//   // ServeEchoService serves the given EchoService backend implementation on conn.
//   func ServeEchoService(conn net.Conn, backend EchoService) error
//
// Any type which implements EchoService can thus be registered via ServeEchoService
// or ListenAndServeEchoService to be called remotely via NewEchoServiceClient or
// DialEchoService.
//
// Generated Code for WebRPC
//
// In addition to the above, the following are also generated to facilitate
// serving RPCs over the web (e.g. AppEngine; see example_ae/):
//
//   // EchoServiceWeb is the web-based RPC version of the interface which
//   // must be implemented by the object wrapped by the webrpc server.
//   type EchoServiceWeb interface {
//     Echo(r *http.Request, in *Payload, out *Payload) error
//   }
//
//   // NewEchoServiceWebClient returns a webrpc wrapper for calling EchoService
//   // remotely via the web.  The remote URL is the base URL of the webrpc server.
//   func NewEchoServiceWebClient(remote *url.URL, pro webrpc.Protocol) EchoService
//
//   // Register a EchoServiceWeb implementation with the given webrpc ServeMux.
//   // If mux is nil, the default webrpc.ServeMux is used.
//   func RegisterEchoServiceWeb(this EchoServiceWeb, mux webrpc.ServeMux) error
//
// Any type which implements EchoServiceWeb (notice that the handlers also
// receive the *http.Request) can be registered.  The RegisterEchoServiceWeb
// function registers the given backend implementation to be called from the
// web via the webrpc package.
//
// Examples
//
// See the examples/ subdirectory for some complete examples demonstrating
// basic usage.  See the example_ae/ subdirectory for an appengine example and
// for directions about how to deploy go-rpcgen on appengine.
//
// Acknowledgements
//
// Thanks to the following people:
//   Bill Broadely <bill@broadley.org> - for beta testing and examples
package main
<commit_msg>change to package rpcgendoc<commit_after>// The go-rpcgen project is an attempt to create an easy-to-use, open source
// protobuf service binding for the standard Go RPC package.  It provides a
// protoc-gen-go (based on the standard "main" from goprotobuf and leveraging
// its libraries) which has a plugin added to also output RPC stub code.
//
// Prerequisites
//
// You will need the protobuf compiler for your operating system of choice.
// You can retrieve this from http://code.google.com/p/protobuf/downloads/list
// if you do not have it already.  As this package builds a plugin for the
// protoc from that package, you will need to have your $GOPATH/bin in your
// path when you run protoc.
//
// Installation
//
// To install, run the following command:
//   go get -v -u github.com/kylelemons/go-rpcgen/protoc-gen-go
//
// Usage
//
// Usage of the package is pretty straightforward.  Once you have installed the
// protoc-gen-go plugin, you can compile protobufs with the following command
// (where file.proto is the protocol buffer file(s) in question):
//   protoc --go_out=. file.proto
//
// This will generate a file named like file.pb.go which contains, in addition
// to the usual Go bindings for the messages, an interface for each service
// containing the methods for that service and functions for creating and using
// them with the RPC package and a webrpc package.
//
// Configuration
//
// By default, protoc-gen-go will generate both RPC and web-based stubs,
// but this can be configured by setting the GO_STUBS environment variable.
// This variable is a comma-separated list of the stubs to generate.  The known
// stubs are:
//
//   rpc // Generate stubs for net/rpc
//   web // Generate stubs for direct HTTP access, e.g. via AppEngine
//
// Generated Code for RPC
//
// Given the following basic .proto definition:
//
//   package echoservice;
//   message payload {
//       required string message = 1;
//   }
//   service echo_service {
//       rpc echo (payload) returns (payload);
//   }
//
// The protoc-gen-go plugin will generate a service definition similar to below:
//
//   // EchoService is an interface satisfied by the generated client and
//   // which must be implemented by the object wrapped by the server.
//   type EchoService interface {
//       Echo(in *Payload, out *Payload) error
//   }
//
//   // DialEchoService returns a EchoService for calling the EchoService servince.
//   func DialEchoService(addr string) (EchoService, error) {
//
//   // NewEchoServiceClient returns an *rpc.Client wrapper for calling the methods
//   // of EchoService remotely.
//   func NewEchoServiceClient(conn net.Conn) EchoService
//
//   // ListenAndServeEchoService serves the given EchoService backend implementation
//   // on all connections accepted as a result of listening on addr (TCP).
//   func ListenAndServeEchoService(addr string, backend EchoService) error
//
//   // ServeEchoService serves the given EchoService backend implementation on conn.
//   func ServeEchoService(conn net.Conn, backend EchoService) error
//
// Any type which implements EchoService can thus be registered via ServeEchoService
// or ListenAndServeEchoService to be called remotely via NewEchoServiceClient or
// DialEchoService.
//
// Generated Code for WebRPC
//
// In addition to the above, the following are also generated to facilitate
// serving RPCs over the web (e.g. AppEngine; see example_ae/):
//
//   // EchoServiceWeb is the web-based RPC version of the interface which
//   // must be implemented by the object wrapped by the webrpc server.
//   type EchoServiceWeb interface {
//     Echo(r *http.Request, in *Payload, out *Payload) error
//   }
//
//   // NewEchoServiceWebClient returns a webrpc wrapper for calling EchoService
//   // remotely via the web.  The remote URL is the base URL of the webrpc server.
//   func NewEchoServiceWebClient(remote *url.URL, pro webrpc.Protocol) EchoService
//
//   // Register a EchoServiceWeb implementation with the given webrpc ServeMux.
//   // If mux is nil, the default webrpc.ServeMux is used.
//   func RegisterEchoServiceWeb(this EchoServiceWeb, mux webrpc.ServeMux) error
//
// Any type which implements EchoServiceWeb (notice that the handlers also
// receive the *http.Request) can be registered.  The RegisterEchoServiceWeb
// function registers the given backend implementation to be called from the
// web via the webrpc package.
//
// Examples
//
// See the examples/ subdirectory for some complete examples demonstrating
// basic usage.  See the example_ae/ subdirectory for an appengine example and
// for directions about how to deploy go-rpcgen on appengine.
//
// Acknowledgements
//
// Thanks to the following people:
//   Bill Broadely <bill@broadley.org> - for beta testing and examples
package rpcgendoc
<|endoftext|>


<commit_before>// Copyright (C) 2015 Space Monkey, Inc.
//
// 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.

/*
More docs soon, but for now, here's a super useful graphviz incantation:

    ccomps -x <(curl -s http://localhost:7070/diagnostics/monitor/v2/funcs/dot) |
      dot | gvpack -array_l1 -m100 | neato -Tsvg -n2 > out.svg

or

    xdot <(curl -s http://localhost:7070/diagnostics/monitor/v2/funcs/dot)

*/
package monitor
<commit_msg>restrict imports<commit_after>// Copyright (C) 2015 Space Monkey, Inc.
//
// 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.

/*
More docs soon, but for now, here's a super useful graphviz incantation:

    ccomps -x <(curl -s http://localhost:7070/diagnostics/monitor/v2/funcs/dot) |
      dot | gvpack -array_l1 -m100 | neato -Tsvg -n2 > out.svg

or

    xdot <(curl -s http://localhost:7070/diagnostics/monitor/v2/funcs/dot)

*/
package monitor // import "gopkg.in/spacemonkeygo/monitor.v2"
<|endoftext|>