Esempio n. 1
0
func TestConstructFail(t *testing.T) {
	err := constructor.New(&struct3{}, func(count int) int {
		return 42
	})
	if err != nil {
		t.Fatal(e.Trace(e.Forward(err)))
	}
	_, err = constructor.Construct(types.Name(&struct3{}), 0)
	if err != nil && !e.Equal(err, ErrInvReturn) {
		t.Fatal(e.Trace(e.Forward(err)))
	} else if err == nil {
		t.Fatal("error is nil")
	}

	err = constructor.Delete(types.Name(&struct3{}))
	if err != nil {
		t.Fatal(e.Trace(e.Forward(err)))
	}

	err = constructor.New(&struct3{}, func(count int) (int, int) {
		return 42, 69
	})
	if err != nil {
		t.Fatal(e.Trace(e.Forward(err)))
	}
	_, err = constructor.Construct(types.Name(&struct3{}), 0)
	if err != nil && !e.Equal(err, ErrInvReturn) {
		t.Fatal(e.Trace(e.Forward(err)))
	} else if err == nil {
		t.Fatal("error is nil")
	}
}
Esempio n. 2
0
func TestDeleteConstructor(t *testing.T) {
	err := constructor.Delete(types.Name(&struct1{}))
	if err != nil {
		t.Fatal(e.Trace(e.Forward(err)))
	}
	err = constructor.Delete(types.Name(&struct1{}))
	if err != nil && !e.Equal(err, ErrConstNotFound) {
		t.Fatal(e.Trace(e.Forward(err)))
	}
}
Esempio n. 3
0
func BenchmarkBoltDbBuffer(b *testing.B) {
	name, err := rand.FileName("boltdb", ".db", 10)
	if err != nil {
		b.Error(e.Trace(e.Forward(err)))
	}
	name = os.TempDir() + "/" + name
	gob := &Gob{
		TypeName: types.Name(&log{}),
	}
	bolt, err := NewBoltDb("test", name, 0600, nil, gob, gob)
	if err != nil {
		b.Error(e.Trace(e.Forward(err)))
	}
	logger := New(
		NewOutBuffer(
			NewGeneric(bolt).F(DefFormatter),
			b.N/2,
		),
		false,
	).Domain("test")
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		logger.Print(msg)
		b.SetBytes(l)
	}
}
Esempio n. 4
0
func TestBoltDb(t *testing.T) {
	name, err := rand.FileName("boltdb", ".db", 10)
	if err != nil {
		t.Fatal(e.Trace(e.Forward(err)))
	}
	name = os.TempDir() + "/" + name
	gob := &Gob{
		TypeName: types.Name(&TestStruct{I: 0}),
	}
	addstore(t, NewBoltDb, "test", name, os.FileMode(0600), &bolt.Options{}, gob, gob)
}
Esempio n. 5
0
func encImg(val interface{}) ([]byte, error) {
	buf := bytes.NewBuffer([]byte{})
	enc := gob.NewEncoder(buf)
	err := enc.Encode(types.Name(val))
	if err != nil {
		return nil, err
	}
	err = enc.Encode(val)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
Esempio n. 6
0
func (c *Constructors) New(val, fn interface{}) error {
	c.lck.Lock()
	defer c.lck.Unlock()
	name := types.Name(val)
	if _, found := c.constructors[name]; found {
		return e.New(ErrConstExist)
	}
	v := reflect.ValueOf(fn)
	if v.Kind() != reflect.Func {
		return e.New(ErrConstIsntFn)
	}
	c.constructors[name] = v
	return nil
}
Esempio n. 7
0
func TestConstruct(t *testing.T) {
	val, err := constructor.Construct(types.Name(&struct1{}), 42)
	if err != nil {
		t.Fatal(e.Trace(e.Forward(err)))
	}
	if reflect.Indirect(val).FieldByName("Count").Int() != 42 {
		t.Fatal("constructor failed")
	}
	_, err = constructor.Construct("foo", 42)
	if err != nil && !e.Equal(err, ErrTypeNotFound) {
		t.Fatal(e.Trace(e.Forward(err)))
	} else if err == nil {
		t.Fatal("error is nil")
	}
	val, err = constructor.Construct(types.Name(&struct2{}), 0)
	if err != nil && !e.Equal(err, ErrTypeNotFound) {
		t.Fatal(e.Trace(e.Forward(err)))
	} else if err == nil {
		t.Fatal("error is nil")
	}
	// if val.Type() != reflect.TypeOf(&struct2{}) {
	// 	t.Fatal("constructor failed")
	// }
}
Esempio n. 8
0
func (r respCall) EncodeMsgpack(enc *msgpack.Encoder) error {
	if r.Err == nil {
		err := enc.Encode(util.ErrNil)
		if err != nil {
			return e.Forward(err)
		}
	} else {
		err := enc.Encode(util.ErrOk)
		if err != nil {
			return e.Forward(err)
		}
		switch v := r.Err.(type) {
		case *e.Error:
			err = enc.Encode(util.ErrorPriv)
			if err != nil {
				return e.Forward(err)
			}
			err = enc.Encode(types.Name(r.Err))
			if err != nil {
				return e.Forward(err)
			}
			err = enc.Encode(r.Err)
			if err != nil {
				return e.Forward(err)
			}
		case error:
			err = enc.Encode(util.ErrorInt)
			if err != nil {
				return e.Forward(err)
			}
			err = enc.Encode(v.Error())
			if err != nil {
				return e.Forward(err)
			}
		}
	}
	err := enc.Encode(len(r.Vals))
	if err != nil {
		return e.Forward(err)
	}
	for _, arg := range r.Vals {
		err := util.MsgPackEncode(enc, arg)
		if err != nil {
			return e.Forward(err)
		}
	}
	return nil
}
Esempio n. 9
0
func (f *Func) Visit(node ast.Node) (w ast.Visitor) {
	switch t := node.(type) {
	case *ast.FieldList:
		if len(t.List) > 0 {
			if len(t.List[0].Names) > 0 {
				f.Recv = t.List[0].Names[0].Name
			}
			switch i := t.List[0].Type.(type) {
			case *ast.StarExpr:
				if ident, ok := i.X.(*ast.Ident); ok {
					f.RecvType = ident.Name
					f.PtrRecv = true
				} else {
					panic("X isn't *ast.Ident")
				}
			case *ast.Ident:
				f.RecvType = i.Name
				f.PtrRecv = false
			default:
				panic("Func: wrong type of node: " + types.Name(i))
			}
			if len(f.RecvType) > 0 && !unicode.IsUpper(rune(f.RecvType[0])) {
				return nil
			}
			return nil
		}
	case *ast.Ident:
		if f.Recv == "" {
			return nil
		}
		f.Name = t.Name
		return nil
	case *ast.FuncType:
		if f.Recv == "" {
			return nil
		}
		f.Params = &Params{
			src:       f.src,
			Arguments: make([][]*Argument, 2),
			Pkgs:      f.Pkgs,
		}
		return f.Params
	}
	return nil
}
Esempio n. 10
0
func (r *RespInst) EncodeMsgpack(enc *msgpack.Encoder) error {
	err := enc.EncodeString(r.Inst)
	if err != nil {
		return e.Forward(err)
	}
	if r.Err == nil {
		err := enc.Encode(util.ErrNil)
		if err != nil {
			return e.Forward(err)
		}
	} else {
		err := enc.Encode(util.ErrOk)
		if err != nil {
			return e.Forward(err)
		}
		switch v := r.Err.(type) {
		case *e.Error:
			err = enc.Encode(util.ErrorPriv)
			if err != nil {
				return e.Forward(err)
			}
			err = enc.Encode(types.Name(r.Err))
			if err != nil {
				return e.Forward(err)
			}
			err = enc.Encode(r.Err)
			if err != nil {
				return e.Forward(err)
			}
		case error:
			err = enc.Encode(util.ErrorInt)
			if err != nil {
				return e.Forward(err)
			}
			err = enc.Encode(v.Error())
			if err != nil {
				return e.Forward(err)
			}
		}
	}
	return nil
}
Esempio n. 11
0
// Store stores a function.
func Store(f interface{}) {
	name := types.Name(f)
	if _, found := functions[name]; !found {
		functions[name] = f
	}
}
Esempio n. 12
0
func (v *Visitor) Visit(node ast.Node) (w ast.Visitor) {
	switch t := node.(type) {
	case *ast.FuncDecl:
		name := t.Name.Name
		if !unicode.IsUpper(rune(name[0])) {
			return nil
		}
		r := t.Recv
		if r != nil {
			if len(r.List) > 0 {
				recv := ""
				switch i := r.List[0].Type.(type) {
				case *ast.StarExpr:
					if ident, ok := i.X.(*ast.Ident); ok {
						recv = ident.Name
					} else {
						panic("X isn't *ast.Ident")
					}
				case *ast.Ident:
					recv = i.Name
				default:
					panic("Func: wrong type of node: " + types.Name(i))
				}
				if len(recv) > 0 && !unicode.IsUpper(rune(recv[0])) {
					return nil
				}
			} else {
				return nil
			}
		}
		f := &Func{
			src:      v.src,
			Comments: v.makeComments(node),
			Pkgs:     v.Pkgs,
		}
		v.Functions = append(v.Functions, f)
		return f
	case *ast.GenDecl:
		switch t.Tok {
		case token.TYPE:
			if len(t.Specs) == 0 {
				return nil
			}
			ts, ok := t.Specs[0].(*ast.TypeSpec)
			if !ok {
				return nil
			}
			switch ts.Type.(type) {
			case *ast.InterfaceType:
				return nil
				//case *ast.StructType:
			default:
				if len(ts.Name.Name) > 0 && !unicode.IsUpper(rune(ts.Name.Name[0])) {
					return nil
				}
				s := &Strct{
					Name:     ts.Name.Name,
					Type:     ts.Type,
					Comments: v.makeComments(node),
				}
				v.Struct[ts.Name.Name] = s
				v.StructOrder = append(v.StructOrder, s)
				return v
			}
		case token.IMPORT:
			for _, spec := range t.Specs {
				ispec, ok := spec.(*ast.ImportSpec)
				if !ok {
					return nil
				}
				if ispec.Name != nil {
					if ispec.Name.Name != "_" {
						v.Pkgs.Add(ispec.Name.Name, ispec.Path.Value)
					}
				} else {
					v.Pkgs.Add("", ispec.Path.Value)
				}
			}
		}
	}
	return v
}
Esempio n. 13
0
func (s *Server) protoCall(conn InstConn) (err error) {
	enc := conn.Encoder()
	dec := conn.Decoder()
	defer func() {
		if err != nil {
			err = enc.Encode(&respCall{Err: err})
			if err != nil {
				log.ProtoLevel().Tag("server", "gormethods").Printf("Encode %v -> %v (%v) error: %v", conn.RemoteAddr(), conn.LocalAddr(), conn.StreamNum(), err)
				err = e.Push(err, ErrWire)
			}
		}
	}()

	inst, err := s.Insts.Get(conn.SessionName(), conn.InstanceName())
	if err != nil {
		log.Tag("server", "gormethods").Errorf("Error getting the instance %v/%v: %v", conn.SessionName(), conn.InstanceName(), e.Forward(err))
		err = e.Forward(err)
		return
	}

	if inst.Type() != WithValue {
		log.Tag("server", "gormethods").Errorf("Instance %v/%v is of wrong type", conn.SessionName(), conn.InstanceName())
		return e.New("instance is of wrong type")
	}

	log.ProtoLevel().Tag("gormethods", "server", "call").Printf("Call %v %v %v", conn.SessionName(), conn.InstanceName(), types.NameOf(inst.Instance().Type()))

	var req reqCall
	err = dec.Decode(&req)
	if e.Find(err, io.EOF) >= 0 {
		return e.Push(err, ErrWire)
	} else if err != nil {
		log.ProtoLevel().Tag("server", "gormethods").Printf("Decode %v -> %v (%v) error: %v", conn.RemoteAddr(), conn.LocalAddr(), conn.StreamNum(), err)
		err = e.Push(err, ErrWire)
		return
	}

	// Tratar argumentos (req.Args) com channel

	// 	criar channel
	// 	recebe do channel envia pelo conn
	// 	recebe do conn envia para channel
	// 	(faz isso até fechar o channel em um dos lados)

	// substutui em req.Args os channels

	// Se existem channels enviar instancias

	err = s.mkChServer(conn, req.Args, enc)
	if err != nil {
		err = e.Forward(err)
		log.Tag("server", "gormethods").Errorf("Channel arguments setup failed: %v", err)
		return
	}

	method := inst.Instance().MethodByName(req.Method)
	if !method.IsValid() {
		err = e.Push(e.New(ErrMethodNotFound), e.New("method %v not found", req.Method))
		log.Tag("server", "gormethods").Errorf("Error in call %v/%v: %v", conn.SessionName(), conn.InstanceName(), err)
		return
	}
	log.ProtoLevel().Tag("server", "gormethods").Printf("Call %v/%v %v %v", conn.SessionName(), conn.InstanceName(), types.NameOf(inst.Instance().Type()), req.Method)
	var retvals []reflect.Value
	if method.Type().IsVariadic() {
		retvals = method.CallSlice(req.Args)
	} else {
		retvals = method.Call(req.Args)
	}
	log.ProtoLevel().Tag("server", "gormethods").Printf("Call returned %v/%v %v %v", conn.SessionName(), conn.InstanceName(), types.NameOf(inst.Instance().Type()), req.Method)
	for i := range retvals {
		var exp *Export
		exp, err = s.Insts.ExportGet(conn.SessionName(), conn.InstanceName(), req.Method, i)
		if err != nil {
			continue
		}
		var instname string
		instname, err = rand.Chars(16, rand.NumberLetters, "go")
		if err != nil {
			err = e.Push(err, "can't create the instance name for exported retval")
			log.Tag("server", "gormethods").Errorf("Error in call %v/%v: %v", conn.SessionName(), conn.InstanceName(), err)
			return
		}
		owners := auth.NewPlainTextCredentials()
		err = owners.Add(conn.Auth())
		if err != nil {
			err = e.Push(err, "can't authorize the exported retval")
			log.Tag("server", "gormethods").Errorf("Error in call %v/%v: %v", conn.SessionName(), conn.InstanceName(), err)
			return
		}
		err = s.Insts.New(conn.SessionName(), instname, retvals[i], owners)
		if err != nil {
			err = e.Push(err, "can't crete the instance for the exported retval")
			log.Tag("server", "gormethods").Errorf("Error in call %v/%v: %v", conn.SessionName(), instname, err)
			return
		}
		for _, to := range exp.ToExport {
			err = s.Insts.Export(conn.SessionName(), instname, to)
			if err != nil {
				err = e.Push(err, e.New("can't export %v/%v %v %v %v to %v", conn.SessionName(), instname, to.Method, to.RetvalPos, types.Name(retvals[i].Interface()), types.Name(exp.Client)))
				log.Tag("server", "gormethods").Errorf("Error in call %v/%v: %v", conn.SessionName(), conn.InstanceName(), err)
				return
			}
		}
		exp.Client.Associate(conn.SessionName(), instname, conn.Auth())
		retvals[i] = reflect.ValueOf(exp.Client)
		continue
	}
	log.ProtoLevel().Tag("server", "gormethods").Printf("Send returned values %v/%v %v %v", conn.SessionName(), conn.InstanceName(), types.NameOf(inst.Instance().Type()), req.Method)
	err = enc.Encode(&respCall{
		Vals: retvals,
		Err:  nil,
	})
	if err != nil {
		log.ProtoLevel().Tag("server", "gormethods").Printf("Encode %v -> %v (%v) error: %v", conn.RemoteAddr(), conn.LocalAddr(), conn.StreamNum(), err)
		err = e.Push(err, ErrWire)
		return
	}
	log.ProtoLevel().Tag("server", "gormethods").Printf("Send returned values done %v/%v %v %v", conn.SessionName(), conn.InstanceName(), types.NameOf(inst.Instance().Type()), req.Method)
	return
}