varnishtest "shard director Restarts"

server s1 {
	rxreq
	txresp -body "ech3Ooj"
	accept
	rxreq
	txresp -body "ech3Ooj"
	accept
	rxreq
	txresp -body "ech3Ooj"
} -start

server s2 {
	rxreq
	txresp -body "ieQu2qua"
	accept
	rxreq
	txresp -body "ieQu2qua"
	accept
	rxreq
	txresp -body "ieQu2qua"
} -start

server s3 {
	rxreq
	txresp -body "xiuFi3Pe"
	accept
	rxreq
	txresp -body "xiuFi3Pe"
	accept
	rxreq
	txresp -body "xiuFi3Pe"
} -start

varnish v1 -vcl+backend {
	import directors;

	sub vcl_init {
		new vd = directors.shard();
		vd.add_backend(s1);
		vd.add_backend(s2);
		vd.add_backend(s3);
		vd.reconfigure(25);
	}

	sub vcl_backend_fetch {
		set bereq.http.Connection = "close";
	}

	sub vcl_recv {
		set req.backend_hint = vd.backend(by=KEY,
		    key=1756955383,
		    alt=req.restarts,
		    healthy=ALL);

		if (req.url == "/2" && req.restarts > 0) {
			unset req.http.vrstart;
		}
		if (req.url == "/3" && req.restarts > 1) {
			unset req.http.vrstart;
		}
		return(pass);
	}

	sub vcl_deliver {
		if (req.http.vrstart) {
			return(restart);
		}

		set resp.http.all-alt-0 = vd.backend(by=KEY, key=1756955383, alt=0, healthy=ALL);
		set resp.http.all-alt-1 = vd.backend(by=KEY, key=1756955383, alt=1, healthy=ALL);
		set resp.http.all-alt-2 = vd.backend(by=KEY, key=1756955383, alt=2, healthy=ALL);
		set resp.http.all-alt-3 = vd.backend(by=KEY, key=1756955383, alt=3, healthy=ALL);
		set resp.http.chosen-alt-0 = vd.backend(by=KEY, key=1756955383, alt=0, healthy=CHOSEN);
		set resp.http.chosen-alt-1 = vd.backend(by=KEY, key=1756955383, alt=1, healthy=CHOSEN);
		set resp.http.chosen-alt-2 = vd.backend(by=KEY, key=1756955383, alt=2, healthy=CHOSEN);
	}

} -start


client c1 {
	txreq -url /1
	rxresp
	expect resp.body == "ech3Ooj"
	expect resp.http.all-alt-0 == "s1"
	expect resp.http.all-alt-1 == "s2"
	expect resp.http.all-alt-2 == "s3"
	expect resp.http.all-alt-3 == resp.http.all-alt-2
	expect resp.http.chosen-alt-0 == "s1"
	expect resp.http.chosen-alt-1 == "s2"
	expect resp.http.chosen-alt-2 == "s3"

	txreq -url /2 -hdr "vrstart: 1"
	rxresp
	expect resp.body == "ieQu2qua"
	expect resp.http.all-alt-0 == "s1"
	expect resp.http.all-alt-1 == "s2"
	expect resp.http.all-alt-2 == "s3"
	expect resp.http.all-alt-3 == resp.http.all-alt-2
	expect resp.http.chosen-alt-0 == "s1"
	expect resp.http.chosen-alt-1 == "s2"
	expect resp.http.chosen-alt-2 == "s3"

	txreq -url /3 -hdr "vrstart: 1"
	rxresp
	expect resp.body == "xiuFi3Pe"
	expect resp.http.all-alt-0 == "s1"
	expect resp.http.all-alt-1 == "s2"
	expect resp.http.all-alt-2 == "s3"
	expect resp.http.all-alt-3 == resp.http.all-alt-2
	expect resp.http.chosen-alt-0 == "s1"
	expect resp.http.chosen-alt-1 == "s2"
	expect resp.http.chosen-alt-2 == "s3"
} -run
