Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 37 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,43 @@ gosec -exclude-dir=pkg/pb ./...

### Run
```bash
docker run -p 8080:3401 fasttrack/random grpc
docker run -p 8080:3401 -e SEED_HEX=0000000000000000000000000000000000000000000000000000000000000000 fasttrack/random grpc
```
```bash
docker run -p 8081:3402 fasttrack/random http
docker run -p 8081:3402 -e SEED_HEX=0000000000000000000000000000000000000000000000000000000000000000 fasttrack/random http
```

## Other

### Example HTTP Requests
```http
GET http://localhost:8081/getRandomFloat64
```
```http
GET http://localhost:8081/getRandomInt64?min=0&max=10

Querystring parameters:
min - minimum number (inclusive)
max - maximum number (inclusive)
```
```http
GET http://localhost:8081/getDeterministicRandom?s=42&p=0.01,0.4,0.59

Querystring parameters:
(s)equence - the sequence number of the random number
(p)robabilities - the set of probabilities to select an index from
```

### Generating a seed
There are several sites where a hex code can be generated.

Example: https://codebeautify.org/generate-random-hexadecimal-numbers

Simply set 'length of hex number' to 64 and generate one.

### Validating deterministic results
The results from function DeterministicRandom can be tested for consistency by using the simulator to generate results
and then hashing the result of two runs with the same parameters.
```bash
shasum -a 256 cmd/simulator/results/DeterministicRandom-X.csv
```
27 changes: 24 additions & 3 deletions cmd/grpc/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ import (
)

func main() {
seed := *config.SEEDHEX
if len(seed) != 64 {
panic("seed must be 64 hex characters")
} else if seed == "0000000000000000000000000000000000000000000000000000000000000000" {
panic("a unique seed value is required")
}

recoveryOpts := []grpc_recovery.Option{
grpc_recovery.WithRecoveryHandler(func(p interface{}) (err error) {
slog.Error("[PANIC] recovered panic", "error", p, "stacktrace", string(debug.Stack()))
Expand All @@ -37,7 +44,7 @@ func main() {

reflection.Register(s)

randomServer := NewRandomGRPCServer()
randomServer := NewRandomGRPCServer(seed)
pb.RegisterRandomServer(s, randomServer)

lis, errListen := net.Listen("tcp", fmt.Sprintf(":%v", *config.GRPCPort))
Expand All @@ -57,10 +64,13 @@ func main() {

type RandomGRPCServer struct {
pb.UnimplementedRandomServer
seed string
}

func NewRandomGRPCServer() *RandomGRPCServer {
return &RandomGRPCServer{}
func NewRandomGRPCServer(seed string) *RandomGRPCServer {
return &RandomGRPCServer{
seed: seed,
}
}

func (rs *RandomGRPCServer) GetRandomInt64(ctx context.Context, req *pb.GetRandomInt64Request) (*pb.GetRandomInt64Response, error) {
Expand Down Expand Up @@ -88,3 +98,14 @@ func (rs *RandomGRPCServer) GetRandomFloat64(ctx context.Context, req *pb.GetRan
Number: number,
}, nil
}

func (rs *RandomGRPCServer) GetDeterministicRandom(ctx context.Context, req *pb.GetDeterministicRandomRequest) (*pb.GetDeterministicRandomResponse, error) {
number, err := random.DeterministicRandom(rs.seed, req.Sequence, req.Probabilities)
if err != nil {
return nil, err
}

return &pb.GetDeterministicRandomResponse{
Number: number,
}, nil
}
69 changes: 68 additions & 1 deletion cmd/http/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,19 @@ import (
"math"
"net/http"
"strconv"
"strings"
"time"
)

func main() {
gin.SetMode(gin.ReleaseMode)
seed := *config.SEEDHEX
if len(seed) != 64 {
panic("seed must be 64 hex characters")
} else if seed == "0000000000000000000000000000000000000000000000000000000000000000" {
panic("a unique seed value is required")
}

gin.SetMode(gin.ReleaseMode)
ginEngine := gin.New()
ginEngine.Use(gin.Recovery())

Expand Down Expand Up @@ -94,6 +101,66 @@ func main() {
c.String(http.StatusOK, fmt.Sprintf("%v", number))
})

ginEngine.GET("/getDeterministicRandom", func(c *gin.Context) {
sequence := int64(0)
sequenceAsStr := c.Query("s")
if len(sequenceAsStr) == 0 {
c.String(http.StatusBadRequest, "sequence is missing")
c.Abort()
return
} else {
sequenceAsNumber, errParseInt := strconv.ParseInt(sequenceAsStr, 10, 64)
if errParseInt != nil {
c.String(http.StatusBadRequest, "unable to parse sequence as number")
c.Abort()
return
} else if sequenceAsNumber < 0 || sequenceAsNumber >= math.MaxInt64 {
c.String(http.StatusBadRequest, "sequence must be between 0 and 9,223,372,036,854,775,806")
c.Abort()
return
} else {
sequence = sequenceAsNumber
}
}

var probabilities []float64
probabilitiesAsStr := c.Query("p")
if len(probabilitiesAsStr) == 0 {
c.String(http.StatusBadRequest, "probabilities are missing")
c.Abort()
return
} else if len(probabilitiesAsStr) > 300 {
c.String(http.StatusBadRequest, "string of probabilities must be less than 300 characters")
c.Abort()
return
} else {
probabilitiesAsStrList := strings.Split(probabilitiesAsStr, ",")
if len(probabilitiesAsStrList) == 0 {
c.String(http.StatusBadRequest, "invalid probabilities, use comma separated list (i.e. 0.01,0.09,0.9")
c.Abort()
return
}

for _, v := range probabilitiesAsStrList {
probability, errParse := strconv.ParseFloat(strings.TrimSpace(v), 64)
if errParse != nil {
c.String(http.StatusBadRequest, fmt.Sprintf("invalid probability: %s", strings.TrimSpace(v)))
c.Abort()
return
}
probabilities = append(probabilities, probability)
}
}

number, errDeterministicRandom := random.DeterministicRandom(seed, sequence, probabilities)
if errDeterministicRandom != nil {
c.String(http.StatusBadRequest, errDeterministicRandom.Error())
c.Abort()
return
}
c.String(http.StatusOK, fmt.Sprintf("%v", number))
})

// start server
slog.Info(fmt.Sprintf("http server listening on %v", *config.HTTPPort))
errRun := ginEngine.Run(fmt.Sprintf(":%v", *config.HTTPPort))
Expand Down
Loading
Loading