Пример #1
0
func (d *HttpHandlerDelegate) Initialize(ctx application.Context) {
	request, pointer := http_server_factory.CreateMessagePipeForHttpServerFactory()
	ctx.ConnectToApplication("mojo:http_server").ConnectToService(&request)
	factory := http_server_factory.NewHttpServerFactoryProxy(pointer, bindings.GetAsyncWaiter())

	addr := &net_address.NetAddress{
		net_address.NetAddressFamily_IpV4,
		&net_address.NetAddressIPv4{
			8080,
			[4]uint8{127, 0, 0, 1},
		},
		nil,
	}
	serverRequest, serverPointer := http_server.CreateMessagePipeForHttpServer()
	factory.CreateHttpServer(serverRequest, addr)
	d.server = http_server.NewHttpServerProxy(serverPointer, bindings.GetAsyncWaiter())
	handlerRequest, handlerPointer := http_server.CreateMessagePipeForHttpHandler()
	ok, err := d.server.SetHandler("/go", handlerPointer)
	if !ok {
		log.Println("can't set handler:", err)
		return
	}

	d.handlerStub = http_server.NewHttpHandlerStub(handlerRequest, &HttpHandler{}, bindings.GetAsyncWaiter())
	go func() {
		for {
			if err := d.handlerStub.ServeRequest(); err != nil {
				log.Println("can't handle http request:", err)
				return
			}
		}
	}()
	factory.Close_Proxy()
}
Пример #2
0
func (d *mdiscovery) Scan(query string, handlerPtr mojom.ScanHandler_Pointer) (*mojom.Closer_Pointer, *mojom.Error, error) {
	ctx, cancel := context.WithCancel(d.ctx)

	scanCh, err := d.d.Scan(ctx, query)
	if err != nil {
		cancel()
		return nil, v2mError(err), nil
	}

	handler := mojom.NewScanHandlerProxy(handlerPtr, bindings.GetAsyncWaiter())
	go func() {
		defer handler.Close_Proxy()

		for update := range scanCh {
			mUpdate := newMojoUpdate(d.ctx, update)

			req, ptr := mojom.CreateMessagePipeForUpdate()
			stub := mojom.NewUpdateStub(req, mUpdate, bindings.GetAsyncWaiter())
			if err := handler.OnUpdate(ptr); err != nil {
				stub.Close()
				cancel()
				return
			}
			d.serveStub(stub, nil)
		}
	}()

	req, ptr := mojom.CreateMessagePipeForCloser()
	stub := mojom.NewCloserStub(req, &closer{cancel}, bindings.GetAsyncWaiter())
	d.serveStub(stub, cancel)
	return &ptr, nil, nil
}
Пример #3
0
func (psd *principalServiceDelegate) fetchWireBlessings(token string, pub publicKey) (*wireBlessings, error) {
	networkReq, networkPtr := network.CreateMessagePipeForNetworkService()
	psd.Ctx.ConnectToApplication("mojo:network_service").ConnectToService(&networkReq)
	networkProxy := network.NewNetworkServiceProxy(networkPtr, bindings.GetAsyncWaiter())

	urlLoaderReq, urlLoaderPtr := url_loader.CreateMessagePipeForUrlLoader()
	if err := networkProxy.CreateUrlLoader(urlLoaderReq); err != nil {
		return nil, fmt.Errorf("Failed to create url loader: %v", err)
	}
	urlLoaderProxy := url_loader.NewUrlLoaderProxy(urlLoaderPtr, bindings.GetAsyncWaiter())

	req, err := blessingRequestURL(token, pub)
	if err != nil {
		return nil, err
	}

	resp, err := urlLoaderProxy.Start(*req)
	if err != nil || resp.Error != nil {
		return nil, fmt.Errorf("Blessings request to Vanadium Identity Provider failed: %v(%v)", err, resp.Error)
	}

	res, b := (*resp.Body).ReadData(system.MOJO_READ_DATA_FLAG_ALL_OR_NONE)
	if res != system.MOJO_RESULT_OK {
		return nil, fmt.Errorf("Failed to read response (blessings) from Vanadium Identity Provider. Result: %v", res)
	}

	var wb wireBlessings
	if err := json.Unmarshal(b, &wb); err != nil {
		return nil, fmt.Errorf("Failed to unmarshal response (blessings) from Vanadium Identity Provider: %v", err)
	}
	// TODO(ataly, gauthamt): We should verify all signatures on the certificate chains in the
	// wire blessings to ensure that it was not tampered with.
	return &wb, nil
}
Пример #4
0
func (d *delegate) Initialize(ctx application.Context) {
	req, ptr := discovery.CreateMessagePipeForDiscovery()
	ctx.ConnectToApplication("https://mojo.v.io/discovery.mojo").ConnectToService(&req)

	ad := discovery.Advertisement{
		InterfaceName: "v.io/discovery.T",
		Addresses:     []string{"localhost:1000"},
		Attributes:    &map[string]string{"foo": "abc"},
		Attachments:   &map[string][]byte{"bar": []byte{1, 2, 3}},
	}
	dProxy := discovery.NewDiscoveryProxy(ptr, bindings.GetAsyncWaiter())
	id, closerPtr, e1, e2 := dProxy.Advertise(ad, nil)
	if e1 != nil || e2 != nil {
		log.Printf("Failed to advertise: %v, %v", e1, e2)
		return
	}
	log.Printf("Advertising %x...", *id)

	d.stop = func() {
		cProxy := discovery.NewCloserProxy(*closerPtr, bindings.GetAsyncWaiter())
		cProxy.Close()
		cProxy.Close_Proxy()

		dProxy.Close_Proxy()
	}
}
Пример #5
0
func (psd *principalServiceDelegate) getBlessing(token string, pub publicKey) ([]uint8, error) {
	networkReq, networkPtr := network.CreateMessagePipeForNetworkService()
	psd.Ctx.ConnectToApplication("mojo:network_service").ConnectToService(&networkReq)
	networkProxy := network.NewNetworkServiceProxy(networkPtr, bindings.GetAsyncWaiter())

	urlLoaderReq, urlLoaderPtr := url_loader.CreateMessagePipeForUrlLoader()
	if err := networkProxy.CreateUrlLoader(urlLoaderReq); err != nil {
		return nil, fmt.Errorf("failed to create url loader: %v", err)
	}
	urlLoader := url_loader.NewUrlLoaderProxy(urlLoaderPtr, bindings.GetAsyncWaiter())

	req, err := blessingRequestURL(token, pub)
	if err != nil {
		return nil, err
	}

	resp, err := urlLoader.Start(*req)
	if err != nil || resp.Error != nil {
		return nil, fmt.Errorf("blessings request to Vanadium Identity Provider failed: %v(%v)", err, resp.Error)
	}

	res, b := (*resp.Body).ReadData(system.MOJO_READ_DATA_FLAG_ALL_OR_NONE)
	if res != system.MOJO_RESULT_OK {
		return nil, fmt.Errorf("failed to read response (blessings) from Vanadium Identity Provider. Result: %v", res)
	}
	return b, nil
}
Пример #6
0
// callRemoteSignature obtains type and header information from the remote
// mojo service. Remote mojo interfaces all define a signature method.
func (fs fakeService) callRemoteSignature(mojourl string, mojoname string) (mojomInterface mojom_types.MojomInterface, desc map[string]mojom_types.UserDefinedType, err error) {
	// TODO(afandria): The service_describer mojom file defines the constant, but
	// it is not actually present in the generated code:
	// https://github.com/domokit/mojo/issues/469
	// serviceDescriberInterfaceName := "_ServiceDescriber"

	r, p := service_describer.CreateMessagePipeForServiceDescriber()
	fs.appctx.ConnectToApplication(mojourl).ConnectToService(&r)
	sDescriber := service_describer.NewServiceDescriberProxy(p, bindings.GetAsyncWaiter())
	defer sDescriber.Close_Proxy()

	r2, p2 := service_describer.CreateMessagePipeForServiceDescription()
	err = sDescriber.DescribeService(mojoname, r2)
	if err != nil {
		return
	}
	sDescription := service_describer.NewServiceDescriptionProxy(p2, bindings.GetAsyncWaiter())
	defer sDescription.Close_Proxy()

	mojomInterface, err = sDescription.GetTopLevelInterface()
	if err != nil {
		return
	}
	descPtr, err := sDescription.GetAllTypeDefinitions()
	if err != nil {
		return
	}
	return mojomInterface, *descPtr, nil
}
Пример #7
0
// When running fortune_client, ctx.Args() should contain:
// 0: mojo app name
// 1: remote endpoint
// 2+: (optional) fortune to add
// If the fortune to add is omitted, then the fortune_client will Get a fortune.
// Otherwise, it will Add the given fortune.
func (delegate *FortuneClientDelegate) Initialize(ctx application.Context) {
	// Parse the arguments.
	remoteEndpoint := ctx.Args()[1]
	addFortune := strings.Join(ctx.Args()[2:], " ")

	log.Printf("FortuneClientDelegate.Initialize... %s", remoteEndpoint)
	fortuneRequest, fortunePointer := fortune.CreateMessagePipeForFortune()
	v23.ConnectToRemoteService(ctx, &fortuneRequest, remoteEndpoint)
	fortuneProxy := fortune.NewFortuneProxy(fortunePointer, bindings.GetAsyncWaiter())

	if addFortune != "" {
		log.Printf("FortuneClientDelegate.Initialize calling Add...")

		if err := fortuneProxy.Add(addFortune); err != nil {
			log.Println(err)
		} else {
			fmt.Printf("client added: %s\n", addFortune)
		}
	} else {
		log.Printf("FortuneClientDelegate.Initialize calling Get...")
		response, err := fortuneProxy.Get()
		if response != "" {
			fmt.Printf("client (get): %s\n", response)
		} else {
			log.Println(err)
		}
	}

	fortuneProxy.Close_Proxy()
	ctx.Close()
}
Пример #8
0
func match(updatePtrs []mojom.Update_Pointer, lost bool, wants ...mojom.Advertisement) error {
	updateMap := make(map[[internal.AdIdLen]uint8]mojom.Update)
	updates := make([]mojom.Update, 0)
	for _, ptr := range updatePtrs {
		update := mojom.NewUpdateProxy(ptr, bindings.GetAsyncWaiter())
		defer update.Close_Proxy()

		id, _ := update.GetId()
		updateMap[id] = update
		updates = append(updates, update)
	}
	for _, want := range wants {
		update := updateMap[*want.Id]
		if update == nil {
			break
		}
		if got, _ := update.IsLost(); got != lost {
			break
		}
		if !updateEqual(update, want) {
			break
		}
		delete(updateMap, *want.Id)
	}
	if len(updateMap) == 0 {
		return nil
	}
	return fmt.Errorf("Match failed; got %v, but wanted %v", updatesToDebugString(updates), adsToDebugString(wants))
}
Пример #9
0
func (r *v23HeaderReceiver) SetupClientProxy(v23Name string, ifaceSig mojom_types.MojomInterface, desc map[string]mojom_types.UserDefinedType, serviceName string, handle system.MessagePipeHandle) (err error) {
	log := r.delegate.ctx
	log.Infof("[server] In SetupProxy(%s, %v, %v, %s, %v)", v23Name, ifaceSig, desc, serviceName, handle)
	r.v23Name = v23Name
	r.ifaceSig = ifaceSig
	r.desc = desc
	r.serviceName = serviceName
	r.handle = handle

	go func() {
		connector := bindings.NewConnector(r.handle, bindings.GetAsyncWaiter())

		// Read generic calls in a loop
		receiver := &messageReceiver{
			header:    r,
			ctx:       r.delegate.ctx,
			connector: connector,
		}
		stub := bindings.NewStub(connector, receiver)
		for {
			if err := stub.ServeRequest(); err != nil {
				connectionError, ok := err.(*bindings.ConnectionError)
				if !ok || !connectionError.Closed() {
					log.Errorf("%v", err)
				}
				break
			}
		}
		r.delegate.stubs = append(r.delegate.stubs, stub)
	}()
	return nil
}
Пример #10
0
// ProvideServices starts a service provider on a separate goroutine that
// provides given services to the remote application. Returns a pointer to
// outgoing connection that can be used to connect to services provided by
// remote application.
// Panics if called more than once.
func (c *Connection) ProvideServices(services ...ServiceFactory) *OutgoingConnection {
	if c.servicesProvided {
		panic("ProvideServices or ProvideServicesWithDescriber can be called only once")
	}
	c.servicesProvided = true
	if c.servicesRequest == nil {
		return c.outgoingConnection
	}
	if len(services) == 0 {
		c.servicesRequest.PassMessagePipe().Close()
		return c.outgoingConnection
	}

	provider := &serviceProviderImpl{
		make(map[string]ServiceFactory),
	}
	for _, service := range services {
		provider.AddService(service)
	}
	c.localServices = sp.NewServiceProviderStub(*c.servicesRequest, provider, bindings.GetAsyncWaiter())
	go func() {
		for {
			if err := c.localServices.ServeRequest(); err != nil {
				connectionError, ok := err.(*bindings.ConnectionError)
				if !ok || !connectionError.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()
	return c.outgoingConnection
}
Пример #11
0
// When running echo_client, ctx.Args() should contain:
// 0: mojo app name
// 1: remote endpoint
// 2+: string to echo
func (delegate *RemoteEchoClientDelegate) Initialize(ctx application.Context) {
	log.Printf("RemoteEchoClientDelegate.Initialize...")

	// Parse arguments. Note: May panic if not enough args are given.
	remoteEndpoint := ctx.Args()[1]
	echoString := "Hello, Go world!"
	if len(ctx.Args()) > 2 {
		echoString = strings.Join(ctx.Args()[2:], " ")
	}

	r, p := echo.CreateMessagePipeForRemoteEcho()

	v23.ConnectToRemoteService(ctx, &r, remoteEndpoint)
	echoProxy := echo.NewRemoteEchoProxy(p, bindings.GetAsyncWaiter())

	log.Printf("RemoteEchoClientDelegate.Initialize calling EchoString...")
	response, err := echoProxy.EchoString(echoString)
	if err == nil {
		fmt.Printf("client: %s\n", response)
	} else {
		fmt.Printf("error: %v\n", err)
	}

	log.Printf("RemoteEchoClientDelegate.Initialize calling EchoX...")
	response2, err := echoProxy.EchoX([]bool{true, false, false, true}, echo.AInArg{"A String"})
	if err == nil {
		fmt.Printf("client: %v\n", response2)
	} else {
		log.Println("Error: ", err)
	}

	fmt.Printf("(done)\n")
	echoProxy.Close_Proxy()
	ctx.Close()
}
Пример #12
0
func createProxy(ctx application.Context) *end_to_end_test.V23ProxyTest_Proxy {
	// Parse arguments. Note: May panic if not enough args are given.
	remoteName := *endpointFlag

	r, p := end_to_end_test.CreateMessagePipeForV23ProxyTest()
	v23.ConnectToRemoteService(ctx, &r, remoteName)
	return end_to_end_test.NewV23ProxyTestProxy(p, bindings.GetAsyncWaiter())
}
// Mojo application implementation.
func (impl *ApplicationImpl) Initialize(shellPointer shell.Shell_Pointer, args *[]string, url string) error {
	impl.shell = shell.NewShellProxy(shellPointer, bindings.GetAsyncWaiter())
	if args != nil {
		impl.args = *args
	}
	impl.url = url
	impl.delegate.Initialize(impl)
	return nil
}
Пример #14
0
func (f *factory) Create(request mojom.Discovery_Request) {
	discovery, err := internal.NewDiscovery(f.d.ctx, f.url)
	if err != nil {
		f.d.ctx.Error(err)
		request.Close()
		return
	}
	stub := mojom.NewDiscoveryStub(request, discovery, bindings.GetAsyncWaiter())
	f.d.run(stub, discovery.Close)
}
Пример #15
0
func (delegate *EchoDelegate) Create(request echo.Echo_Request) {
	stub := echo.NewEchoStub(request, &EchoImpl{}, bindings.GetAsyncWaiter())
	go func() {
		if err := stub.ServeRequest(); err != nil {
			panic(err)
		}
		stub.Close()
		delegate.Wg.Done()
	}()
}
func newGlobalDiscovery(mctx application.Context, scanInterval time.Duration) *mojom.Discovery_Proxy {
	u, _ := url.Parse("https://mojo.v.io/discovery.mojo")
	q := u.Query()
	q.Set(QueryGlobal, "a/b/c")
	q.Set(QueryScanInterval, fmt.Sprintf("%.3fs", scanInterval.Seconds()))
	u.RawQuery = q.Encode()

	req, ptr := mojom.CreateMessagePipeForDiscovery()
	mctx.ConnectToApplication(u.String()).ConnectToService(&req)
	return mojom.NewDiscoveryProxy(ptr, bindings.GetAsyncWaiter())
}
Пример #17
0
func scan(d mojom.Discovery, query string) (<-chan mojom.Update_Pointer, func(), error) {
	ch := make(chan mojom.Update_Pointer, 10)
	handler := &mockScanHandler{ch}
	req, ptr := mojom.CreateMessagePipeForScanHandler()
	stub := mojom.NewScanHandlerStub(req, handler, bindings.GetAsyncWaiter())

	closer, e1, e2 := d.Scan(query, ptr)
	if e1 != nil {
		close(ch)
		return nil, nil, errors.New(e1.Msg)
	}
	if e2 != nil {
		close(ch)
		return nil, nil, e2
	}

	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			if err := stub.ServeRequest(); err != nil {
				connErr, ok := err.(*bindings.ConnectionError)
				if !ok || !connErr.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()

	stop := func() {
		p := mojom.NewCloserProxy(*closer, bindings.GetAsyncWaiter())
		p.Close()
		p.Close_Proxy()
		stub.Close()
		wg.Wait()
		close(ch)
	}
	return ch, stop, nil
}
Пример #18
0
func checkWait(handle system.Handle, signals system.MojoHandleSignals, expected system.MojoResult, wg *sync.WaitGroup) {
	wg.Add(1)
	responseChan := make(chan bindings.WaitResponse)
	bindings.GetAsyncWaiter().AsyncWait(handle, signals, responseChan)
	go func() {
		response := <-responseChan
		if expected != response.Result {
			panic(fmt.Sprintf("unexpected wait result: expected %v, got %v", expected, response.Result))
		}
		wg.Done()
	}()
}
Пример #19
0
func (d *HttpServerDelegate) InitServerSocket() error {
	request, pointer := tcp_server_socket.CreateMessagePipeForTcpServerSocket()
	networkError, err := d.tcpBoundSocket.StartListening(request)
	if err != nil {
		return err
	}
	if networkError.Code != 0 {
		return fmt.Errorf("%s", *networkError.Description)
	}
	d.serverSocket = tcp_server_socket.NewTcpServerSocketProxy(pointer, bindings.GetAsyncWaiter())
	return nil
}
Пример #20
0
func checkEcho(echoPointer echo.Echo_Pointer) {
	echo := echo.NewEchoProxy(echoPointer, bindings.GetAsyncWaiter())
	str := fmt.Sprintf("Hello, world")
	response, err := echo.EchoString(&str)
	if err != nil {
		panic(err)
	}
	if *response != str {
		panic(fmt.Sprintf("invalid response: want %v, got %v", str, *response))
	}
	echo.Close_Proxy()
}
Пример #21
0
func (delegate *EchoClientDelegate) Initialize(ctx application.Context) {
	echoRequest, echoPointer := echo.CreateMessagePipeForEcho()
	ctx.ConnectToApplication("mojo:go_echo_server").ConnectToService(&echoRequest)
	echoProxy := echo.NewEchoProxy(echoPointer, bindings.GetAsyncWaiter())
	response, err := echoProxy.EchoString(bindings.StringPointer("Hello, Go world!"))
	if response != nil {
		fmt.Printf("client: %s\n", *response)
	} else {
		log.Println(err)
	}
	echoProxy.Close_Proxy()
	ctx.Close()
}
Пример #22
0
func TestApplication(t *testing.T) {
	var apps []*mojoApp.Application_Proxy
	var responsesSent, appsTerminated sync.WaitGroup
	// Create and run applications.
	for i := 0; i < 2; i++ {
		request, pointer := mojoApp.CreateMessagePipeForApplication()
		apps = append(apps, mojoApp.NewApplicationProxy(pointer, bindings.GetAsyncWaiter()))
		// Each app instance provides echo service once when it creates
		// a connection and once other instance creates a connection.
		responsesSent.Add(2)
		appsTerminated.Add(1)
		delegate := &EchoDelegate{&responsesSent, urls[i]}
		go func() {
			application.Run(delegate, request.PassMessagePipe().ReleaseNativeHandle())
			appsTerminated.Done()
		}()
	}
	// Provide a shell for each application.
	for i := 0; i < 2; i++ {
		shellRequest, shellPointer := shell.CreateMessagePipeForShell()
		shellStub := shell.NewShellStub(shellRequest, &shellImpl{apps[i^1], urls[i]}, bindings.GetAsyncWaiter())
		go func() {
			if err := shellStub.ServeRequest(); err != nil {
				panic(err)
			}
			shellStub.Close()
		}()
		apps[i].Initialize(shellPointer, &[]string{urls[i]}, urls[i])
	}
	// Wait and then close pipes.
	responsesSent.Wait()
	for i := 0; i < 2; i++ {
		apps[i].RequestQuit()
	}
	appsTerminated.Wait()
	for i := 0; i < 2; i++ {
		apps[i].Close_Proxy()
	}
}
Пример #23
0
func TestAcceptWithResponseMultiple(t *testing.T) {
	r, h0, h1 := core.CreateMessagePipe(nil)
	defer h1.Close()
	if r != system.MOJO_RESULT_OK {
		t.Fatalf("can't create a message pipe: %v", r)
	}
	router := bindings.NewRouter(h0, bindings.GetAsyncWaiter())
	var wg sync.WaitGroup
	wg.Add(numberOfRequests + 1)
	// Serve requests.
	go func() {
		for i := 0; i < numberOfRequests; i++ {
			c := make(chan bindings.WaitResponse, 1)
			bindings.GetAsyncWaiter().AsyncWait(h1, system.MOJO_HANDLE_SIGNAL_READABLE, c)
			r, bytes, handles := h1.ReadMessage(system.MOJO_READ_MESSAGE_FLAG_NONE)
			if r != system.MOJO_RESULT_OK {
				t.Fatalf("can't read from a message pipe: %v", r)
			}
			r = h1.WriteMessage(bytes, handles, system.MOJO_WRITE_MESSAGE_FLAG_NONE)
			if r != system.MOJO_RESULT_OK {
				t.Fatalf("can't write to a message pipe: %v", r)
			}
		}
		wg.Done()
	}()
	// Send concurrent requests.
	for i := 0; i < numberOfRequests; i++ {
		go func(i int) {
			header := bindings.MessageHeader{0, bindings.MessageExpectsResponseFlag, uint64(i + 1)}
			err := (<-router.AcceptWithResponse(encodeMessage(header, &header))).Error
			if err != nil {
				panic(err)
			}
			wg.Done()
		}(i)
	}
	wg.Wait()
	router.Close()
}
Пример #24
0
// Invoke calls the mojom service based on the suffix and converts the mojom
// results (a struct) to Vanadium results (a slice of *vom.RawBytes).
// Note: The argptrs from Prepare are reused here. The vom bytes should have
// been decoded into these argptrs, so there are actual values inside now.
func (fs fakeService) Invoke(ctx *context.T, call rpc.StreamServerCall, method string, argptrs []interface{}) (results []interface{}, _ error) {
	// fs.suffix consists of the mojo url and the application/interface name.
	// The last part should be the name; everything else is the url.
	parts := strings.Split(fs.suffix, "/")
	mojourl := strings.Join(parts[:len(parts)-1], "/") // e.g., mojo:go_remote_echo_server. May be defined in a BUILD.gn file.
	mojoname := parts[len(parts)-1]                    // e.g., mojo::examples::RemoteEcho. Defined from the interface + module.

	// Create the generic message pipe. r is a bindings.InterfaceRequest, and
	// p is a bindings.InterfacePointer.
	r, p := bindings.CreateMessagePipeForMojoInterface()
	v := v23ServiceRequest{
		request: r,
		name:    mojoname,
	} // v is an application.ServiceRequest with mojoname

	// Connect to the mojourl.
	fs.appctx.ConnectToApplication(mojourl).ConnectToService(&v)

	// Then assign a new router the FakeService.
	// This will never conflict because each FakeService is only invoked once.
	fs.router = bindings.NewRouter(p.PassMessagePipe(), bindings.GetAsyncWaiter())
	defer fs.Close_Proxy()

	ctx.Infof("Fake Service Invoke (Remote Signature: %q -- %q)", mojourl, mojoname)

	// Vanadium relies on type information, so we will retrieve that first.
	mojomInterface, desc, err := fs.callRemoteSignature(mojourl, mojoname)
	if err != nil {
		return nil, err
	}

	ctx.Infof("Fake Service Invoke Signature %v", mojomInterface)
	ctx.Infof("Fake Service Invoke (Remote Method: %v)", method)

	// With the type information, we can make the method call to the remote interface.
	methodResults, err := fs.callRemoteMethod(ctx, method, mojomInterface, desc, argptrs)
	if err != nil {
		ctx.Errorf("Method called failed: %v", err)
		return nil, err
	}

	ctx.Infof("Fake Service Invoke Results %v", methodResults)

	// Convert methodResult to results.
	results = make([]interface{}, len(methodResults))
	for i := range methodResults {
		results[i] = &methodResults[i]
	}
	return results, nil
}
Пример #25
0
func (d *delegate) Initialize(ctx application.Context) {
	req, ptr := discovery.CreateMessagePipeForDiscovery()
	ctx.ConnectToApplication("https://mojo.v.io/discovery.mojo").ConnectToService(&req)

	scanHandlerReq, scanHandlerPtr := discovery.CreateMessagePipeForScanHandler()
	scanHandlerStub := discovery.NewScanHandlerStub(scanHandlerReq, &scanHandler{}, bindings.GetAsyncWaiter())

	dProxy := discovery.NewDiscoveryProxy(ptr, bindings.GetAsyncWaiter())
	closerPtr, e1, e2 := dProxy.Scan(`v.InterfaceName="v.io/discovery.T"`, scanHandlerPtr)
	if e1 != nil || e2 != nil {
		log.Printf("Failed to scan: %v, %v", e1, e2)
		scanHandlerStub.Close()
		dProxy.Close_Proxy()
		return
	}

	go func() {
		for {
			if err := scanHandlerStub.ServeRequest(); err != nil {
				connErr, ok := err.(*bindings.ConnectionError)
				if !ok || !connErr.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()

	d.stop = func() {
		cProxy := discovery.NewCloserProxy(*closerPtr, bindings.GetAsyncWaiter())
		cProxy.Close()
		cProxy.Close_Proxy()

		scanHandlerStub.Close()
		dProxy.Close_Proxy()
	}
}
Пример #26
0
func (pImpl *principalServiceImpl) Create(req vpkg.PrincipalService_Request) {
	stub := vpkg.NewPrincipalServiceStub(req, pImpl, bindings.GetAsyncWaiter())
	pImpl.psd.addStubForCleanup(stub)
	go func() {
		for {
			if err := stub.ServeRequest(); err != nil {
				connectionError, ok := err.(*bindings.ConnectionError)
				if !ok || !connectionError.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()
}
Пример #27
0
func (sd *ServiceDescriberFactory) Create(request service_describer.ServiceDescriber_Request) {
	stub := service_describer.NewServiceDescriberStub(request, sd, bindings.GetAsyncWaiter())
	sd.stubs = append(sd.stubs, stub)
	go func() {
		for {
			if err := stub.ServeRequest(); err != nil {
				connectionError, ok := err.(*bindings.ConnectionError)
				if !ok || !connectionError.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()
}
Пример #28
0
func (psd *principalServiceDelegate) getOAuth2Token() (string, error) {
	authReq, authPtr := auth.CreateMessagePipeForAuthenticationService()
	psd.Ctx.ConnectToApplication("mojo:authentication").ConnectToService(&authReq)
	authProxy := auth.NewAuthenticationServiceProxy(authPtr, bindings.GetAsyncWaiter())

	name, errString, _ := authProxy.SelectAccount(false /*return_last_selected*/)
	if name == nil {
		return "", fmt.Errorf("failed to select an account for user:%s", errString)
	}
	token, errString, _ := authProxy.GetOAuth2Token(*name, []string{"email"})
	if token == nil {
		return "", fmt.Errorf("failed to obtain OAuth2 token for selected account:%s", errString)
	}
	return *token, nil
}
Пример #29
0
func (delegate *EchoServerDelegate) Create(request echo.Echo_Request) {
	stub := echo.NewEchoStub(request, &EchoImpl{}, bindings.GetAsyncWaiter())
	delegate.stubs = append(delegate.stubs, stub)
	go func() {
		for {
			if err := stub.ServeRequest(); err != nil {
				connectionError, ok := err.(*bindings.ConnectionError)
				if !ok || !connectionError.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()
}
Пример #30
0
func (factory *V23ProxyTestFactory) Create(request end_to_end_test.V23ProxyTest_Request) {
	log.Printf("V23ProxyTestServer's V23ProxyTestFactory.Create...")
	stub := end_to_end_test.NewV23ProxyTestStub(request, factory.testImpl, bindings.GetAsyncWaiter())
	factory.stubs = append(factory.stubs, stub)
	go func() {
		for {
			if err := stub.ServeRequest(); err != nil {
				connectionError, ok := err.(*bindings.ConnectionError)
				if !ok || !connectionError.Closed() {
					log.Println(err)
				}
				break
			}
		}
	}()
}