vtest "shard director LAZY - directors_c00003.vtc"

server s1 -repeat 2 {
	rxreq
	txresp -body "ech3Ooj"
} -start

server s2 -repeat 2 {
	rxreq
	txresp -body "ieQu2qua"
} -start

server s3 -repeat 2 {
	rxreq
	txresp -body "xiuFi3Pe"
} -start

vinyl v1 -vcl+backend {
	import std;
	import directors;

	sub vcl_init {
	    new vd = directors.shard();
	    if (!vd.add_backend(s1)) {
		return(fail("add s1 failed"));
	    }
	    if (!vd.add_backend(s2)) {
		return(fail("add s2 failed"));
	    }
	    if (!vd.add_backend(s3)) {
		return(fail("add s3 failed"));
	    }
	    if (!vd.reconfigure(replicas=25)) {
		return(fail("reconfigure failed"));
	    }

	    vd.debug(1);

	    new p = directors.shard_param();
	    p.set(by=KEY, key=1);
	    vd.associate(p.use());

	    new p3 = directors.shard_param();
	    p3.set(by=KEY, key=4294967295);
	}

	sub vcl_recv {
	    if (req.http.pipe) {
		return (pipe);
	    }
	    return(pass);
	}

	sub shard_be {
	    set bereq.backend=vd.backend(resolve=LAZY);

	    if (bereq.url == "/1") {
		# default
	    } else
	    if (bereq.url == "/2") {
		# backend override parameter set
		p.set(by=KEY, key=2147483647);
	    } else
	    if (bereq.url == "/3") {
		# backend override association
		vd.backend(resolve=LAZY, param=p3.use());
	    }
	}

	sub vcl_backend_fetch {
	    call shard_be;
	}

	sub vcl_pipe {
	    call shard_be;
	}

	sub vcl_backend_response {
	    set beresp.http.backend = bereq.backend;
	}
} -start


client c1 {
	txreq -url /1
	rxresp
	expect resp.body == "ech3Ooj"
	expect resp.http.backend == "vd"

	txreq -url /2
	rxresp
	expect resp.body == "ieQu2qua"
	expect resp.http.backend == "vd"

	txreq -url /3
	rxresp
	expect resp.body == "xiuFi3Pe"
	expect resp.http.backend == "vd"
} -run

vinyl v1 -vsl_catchup

client c1 {
	txreq -url /1 -hdr "pipe: true"
	rxresp
	expect resp.body == "ech3Ooj"
} -run

client c1 {
	txreq -url /2 -hdr "pipe: true"
	rxresp
	expect resp.body == "ieQu2qua"
} -run

client c1 {
	txreq -url /3 -hdr "pipe: true"
	rxresp
	expect resp.body == "xiuFi3Pe"
} -run

server s1 -wait
server s2 -wait
server s3 -wait
