fermyon / spin-js-sdk

https://developer.fermyon.com/spin/javascript-components
Apache License 2.0
49 stars 17 forks source link

`Math.random()` always returns the same number, when using the `uuid` library and instantiating `uuidv4()` outside the handler function #215

Closed mikkelhegn closed 8 months ago

mikkelhegn commented 8 months ago

The code below result in Math.random() always returning the same number, on each request. Moving the constant requestId in to the handler function resolves it, so that Math.random() now returs a new number on each request.

import { HandleRequest, HttpRequest, HttpResponse } from "@fermyon/spin-sdk"
import { v4 as uuidv4 } from "uuid";

// Moving this inside the handler will solve the problem
const requestId = uuidv4()

export const handleRequest: HandleRequest = async function (request: HttpRequest): Promise<HttpResponse> {

  let number = Math.floor(Math.random() * 10)

  console.log(number)

  return {
    status: 200,
    headers: { "content-type": "text/plain" },
    body: JSON.stringify(number)
  }

}
ThorstenHans commented 8 months ago

I've tried the following, which also results in same values being returned for every execution:

let number = Math.floor(Math.random() * 10)

export const handleRequest: HandleRequest = async function (request: HttpRequest): Promise<HttpResponse> {
  const requestId = uuidv4()
  return {
    status: 200,
    headers: { "content-type": "text/plain" },
    body: JSON.stringify({ id: requestId, n: number})
  }
}

Even when I declare a variable outside the handler (either using Math.floor(Math.random() * 10) or uuidv4()) that is NOT used at all, it keeps on returning the same values across multiple requests:

let notUsedAtAll = Math.floor(Math.random() * 10) 

export const handleRequest: HandleRequest = async function (request: HttpRequest): Promise<HttpResponse> {
  const requestId = uuidv4()
  let number = Math.floor(Math.random() * 10) 
  return {
    status: 200,
    headers: { "content-type": "text/plain" },
    body: JSON.stringify({ id: requestId, n: number})
  }
}

However, defining a third variable, which is unrelated to some sort of randomness, it works as expected:

let bar = "baz"

export const handleRequest: HandleRequest = async function (request: HttpRequest): Promise<HttpResponse> {
  const requestId = uuidv4()
  let number = Math.floor(Math.random() * 10)

  return {
    status: 200,
    headers: { "content-type": "text/plain" },
    body: JSON.stringify({ id: requestId, n: number, foo: bar})
  }
}
dicej commented 8 months ago

This has the same underlying cause as https://github.com/fermyon/spin-python-sdk/issues/55, and will require the same solution. I'll open a PR later today.