VCL: Fastly integer Math


#1

Hi,
Is there a way to do simple math in fastly?

Example:
Received cookie = 10
New cookie to 10+8=18.

How can i declare an integer variable under req.http? I see that it allows only string variables to be declared.


#2

Hello! We are working on this right now. Give us a a month or so.


#3

Thank you Sean.
Meanwhile, i am using req.grace to do math on it and then restore the original value of grace. Only problem is that initial value i see is “inf”, which cannot be restored when there is no specific grace value set.

-Michael


#4

@sean
Do you have any updates on this?

  • Dominic

#5

Hey all - sorry for the delay. It is ready to deploy, just finishing up the documentation and some last minute testing (code is done) - so should be within a few weeks. Will post here when it’s live with a link to the docs.


#6

We need this as well, glad to see it’s around the corner! :slight_smile:


#7

Are there any updates here?


#8

Thank you. Its very handy now to use these new variables.


#9

Is it now possible to do additions and subtractions with integer local variables?


#10

You can (ab)use req.grace to do simple arithmetic:

# preserve req.grace
set req.http.VCL-grace = req.grace;

# addition
set req.grace = 400s;
set req.grace += 200s;
set req.http.VCL-sum = req.grace;
set req.http.VCL-sum = regsub(req.http.VCL-sum, "\..*", "");

# subtraction
set req.grace = 400s;
set req.grace -= 200s;
set req.http.VCL-difference = req.grace;
set req.http.VCL-difference = regsub(req.http.VCL-difference, "\..*", "");

# multiplication
set req.grace = 400s;
set req.grace *= 200;
set req.http.VCL-product = req.grace;
set req.http.VCL-product = regsub(req.http.VCL-product, "\..*", "");

# division
set req.grace = 400s;
set req.grace /= 200;
set req.http.VCL-quotient = req.grace;
set req.http.VCL-quotient = regsub(req.http.VCL-quotient, "\..*", "");

# dynamic input
set req.http.X-Some-Input = "500";
set req.grace = std.atoi(req.http.X-Some-Input);
set req.grace *= 2;
set req.http.VCL-product = req.grace;
set req.http.VCL-product = regsub(req.http.VCL-product, "\..*", "");

# time math
set req.grace = std.atoi(strftime({"%s"}, now));
set req.grace -= std.atoi(obj.entered);
set http.X-Object-Entered-Cache-Unix = req.grace;
set resp.http.X-Object-Entered-Cache-Unix = regsub(http.X-Object-Entered-Cache-Unix, "\..*", "");

# reset grace to its original value
set req.grace = std.atoi(req.http.VCL-grace);

If you need modulus you can use this formula: dividend-((dividend/divisor)*divisor)


#11

We recently added local variables to VCL, including numeric and time types, which make these kinds of calculations easy:

https://docs.fastly.com/guides/vcl/local-variables-in-vcl

Feel free to reach out if you have any questions.