103 lines
2.0 KiB
Go
103 lines
2.0 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"strconv"
|
|
"time"
|
|
|
|
"chronical/config"
|
|
|
|
"github.com/godruoyi/go-snowflake"
|
|
"github.com/gofiber/fiber/v2"
|
|
"golang.org/x/time/rate"
|
|
)
|
|
|
|
type SnowflakeResponse struct {
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
type MultipleSnowflakeResponse struct {
|
|
IDs []string `json:"ids"`
|
|
Count int `json:"count"`
|
|
}
|
|
|
|
type ErrorResponse struct {
|
|
Error string `json:"error"`
|
|
}
|
|
|
|
func RateLimit() fiber.Handler {
|
|
limiter := rate.NewLimiter(rate.Limit(4094), 4094)
|
|
|
|
return func(c *fiber.Ctx) error {
|
|
|
|
count := 1
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
|
defer cancel()
|
|
|
|
reservation := limiter.ReserveN(time.Now(), count)
|
|
if !reservation.OK() {
|
|
return c.Status(fiber.StatusTooManyRequests).JSON(ErrorResponse{
|
|
Error: "Rate limit exceeded. Server limited to 4094 IDs per second.",
|
|
})
|
|
}
|
|
|
|
delay := reservation.DelayFrom(time.Now())
|
|
if delay > 0 {
|
|
if delay > time.Second {
|
|
reservation.Cancel()
|
|
return c.Status(fiber.StatusTooManyRequests).JSON(ErrorResponse{
|
|
Error: "Rate limit exceeded. Server limited to 4094 IDs per second.",
|
|
})
|
|
}
|
|
|
|
select {
|
|
case <-time.After(delay):
|
|
|
|
case <-ctx.Done():
|
|
reservation.Cancel()
|
|
return c.Status(fiber.StatusTooManyRequests).JSON(ErrorResponse{
|
|
Error: "Rate limit exceeded. Request timeout.",
|
|
})
|
|
}
|
|
}
|
|
|
|
return c.Next()
|
|
}
|
|
}
|
|
|
|
func SnowflakeServer() {
|
|
app := fiber.New()
|
|
|
|
app.Use("/id", RateLimit())
|
|
|
|
app.Get("/", func(c *fiber.Ctx) error {
|
|
return c.JSON(fiber.Map{
|
|
"message": "Chronical Snowflake ID Service",
|
|
"endpoints": fiber.Map{
|
|
"single": "GET /id - Generate a single snowflake ID.",
|
|
},
|
|
})
|
|
})
|
|
|
|
app.Get("/id", func(c *fiber.Ctx) error {
|
|
snowflake.SetStartTime(time.Date(config.Epoch, 1, 1, 0, 0, 0, 0, time.UTC))
|
|
id := snowflake.ID()
|
|
return c.JSON(SnowflakeResponse{
|
|
ID: strconv.FormatUint(id, 10),
|
|
})
|
|
})
|
|
|
|
app.Get("/health", func(c *fiber.Ctx) error {
|
|
return c.JSON(fiber.Map{
|
|
"status": "healthy",
|
|
"service": "chronical",
|
|
})
|
|
})
|
|
|
|
err := app.Listen(":3000")
|
|
if err != nil {
|
|
return
|
|
}
|
|
}
|