package relay

import (
	
	

	amhelp 
	am 
	arpc 
	ssrpc 
	
)

// startArpcToDbg connects an aRPC client to the server and proxies the client's
// NetMach telemetry to am-dbg. The client is created without a local schema
// definition, so the remote schema (including relations) is synced from the
// aRPC server during the hello handshake.
func ( *Relay) (
	 context.Context,  *am.Event,  *types.ArgsArpcToDbg,
) {
	.out("connecting to aRPC %s, telemetry to %s\n", .RpcAddr, .DbgAddr)

	// no local schema, the remote one is synced via the hello handshake
	,  := arpc.NewClient(, .RpcAddr, "arpc-to-dbg", nil,
		&arpc.ClientOpts{
			Parent: .Mach,
			// prevent env-based auto-attach to AM_DBG_ADDR
			DebugDisable: true,
		})
	if  != nil {
		.Mach.EvAddErr(, , nil)
		return
	}
	.arpcClient = 

	.Start(nil)

	.Mach.Go(, func() {
		select {
		case <-.Mach.When1(ssrpc.ClientStates.Ready, ):
			if .Mach.Not1(ssrpc.ClientStates.Ready) {
				return // expired
			}
		case <-.Mach.When1(ssrpc.ClientStates.ConnRetryFailed, ):
			 := errors.New("aRPC connection failed")
			.Mach.EvAddErr(, , nil)
			.Mach.EvRemove1(, ssR.Start, nil)
			return
		case <-.Done():
			return
		}

		// Attach after the handshake, when the machines are idle: the NetMach
		// state names and schema are only populated then, and the dbg tracer
		// sends the schema once on MachineInit. This way am-dbg receives the
		// remote schema with rels. Attaching earlier would race with the
		// machines' queue processing.
		if .NetMach == nil {
			.Mach.EvAddErr(, errors.New("aRPC netmach missing"), nil)
			return
		}
		 := am.LogOps
		for ,  := range []am.Api{.Mach, .Mach, .NetMach} {
			if  := amhelp.MachDebug(, .DbgAddr, , false,
				amhelp.SemConfigEnv(true));  != nil {
				.Mach.EvAddErr(, , nil)
				return
			}
		}
		.out("connected, streaming telemetry to %s\n", .DbgAddr)
	})
}