Skip to content

Open-source status page, incident response and uptime monitoring

🚀 TCP New checker type (#982)

Thibault Le Ouay7c889a52c776
diff --git a/apps/checker/.golangci.yml b/apps/checker/.golangci.yml
new file mode 100644
index 000000000..8ce97c53b
--- /dev/null
+++ b/apps/checker/.golangci.yml
@@ -0,0 +1,4 @@
+linters:
+ enable-all: true
+ disable-all: false
+ fast: true
diff --git a/apps/checker/cmd/main.go b/apps/checker/cmd/main.go
index 121c61195..497f6fbfa 100644
--- a/apps/checker/cmd/main.go
+++ b/apps/checker/cmd/main.go
@@ -2,7 +2,6 @@ package main
import (
"context"
- "encoding/json"
"errors"
"fmt"
"net/http"
@@ -12,35 +11,13 @@ import (
"time"
"github.com/gin-gonic/gin"
- "github.com/openstatushq/openstatus/apps/checker"
- "github.com/openstatushq/openstatus/apps/checker/pkg/assertions"
+ "github.com/openstatushq/openstatus/apps/checker/handlers"
+
"github.com/openstatushq/openstatus/apps/checker/pkg/logger"
"github.com/openstatushq/openstatus/apps/checker/pkg/tinybird"
- "github.com/openstatushq/openstatus/apps/checker/request"
"github.com/rs/zerolog/log"
-
- backoff "github.com/cenkalti/backoff/v4"
)
-type statusCode int
-
-// We should export it
-type PingResponse struct {
- Body string `json:"body,omitempty"`
- Headers string `json:"headers,omitempty"`
- Region string `json:"region"`
- RequestId int64 `json:"requestId,omitempty"`
- WorkspaceId int64 `json:"workspaceId,omitempty"`
- Latency int64 `json:"latency"`
- Time int64 `json:"time"`
- Timing checker.Timing `json:"timing"`
- Status int `json:"status,omitempty"`
-}
-
-func (s statusCode) IsSuccessful() bool {
- return s >= 200 && s < 300
-}
-
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
@@ -71,274 +48,24 @@ func main() {
tinybirdClient := tinybird.NewClient(httpClient, tinyBirdToken)
- router := gin.New()
- router.POST("/checker", func(c *gin.Context) {
- ctx := c.Request.Context()
- dataSourceName := "ping_response__v8"
- if c.GetHeader("Authorization") != fmt.Sprintf("Basic %s", cronSecret) {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
- return
- }
-
- if cloudProvider == "fly" {
- // if the request has been routed to a wrong region, we forward it to the correct one.
- region := c.GetHeader("fly-prefer-region")
- if region != "" && region != flyRegion {
- c.Header("fly-replay", fmt.Sprintf("region=%s", region))
- c.String(http.StatusAccepted, "Forwarding request to %s", region)
- return
- }
- }
-
- var req request.CheckerRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to decode checker request")
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
- return
- }
- // We need a new client for each request to avoid connection reuse.
- requestClient := &http.Client{
- Timeout: time.Duration(req.Timeout) * time.Millisecond,
- }
- defer requestClient.CloseIdleConnections()
-
- // Might be a more efficient way to do it
- var i interface{} = req.RawAssertions
- jsonBytes, _ := json.Marshal(i)
- assertionAsString := string(jsonBytes)
- if assertionAsString == "null" {
- assertionAsString = ""
- }
-
- var called int
- op := func() error {
- called++
- res, err := checker.Ping(ctx, requestClient, req)
- if err != nil {
- return fmt.Errorf("unable to ping: %w", err)
- }
- statusCode := statusCode(res.StatusCode)
-
- var isSuccessfull bool = true
- if len(req.RawAssertions) > 0 {
- for _, a := range req.RawAssertions {
- var assert request.Assertion
- err = json.Unmarshal(a, &assert)
- if err != nil {
- // handle error
- return fmt.Errorf("unable to unmarshal assertion: %w", err)
- }
- switch assert.AssertionType {
- case request.AssertionHeader:
- var target assertions.HeaderTarget
- if err := json.Unmarshal(a, &target); err != nil {
- return fmt.Errorf("unable to unmarshal IntTarget: %w", err)
- }
- isSuccessfull = isSuccessfull && target.HeaderEvaluate(res.Headers)
-
- case request.AssertionTextBody:
- var target assertions.StringTargetType
- if err := json.Unmarshal(a, &target); err != nil {
- return fmt.Errorf("unable to unmarshal IntTarget: %w", err)
- }
- isSuccessfull = isSuccessfull && target.StringEvaluate(res.Body)
-
- case request.AssertionStatus:
- var target assertions.StatusTarget
- if err := json.Unmarshal(a, &target); err != nil {
- return fmt.Errorf("unable to unmarshal IntTarget: %w", err)
- }
- isSuccessfull = isSuccessfull && target.StatusEvaluate(int64(res.StatusCode))
- case request.AssertionJsonBody:
- fmt.Println("assertion type", assert.AssertionType)
- default:
- fmt.Println("⚠️ Not Handled assertion type", assert.AssertionType)
- }
- }
- } else {
- isSuccessfull = statusCode.IsSuccessful()
- }
-
- // let's retry at least once if the status code is not successful.
- if !isSuccessfull && called < 2 {
- return fmt.Errorf("unable to ping: %v with status %v", res, res.StatusCode)
- }
-
- // it's in error if not successful
- if isSuccessfull {
- res.Error = 0
- // Small trick to avoid sending the body at the moment to TB
- res.Body = ""
- } else {
- res.Error = 1
- }
-
- res.Assertions = assertionAsString
- // That part could be refactored
- if !isSuccessfull && req.Status == "active" {
- // Q: Why here we do not check if the status was previously active?
- checker.UpdateStatus(ctx, checker.UpdateData{
- MonitorId: req.MonitorID,
- Status: "error",
- StatusCode: res.StatusCode,
- Region: flyRegion,
- Message: res.Message,
- CronTimestamp: req.CronTimestamp,
- })
- }
- // Check if the status is degraded
- if isSuccessfull && req.Status == "active" {
- if req.DegradedAfter > 0 && res.Latency > req.DegradedAfter {
- checker.UpdateStatus(ctx, checker.UpdateData{
- MonitorId: req.MonitorID,
- Status: "degraded",
- Region: flyRegion,
- StatusCode: res.StatusCode,
- CronTimestamp: req.CronTimestamp,
- })
- }
- }
- // We were in error and now we are successful don't check for degraded
- if isSuccessfull && req.Status == "error" {
- // Q: Why here we check the data before updating the status in this scenario?
- checker.UpdateStatus(ctx, checker.UpdateData{
- MonitorId: req.MonitorID,
- Status: "active",
- Region: flyRegion,
- StatusCode: res.StatusCode,
- CronTimestamp: req.CronTimestamp,
- })
- }
- // if we were in degraded and now we are successful, we should update the status to active
- if isSuccessfull && req.Status == "degraded" {
- if req.DegradedAfter > 0 && res.Latency <= req.DegradedAfter {
- checker.UpdateStatus(ctx, checker.UpdateData{
- MonitorId: req.MonitorID,
- Status: "active",
- Region: flyRegion,
- StatusCode: res.StatusCode,
- CronTimestamp: req.CronTimestamp,
- })
- }
- }
-
- if err := tinybirdClient.SendEvent(ctx, res, dataSourceName); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
- }
-
- return nil
- }
-
- if err := backoff.Retry(op, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3)); err != nil {
- if err := tinybirdClient.SendEvent(ctx, checker.PingData{
- URL: req.URL,
- Region: flyRegion,
- Message: err.Error(),
- CronTimestamp: req.CronTimestamp,
- Timestamp: req.CronTimestamp,
- MonitorID: req.MonitorID,
- WorkspaceID: req.WorkspaceID,
- Error: 1,
- Assertions: assertionAsString,
- Body: "",
- }, dataSourceName); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
- }
-
- if req.Status == "active" {
- checker.UpdateStatus(ctx, checker.UpdateData{
- MonitorId: req.MonitorID,
- Status: "error",
- Message: err.Error(),
- Region: flyRegion,
- CronTimestamp: req.CronTimestamp,
- })
- }
-
- }
+ h := &handlers.Handler{
+ Secret: cronSecret,
+ CloudProvider: cloudProvider,
+ Region: flyRegion,
+ TbClient: tinybirdClient,
+ }
- c.JSON(http.StatusOK, gin.H{"message": "ok"})
- })
+ router := gin.New()
+ router.POST("/checker", h.HTTPCheckerHandler)
+ router.POST("/checker/http", h.HTTPCheckerHandler)
+ router.POST("/checker/tcp", h.TCPHandler)
+ router.POST("/ping/:region", h.PingRegionHandler)
+ router.POST("/tcp/:region", h.TCPHandlerRegion)
router.GET("/health", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "pong", "fly_region": flyRegion})
})
- router.POST("/ping/:region", func(c *gin.Context) {
- dataSourceName := "check_response__v1"
- region := c.Param("region")
- if region == "" {
- c.String(http.StatusBadRequest, "region is required")
- return
- }
- fmt.Printf("Start of /ping/%s\n", region)
-
- if c.GetHeader("Authorization") != fmt.Sprintf("Basic %s", cronSecret) {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
- return
- }
-
- if cloudProvider == "fly" {
-
- if region != flyRegion {
- c.Header("fly-replay", fmt.Sprintf("region=%s", region))
- c.String(http.StatusAccepted, "Forwarding request to %s", region)
- return
- }
- }
- // We need a new client for each request to avoid connection reuse.
- requestClient := &http.Client{
- Timeout: 45 * time.Second,
- }
- defer requestClient.CloseIdleConnections()
-
- var req request.PingRequest
- if err := c.ShouldBindJSON(&req); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to decode checker request")
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
- return
- }
- var res checker.Response
- op := func() error {
- r, err := checker.SinglePing(c.Request.Context(), requestClient, req)
- if err != nil {
- return fmt.Errorf("unable to ping: %w", err)
- }
-
- r.Region = flyRegion
-
- headersAsString, err := json.Marshal(r.Headers)
- if err != nil {
- return err
- }
-
- tbData := PingResponse{
- RequestId: req.RequestId,
- WorkspaceId: req.WorkspaceId,
- Status: r.Status,
- Latency: r.Latency,
- Body: r.Body,
- Headers: string(headersAsString),
- Time: r.Time,
- Timing: r.Timing,
- Region: r.Region,
- }
-
- res = r
- if tbData.RequestId != 0 {
- if err := tinybirdClient.SendEvent(ctx, tbData, dataSourceName); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
- }
- }
- return nil
- }
- if err := backoff.Retry(op, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3)); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
- return
- }
- c.JSON(http.StatusOK, res)
- })
-
httpServer := &http.Server{
Addr: fmt.Sprintf("0.0.0.0:%s", env("PORT", "8080")),
Handler: router,
@@ -354,6 +81,7 @@ func main() {
<-ctx.Done()
if err := httpServer.Shutdown(ctx); err != nil {
log.Ctx(ctx).Error().Err(err).Msg("failed to shutdown http server")
+
return
}
}
diff --git a/apps/checker/handlers/checker.go b/apps/checker/handlers/checker.go
new file mode 100644
index 000000000..e273cf53b
--- /dev/null
+++ b/apps/checker/handlers/checker.go
@@ -0,0 +1,262 @@
+package handlers
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/cenkalti/backoff/v4"
+ "github.com/gin-gonic/gin"
+ "github.com/openstatushq/openstatus/apps/checker"
+ "github.com/openstatushq/openstatus/apps/checker/pkg/assertions"
+ "github.com/openstatushq/openstatus/apps/checker/request"
+ "github.com/rs/zerolog/log"
+)
+
+type statusCode int
+
+func (s statusCode) IsSuccessful() bool {
+ return s >= 200 && s < 300
+}
+
+type PingData struct {
+ WorkspaceID string `json:"workspaceId"`
+ MonitorID string `json:"monitorId"`
+ URL string `json:"url"`
+ Region string `json:"region"`
+ Message string `json:"message,omitempty"`
+ Timing string `json:"timing,omitempty"`
+ Headers string `json:"headers,omitempty"`
+ Assertions string `json:"assertions"`
+ Body string `json:"body,omitempty"`
+ Latency int64 `json:"latency"`
+ CronTimestamp int64 `json:"cronTimestamp"`
+ Timestamp int64 `json:"timestamp"`
+ StatusCode int `json:"statusCode,omitempty"`
+ Error uint8 `json:"error"`
+}
+
+func (h Handler) HTTPCheckerHandler(c *gin.Context) {
+ ctx := c.Request.Context()
+ dataSourceName := "ping_response__v8"
+
+ if c.GetHeader("Authorization") != fmt.Sprintf("Basic %s", h.Secret) {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
+
+ return
+ }
+
+ if h.CloudProvider == "fly" {
+ // if the request has been routed to a wrong region, we forward it to the correct one.
+ region := c.GetHeader("fly-prefer-region")
+ if region != "" && region != h.Region {
+ c.Header("fly-replay", fmt.Sprintf("region=%s", region))
+ c.String(http.StatusAccepted, "Forwarding request to %s", region)
+
+ return
+ }
+ }
+
+ var req request.HttpCheckerRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to decode checker request")
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+
+ return
+ }
+ // We need a new client for each request to avoid connection reuse.
+ requestClient := &http.Client{
+ Timeout: time.Duration(req.Timeout) * time.Millisecond,
+ }
+ defer requestClient.CloseIdleConnections()
+
+ // Might be a more efficient way to do it
+ var i interface{} = req.RawAssertions
+ jsonBytes, _ := json.Marshal(i)
+ assertionAsString := string(jsonBytes)
+
+ if assertionAsString == "null" {
+ assertionAsString = ""
+ }
+
+ var called int
+ op := func() error {
+ called++
+ res, err := checker.Http(ctx, requestClient, req)
+
+ if err != nil {
+ return fmt.Errorf("unable to ping: %w", err)
+ }
+
+ // In TB we need to store them as string
+ timingAsString, err := json.Marshal(res.Timing)
+ if err != nil {
+ return fmt.Errorf("error while parsing timing data %s: %w", req.URL, err)
+ }
+
+ headersAsString, err := json.Marshal(res.Headers)
+ if err != nil {
+ return fmt.Errorf("error while parsing headers %s: %w", req.URL, err)
+ }
+
+ data := PingData{
+ Latency: res.Latency,
+ StatusCode: res.Status,
+ MonitorID: req.MonitorID,
+ Region: h.Region,
+ WorkspaceID: req.WorkspaceID,
+ Timestamp: res.Timestamp,
+ CronTimestamp: req.CronTimestamp,
+ URL: req.URL,
+ Timing: string(timingAsString),
+ Headers: string(headersAsString),
+ Body: string(res.Body),
+ }
+
+ statusCode := statusCode(res.Status)
+
+ var isSuccessfull bool = true
+
+ if len(req.RawAssertions) > 0 {
+ for _, a := range req.RawAssertions {
+ var assert request.Assertion
+ err = json.Unmarshal(a, &assert)
+
+ if err != nil {
+ // handle error
+ return fmt.Errorf("unable to unmarshal assertion: %w", err)
+ }
+
+ switch assert.AssertionType {
+ case request.AssertionHeader:
+ var target assertions.HeaderTarget
+ if err := json.Unmarshal(a, &target); err != nil {
+ return fmt.Errorf("unable to unmarshal IntTarget: %w", err)
+ }
+ isSuccessfull = isSuccessfull && target.HeaderEvaluate(data.Headers)
+
+ case request.AssertionTextBody:
+ var target assertions.StringTargetType
+ if err := json.Unmarshal(a, &target); err != nil {
+ return fmt.Errorf("unable to unmarshal IntTarget: %w", err)
+ }
+ isSuccessfull = isSuccessfull && target.StringEvaluate(data.Body)
+
+ case request.AssertionStatus:
+ var target assertions.StatusTarget
+ if err := json.Unmarshal(a, &target); err != nil {
+ return fmt.Errorf("unable to unmarshal IntTarget: %w", err)
+ }
+ isSuccessfull = isSuccessfull && target.StatusEvaluate(int64(res.Status))
+ case request.AssertionJsonBody:
+ fmt.Println("assertion type", assert.AssertionType)
+ default:
+ fmt.Println("! Not Handled assertion type", assert.AssertionType)
+ }
+ }
+ } else {
+ isSuccessfull = statusCode.IsSuccessful()
+ }
+
+ // let's retry at least once if the status code is not successful.
+ if !isSuccessfull && called < 2 {
+ return fmt.Errorf("unable to ping: %v with status %v", res, res.Status)
+ }
+
+ // it's in error if not successful
+ if isSuccessfull {
+ data.Error = 0
+ // Small trick to avoid sending the body at the moment to TB
+ data.Body = ""
+ } else {
+ data.Error = 1
+ }
+
+ data.Assertions = assertionAsString
+ // That part could be refactored
+ if !isSuccessfull && req.Status == "active" {
+ // Q: Why here we do not check if the status was previously active?
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "error",
+ StatusCode: res.Status,
+ Region: h.Region,
+ Message: res.Error,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+ // Check if the status is degraded
+ if isSuccessfull && req.Status == "active" {
+ if req.DegradedAfter > 0 && res.Latency > req.DegradedAfter {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "degraded",
+ Region: h.Region,
+ StatusCode: res.Status,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+ }
+ // We were in error and now we are successful don't check for degraded
+ if isSuccessfull && req.Status == "error" {
+ // Q: Why here we check the data before updating the status in this scenario?
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "active",
+ Region: h.Region,
+ StatusCode: res.Status,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+ // if we were in degraded and now we are successful, we should update the status to active
+ if isSuccessfull && req.Status == "degraded" {
+ if req.DegradedAfter > 0 && res.Latency <= req.DegradedAfter {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "active",
+ Region: h.Region,
+ StatusCode: res.Status,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+ }
+
+ if err := h.TbClient.SendEvent(ctx, data, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+
+ return nil
+ }
+
+ if err := backoff.Retry(op, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3)); err != nil {
+ if err := h.TbClient.SendEvent(ctx, PingData{
+ URL: req.URL,
+ Region: h.Region,
+ Message: err.Error(),
+ CronTimestamp: req.CronTimestamp,
+ Timestamp: req.CronTimestamp,
+ MonitorID: req.MonitorID,
+ WorkspaceID: req.WorkspaceID,
+ Error: 1,
+ Assertions: assertionAsString,
+ Body: "",
+ }, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+
+ if req.Status == "active" {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "error",
+ Message: err.Error(),
+ Region: h.Region,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+
+ }
+
+ c.JSON(http.StatusOK, gin.H{"message": "ok"})
+
+}
diff --git a/apps/checker/handlers/handler.go b/apps/checker/handlers/handler.go
new file mode 100644
index 000000000..7f475434d
--- /dev/null
+++ b/apps/checker/handlers/handler.go
@@ -0,0 +1,14 @@
+package handlers
+
+import (
+ "github.com/openstatushq/openstatus/apps/checker/pkg/tinybird"
+)
+
+type Handler struct {
+ TbClient tinybird.Client
+ Secret string
+ CloudProvider string
+ Region string
+}
+
+// Authorization could be handle by middleware
diff --git a/apps/checker/handlers/ping.go b/apps/checker/handlers/ping.go
new file mode 100644
index 000000000..22e77e15f
--- /dev/null
+++ b/apps/checker/handlers/ping.go
@@ -0,0 +1,148 @@
+package handlers
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/cenkalti/backoff/v4"
+ "github.com/gin-gonic/gin"
+ "github.com/openstatushq/openstatus/apps/checker"
+ "github.com/openstatushq/openstatus/apps/checker/request"
+ "github.com/rs/zerolog/log"
+)
+
+type PingResponse struct {
+ Body string `json:"body,omitempty"`
+ Headers string `json:"headers,omitempty"`
+ Region string `json:"region"`
+ RequestId int64 `json:"requestId,omitempty"`
+ WorkspaceId int64 `json:"workspaceId,omitempty"`
+ Latency int64 `json:"latency"`
+ Time int64 `json:"time"`
+ Status int `json:"status,omitempty"`
+ Timing checker.Timing `json:"timing"`
+}
+
+type Response struct {
+ Headers map[string]string `json:"headers,omitempty"`
+ Error string `json:"error,omitempty"`
+ Body string `json:"body,omitempty"`
+ Region string `json:"region"`
+ Tags []string `json:"tags,omitempty"`
+ RequestId int64 `json:"requestId,omitempty"`
+ WorkspaceId int64 `json:"workspaceId,omitempty"`
+ Latency int64 `json:"latency"`
+ Time int64 `json:"time"`
+ Timing checker.Timing `json:"timing"`
+ Status int `json:"status,omitempty"`
+}
+
+func (h Handler) PingRegionHandler(c *gin.Context) {
+ ctx := c.Request.Context()
+
+ dataSourceName := "check_response__v1"
+ region := c.Param("region")
+
+ if region == "" {
+ c.String(http.StatusBadRequest, "region is required")
+
+ return
+ }
+
+ fmt.Printf("Start of /ping/%s\n", region)
+
+ if c.GetHeader("Authorization") != fmt.Sprintf("Basic %s", h.Secret) {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
+
+ return
+ }
+
+ if h.CloudProvider == "fly" {
+ if region != h.Region {
+ c.Header("fly-replay", fmt.Sprintf("region=%s", region))
+ c.String(http.StatusAccepted, "Forwarding request to %s", region)
+
+ return
+ }
+ }
+
+ // We need a new client for each request to avoid connection reuse.
+ requestClient := &http.Client{
+ Timeout: 45 * time.Second,
+ }
+ defer requestClient.CloseIdleConnections()
+
+ var req request.PingRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to decode checker request")
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+
+ return
+ }
+
+ var res checker.Response
+
+ op := func() error {
+
+ headers := make([]struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+ }, 0)
+
+ for key, value := range req.Headers {
+ headers = append(headers, struct {
+ Key string `json:"key"`
+ Value string `json:"value"`
+ }{Key: key, Value: value})
+ }
+
+ input := request.HttpCheckerRequest{
+ Headers: headers,
+ URL: req.URL,
+ Method: req.Method,
+ Body: req.Body,
+ }
+
+ r, err := checker.Http(c.Request.Context(), requestClient, input)
+
+ if err != nil {
+ return fmt.Errorf("unable to ping: %w", err)
+ }
+
+ headersAsString, err := json.Marshal(r.Headers)
+ if err != nil {
+ return nil
+ }
+
+ tbData := PingResponse{
+ RequestId: req.RequestId,
+ WorkspaceId: req.WorkspaceId,
+ Status: r.Status,
+ Latency: r.Latency,
+ Body: r.Body,
+ Headers: string(headersAsString),
+ Time: r.Timestamp,
+ Timing: r.Timing,
+ Region: h.Region,
+ }
+
+ res = r
+
+ if tbData.RequestId != 0 {
+ if err := h.TbClient.SendEvent(ctx, tbData, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+ }
+
+ return nil
+ }
+ if err := backoff.Retry(op, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3)); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+
+ return
+ }
+
+ c.JSON(http.StatusOK, res)
+}
diff --git a/apps/checker/handlers/tcp.go b/apps/checker/handlers/tcp.go
new file mode 100644
index 000000000..16eb8aff8
--- /dev/null
+++ b/apps/checker/handlers/tcp.go
@@ -0,0 +1,218 @@
+package handlers
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/cenkalti/backoff/v4"
+ "github.com/gin-gonic/gin"
+ "github.com/openstatushq/openstatus/apps/checker"
+ "github.com/openstatushq/openstatus/apps/checker/request"
+ "github.com/rs/zerolog/log"
+)
+
+type TCPResponse struct {
+ Error string `json:"error,omitempty"`
+ Region string `json:"region"`
+ RequestId int64 `json:"requestId,omitempty"`
+ WorkspaceID int64 `json:"workspaceId"`
+ MonitorID int64 `json:"monitorId"`
+ Timestamp int64 `json:"timestamp"`
+ Timing checker.TCPResponseTiming `json:"timing"`
+}
+
+func (h Handler) TCPHandler(c *gin.Context) {
+ ctx := c.Request.Context()
+ dataSourceName := "tcp_response__v0"
+ if c.GetHeader("Authorization") != fmt.Sprintf("Basic %s", h.Secret) {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
+ return
+ }
+
+ if h.CloudProvider == "fly" {
+ // if the request has been routed to a wrong region, we forward it to the correct one.
+ region := c.GetHeader("fly-prefer-region")
+ if region != "" && region != h.Region {
+ c.Header("fly-replay", fmt.Sprintf("region=%s", region))
+ c.String(http.StatusAccepted, "Forwarding request to %s", region)
+ return
+ }
+ }
+ var req request.TCPCheckerRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to decode checker request")
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+ return
+ }
+ workspaceId, err := strconv.ParseInt(req.WorkspaceID, 10, 64)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+ return
+ }
+ monitorId, err := strconv.ParseInt(req.MonitorID, 10, 64)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+ return
+ }
+
+ var called int
+ op := func() error {
+ called++
+ res, err := checker.PingTcp(int(req.Timeout), req.URL)
+ if err != nil {
+ return fmt.Errorf("unable to check tcp %s", err)
+ }
+
+ r := TCPResponse{
+ WorkspaceID: workspaceId,
+ Timestamp: req.CronTimestamp,
+ Timing: checker.TCPResponseTiming{
+ TCPStart: res.TCPStart,
+ TCPDone: res.TCPDone,
+ },
+ Region: h.Region,
+ MonitorID: monitorId,
+ }
+ latency := res.TCPDone - res.TCPStart
+ if req.Status == "active" && req.DegradedAfter > 0 && latency > req.DegradedAfter {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "degraded",
+ Region: h.Region,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+ if req.Status == "degraded" && req.DegradedAfter > 0 && latency <= req.DegradedAfter {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "active",
+ Region: h.Region,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+
+ if req.Status == "error" {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "active",
+ Region: h.Region,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+
+ if err := h.TbClient.SendEvent(ctx, r, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+
+ return nil
+ }
+
+ if err := backoff.Retry(op, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3)); err != nil {
+ if err := h.TbClient.SendEvent(ctx, TCPResponse{
+ WorkspaceID: workspaceId,
+ Timestamp: req.CronTimestamp,
+ Error: err.Error(),
+ Region: h.Region,
+ MonitorID: monitorId,
+ }, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+
+ if req.Status == "active" {
+ checker.UpdateStatus(ctx, checker.UpdateData{
+ MonitorId: req.MonitorID,
+ Status: "error",
+ Message: err.Error(),
+ Region: h.Region,
+ CronTimestamp: req.CronTimestamp,
+ })
+ }
+ }
+ c.JSON(http.StatusOK, gin.H{"message": "ok"})
+}
+
+func (h Handler) TCPHandlerRegion(c *gin.Context) {
+ ctx := c.Request.Context()
+ dataSourceName := "check_tcp_response__v1"
+
+ region := c.Param("region")
+ if region == "" {
+ c.String(http.StatusBadRequest, "region is required")
+ return
+ }
+
+ if c.GetHeader("Authorization") != fmt.Sprintf("Basic %s", h.Secret) {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
+ return
+ }
+
+ if h.CloudProvider == "fly" {
+ // if the request has been routed to a wrong region, we forward it to the correct one.
+ region := c.GetHeader("fly-prefer-region")
+ if region != "" && region != h.Region {
+ c.Header("fly-replay", fmt.Sprintf("region=%s", region))
+ c.String(http.StatusAccepted, "Forwarding request to %s", region)
+ return
+ }
+ }
+ var req request.TCPCheckerRequest
+ if err := c.ShouldBindJSON(&req); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to decode checker request")
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+ return
+ }
+
+ workspaceId, err := strconv.ParseInt(req.WorkspaceID, 10, 64)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+ return
+ }
+ monitorId, err := strconv.ParseInt(req.MonitorID, 10, 64)
+ if err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
+ return
+ }
+
+ var called int
+ var response TCPResponse
+ op := func() error {
+ called++
+ res, err := checker.PingTcp(int(req.Timeout), req.URL)
+ if err != nil {
+ return fmt.Errorf("unable to check tcp %s", err)
+ }
+
+ response = TCPResponse{
+ WorkspaceID: workspaceId,
+ Timestamp: req.CronTimestamp,
+ Timing: checker.TCPResponseTiming{
+ TCPStart: res.TCPStart,
+ TCPDone: res.TCPDone,
+ },
+ Region: h.Region,
+ MonitorID: monitorId,
+ }
+
+ if req.RequestId != 0 {
+ if err := h.TbClient.SendEvent(ctx, response, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+ }
+
+ return nil
+ }
+
+ if err := backoff.Retry(op, backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 3)); err != nil {
+ if err := h.TbClient.SendEvent(ctx, TCPResponse{
+ WorkspaceID: workspaceId,
+ Timestamp: req.CronTimestamp,
+ Error: err.Error(),
+ Region: h.Region,
+ MonitorID: monitorId,
+ }, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+ }
+ c.JSON(http.StatusOK, response)
+}
diff --git a/apps/checker/http.go b/apps/checker/http.go
new file mode 100644
index 000000000..84ca6ae1b
--- /dev/null
+++ b/apps/checker/http.go
@@ -0,0 +1,155 @@
+package checker
+
+import (
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptrace"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/openstatushq/openstatus/apps/checker/request"
+ "github.com/rs/zerolog/log"
+)
+
+type Timing struct {
+ DnsStart int64 `json:"dnsStart"`
+ DnsDone int64 `json:"dnsDone"`
+ ConnectStart int64 `json:"connectStart"`
+ ConnectDone int64 `json:"connectDone"`
+ TlsHandshakeStart int64 `json:"tlsHandshakeStart"`
+ TlsHandshakeDone int64 `json:"tlsHandshakeDone"`
+ FirstByteStart int64 `json:"firstByteStart"`
+ FirstByteDone int64 `json:"firstByteDone"`
+ TransferStart int64 `json:"transferStart"`
+ TransferDone int64 `json:"transferDone"`
+}
+
+type Response struct {
+ Headers map[string]string `json:"headers,omitempty"`
+ Body string `json:"body,omitempty"`
+ Error string `json:"error,omitempty"`
+ Latency int64 `json:"latency"`
+ Timestamp int64 `json:"timestamp"`
+ Status int `json:"status,omitempty"`
+ Timing Timing `json:"timing"`
+}
+
+// FIXME: This should only return the TCP Timing Data;
+func Http(ctx context.Context, client *http.Client, inputData request.HttpCheckerRequest) (Response, error) {
+ logger := log.Ctx(ctx).With().Str("monitor", inputData.URL).Logger()
+
+ b := []byte(inputData.Body)
+ if inputData.Method == http.MethodPost {
+ for _, header := range inputData.Headers {
+ if header.Key == "Content-Type" && header.Value == "application/octet-stream" {
+ // split the body by comma and convert it to bytes it's data url base64
+ data := strings.Split(inputData.Body, ",")
+ if len(data) == 2 {
+ decoded, err := base64.StdEncoding.DecodeString(data[1])
+ if err != nil {
+ return Response{}, fmt.Errorf("error while decoding base64: %w", err)
+ }
+
+ b = decoded
+
+ }
+ }
+ }
+ }
+
+ req, err := http.NewRequestWithContext(ctx, inputData.Method, inputData.URL, bytes.NewReader(b))
+ if err != nil {
+ logger.Error().Err(err).Msg("error while creating req")
+ return Response{}, fmt.Errorf("unable to create req: %w", err)
+ }
+ req.Header.Set("User-Agent", "OpenStatus/1.0")
+ for _, header := range inputData.Headers {
+ if header.Key != "" {
+ req.Header.Set(header.Key, header.Value)
+ }
+ }
+
+ if inputData.Method != http.MethodGet {
+ head := req.Header
+ _, ok := head["Content-Type"]
+ if !ok {
+ // by default we set the content type to application/json if it's a POST request
+ req.Header.Set("Content-Type", "application/json")
+ }
+ }
+
+ timing := Timing{}
+
+ trace := &httptrace.ClientTrace{
+ DNSStart: func(_ httptrace.DNSStartInfo) { timing.DnsStart = time.Now().UTC().UnixMilli() },
+ DNSDone: func(_ httptrace.DNSDoneInfo) { timing.DnsDone = time.Now().UTC().UnixMilli() },
+ ConnectStart: func(_, _ string) { timing.ConnectStart = time.Now().UTC().UnixMilli() },
+ ConnectDone: func(_, _ string, _ error) { timing.ConnectDone = time.Now().UTC().UnixMilli() },
+ TLSHandshakeStart: func() { timing.TlsHandshakeStart = time.Now().UTC().UnixMilli() },
+ TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { timing.TlsHandshakeDone = time.Now().UTC().UnixMilli() },
+ GotConn: func(_ httptrace.GotConnInfo) {
+ timing.FirstByteStart = time.Now().UTC().UnixMilli()
+ },
+ GotFirstResponseByte: func() {
+ timing.FirstByteDone = time.Now().UTC().UnixMilli()
+ timing.TransferStart = time.Now().UTC().UnixMilli()
+ },
+ }
+
+ req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
+
+ start := time.Now()
+
+ response, err := client.Do(req)
+ timing.TransferDone = time.Now().UTC().UnixMilli()
+ latency := time.Since(start).Milliseconds()
+ if err != nil {
+
+ var urlErr *url.Error
+ if errors.As(err, &urlErr) && urlErr.Timeout() {
+ return Response{
+ Latency: latency,
+ Timing: timing,
+ Timestamp: start.UTC().UnixMilli(),
+ Error: fmt.Sprintf("Timeout after %d ms", latency),
+ }, nil
+ }
+
+ logger.Error().Err(err).Msg("error while pinging")
+
+ return Response{}, fmt.Errorf("error with monitorURL %s: %w", inputData.URL, err)
+ }
+ defer response.Body.Close()
+
+ body, err := io.ReadAll(response.Body)
+ if err != nil {
+ return Response{
+ Latency: latency,
+ Timing: timing,
+ Timestamp: start.UTC().UnixMilli(),
+ Error: fmt.Sprintf("Cannot read response body: %s", err.Error()),
+ }, fmt.Errorf("error with monitorURL %s: %w", inputData.URL, err)
+ }
+
+ headers := make(map[string]string)
+ for key := range response.Header {
+ headers[key] = response.Header.Get(key)
+ }
+
+ return Response{
+ Timestamp: start.UTC().UnixMilli(),
+ Status: response.StatusCode,
+ Headers: headers,
+ Timing: timing,
+ Latency: latency,
+ Body: string(body),
+ }, nil
+
+}
diff --git a/apps/checker/ping_test.go b/apps/checker/http_test.go
similarity index 50%
rename from apps/checker/ping_test.go
rename to apps/checker/http_test.go
index e858cce23..664b23637 100644
--- a/apps/checker/ping_test.go
+++ b/apps/checker/http_test.go
@@ -1,46 +1,47 @@
-package checker
+package checker_test
import (
"context"
"net/http"
"testing"
+ "github.com/openstatushq/openstatus/apps/checker"
"github.com/openstatushq/openstatus/apps/checker/request"
)
func Test_ping(t *testing.T) {
type args struct {
client *http.Client
- inputData request.CheckerRequest
+ inputData request.HttpCheckerRequest
}
tests := []struct {
name string
args args
- want PingData
+ want checker.Response
wantErr bool
}{
- {name: "200", args: args{client: &http.Client{}, inputData: request.CheckerRequest{URL: "https://openstat.us", CronTimestamp: 1, Headers: []struct {
+ {name: "200", args: args{client: &http.Client{}, inputData: request.HttpCheckerRequest{URL: "https://openstat.us", CronTimestamp: 1, Headers: []struct {
Key string `json:"key"`
Value string `json:"value"`
- }{{Key: "", Value: ""}}}}, want: PingData{URL: "https://openstat.us", StatusCode: 200}, wantErr: false},
- {name: "200", args: args{client: &http.Client{}, inputData: request.CheckerRequest{URL: "https://openstat.us", CronTimestamp: 1, Headers: []struct {
+ }{{Key: "", Value: ""}}}}, want: checker.Response{Status: 200}, wantErr: false},
+ {name: "200", args: args{client: &http.Client{}, inputData: request.HttpCheckerRequest{URL: "https://openstat.us", CronTimestamp: 1, Headers: []struct {
Key string `json:"key"`
Value string `json:"value"`
- }{{Key: "Test", Value: ""}}}}, want: PingData{URL: "https://openstat.us", StatusCode: 200}, wantErr: false},
- {name: "500", args: args{client: &http.Client{}, inputData: request.CheckerRequest{URL: "https://openstat.us/500", CronTimestamp: 1}}, want: PingData{URL: "https://openstat.us/500", StatusCode: 500}, wantErr: false},
- {name: "500", args: args{client: &http.Client{}, inputData: request.CheckerRequest{URL: "https://somethingthatwillfail.ed", CronTimestamp: 1}}, want: PingData{URL: "https://openstat.us/500", StatusCode: 0}, wantErr: true},
+ }{{Key: "Test", Value: ""}}}}, want: checker.Response{Status: 200}, wantErr: false},
+ {name: "500", args: args{client: &http.Client{}, inputData: request.HttpCheckerRequest{URL: "https://openstat.us/500", CronTimestamp: 1}}, want: checker.Response{Status: 500}, wantErr: false},
+ {name: "500", args: args{client: &http.Client{}, inputData: request.HttpCheckerRequest{URL: "https://somethingthatwillfail.ed", CronTimestamp: 1}}, want: checker.Response{Status: 0}, wantErr: true},
// TODO: Add test cases.
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- got, err := Ping(context.Background(), tt.args.client, tt.args.inputData)
+ got, err := checker.Http(context.Background(), tt.args.client, tt.args.inputData)
if (err != nil) != tt.wantErr {
t.Errorf("Ping() error = %v, wantErr %v", err, tt.wantErr)
return
}
- if got.StatusCode != tt.want.StatusCode {
+ if got.Status != tt.want.Status {
t.Errorf("Ping() = %v, want %v", got, tt.want)
}
})
diff --git a/apps/checker/ping.go b/apps/checker/ping.go
deleted file mode 100644
index 70506ca53..000000000
--- a/apps/checker/ping.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package checker
-
-import (
- "bytes"
- "context"
- "crypto/tls"
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "net/http/httptrace"
- "net/url"
- "os"
- "strings"
- "time"
-
- "github.com/openstatushq/openstatus/apps/checker/request"
- "github.com/rs/zerolog/log"
-)
-
-type PingData struct {
- WorkspaceID string `json:"workspaceId"`
- MonitorID string `json:"monitorId"`
- URL string `json:"url"`
- Region string `json:"region"`
- Message string `json:"message,omitempty"`
- Timing string `json:"timing,omitempty"`
- Headers string `json:"headers,omitempty"`
- Assertions string `json:"assertions"`
- Body string `json:"body,omitempty"`
- Latency int64 `json:"latency"`
- CronTimestamp int64 `json:"cronTimestamp"`
- Timestamp int64 `json:"timestamp"`
- StatusCode int `json:"statusCode,omitempty"`
- Error uint8 `json:"error"`
-}
-
-type Timing struct {
- DnsStart int64 `json:"dnsStart"`
- DnsDone int64 `json:"dnsDone"`
- ConnectStart int64 `json:"connectStart"`
- ConnectDone int64 `json:"connectDone"`
- TlsHandshakeStart int64 `json:"tlsHandshakeStart"`
- TlsHandshakeDone int64 `json:"tlsHandshakeDone"`
- FirstByteStart int64 `json:"firstByteStart"`
- FirstByteDone int64 `json:"firstByteDone"`
- TransferStart int64 `json:"transferStart"`
- TransferDone int64 `json:"transferDone"`
-}
-
-type Response struct {
- Headers map[string]string `json:"headers,omitempty"`
- Error string `json:"error,omitempty"`
- Body string `json:"body,omitempty"`
- Region string `json:"region"`
- Tags []string `json:"tags,omitempty"`
- RequestId int64 `json:"requestId,omitempty"`
- WorkspaceId int64 `json:"workspaceId,omitempty"`
- Latency int64 `json:"latency"`
- Time int64 `json:"time"`
- Timing Timing `json:"timing"`
- Status int `json:"status,omitempty"`
-}
-
-func Ping(ctx context.Context, client *http.Client, inputData request.CheckerRequest) (PingData, error) {
- logger := log.Ctx(ctx).With().Str("monitor", inputData.URL).Logger()
- region := os.Getenv("FLY_REGION")
-
- b := []byte(inputData.Body)
- if inputData.Method == http.MethodPost {
- for _, header := range inputData.Headers {
- if header.Key == "Content-Type" && header.Value == "application/octet-stream" {
-
- // split the body by comma and convert it to bytes
- data := strings.Split(inputData.Body, ",")
- if len(data) == 2 {
-
- decoded, err := base64.StdEncoding.DecodeString(data[1])
- if err != nil {
- return PingData{}, fmt.Errorf("error while decoding base64: %w", err)
- }
-
- b = decoded
-
- }
- }
- }
- }
-
- req, err := http.NewRequestWithContext(ctx, inputData.Method, inputData.URL, bytes.NewReader(b))
- if err != nil {
- logger.Error().Err(err).Msg("error while creating req")
- return PingData{}, fmt.Errorf("unable to create req: %w", err)
- }
- req.Header.Set("User-Agent", "OpenStatus/1.0")
- for _, header := range inputData.Headers {
- if header.Key != "" {
- req.Header.Set(header.Key, header.Value)
- }
- }
- if inputData.Method != http.MethodGet {
- head := req.Header
- _, ok := head["Content-Type"]
- if !ok {
- // by default we set the content type to application/json if it's a POST request
- req.Header.Set("Content-Type", "application/json")
- }
- }
-
- timing := Timing{}
-
- trace := &httptrace.ClientTrace{
- DNSStart: func(_ httptrace.DNSStartInfo) { timing.DnsStart = time.Now().UTC().UnixMilli() },
- DNSDone: func(_ httptrace.DNSDoneInfo) { timing.DnsDone = time.Now().UTC().UnixMilli() },
- ConnectStart: func(_, _ string) { timing.ConnectStart = time.Now().UTC().UnixMilli() },
- ConnectDone: func(_, _ string, _ error) { timing.ConnectDone = time.Now().UTC().UnixMilli() },
- TLSHandshakeStart: func() { timing.TlsHandshakeStart = time.Now().UTC().UnixMilli() },
- TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { timing.TlsHandshakeDone = time.Now().UTC().UnixMilli() },
- GotConn: func(_ httptrace.GotConnInfo) {
- timing.FirstByteStart = time.Now().UTC().UnixMilli()
- },
- GotFirstResponseByte: func() {
- timing.FirstByteDone = time.Now().UTC().UnixMilli()
- timing.TransferStart = time.Now().UTC().UnixMilli()
- },
- }
-
- req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
-
- start := time.Now()
-
- response, err := client.Do(req)
- timing.TransferDone = time.Now().UTC().UnixMilli()
- latency := time.Since(start).Milliseconds()
- if err != nil {
- timingAsString, err2 := json.Marshal(timing)
- if err2 != nil {
- logger.Error().Err(err2).Msg("error while parsing timing data")
- }
- var urlErr *url.Error
- if errors.As(err, &urlErr) && urlErr.Timeout() {
- return PingData{
- Latency: latency,
- MonitorID: inputData.MonitorID,
- Region: region,
- WorkspaceID: inputData.WorkspaceID,
- Timestamp: start.UTC().UnixMilli(),
- CronTimestamp: inputData.CronTimestamp,
- URL: inputData.URL,
- Message: fmt.Sprintf("Timeout after %d ms", latency),
- Timing: string(timingAsString),
- }, nil
- }
-
- logger.Error().Err(err).Msg("error while pinging")
- return PingData{}, fmt.Errorf("error with monitorURL %s: %w", inputData.URL, err)
- }
- defer response.Body.Close()
-
- body, err := io.ReadAll(response.Body)
- if err != nil {
- return PingData{
- Latency: latency,
- MonitorID: inputData.MonitorID,
- Region: region,
- WorkspaceID: inputData.WorkspaceID,
- Timestamp: start.UTC().UnixMilli(),
- CronTimestamp: inputData.CronTimestamp,
- URL: inputData.URL,
- Message: fmt.Sprintf("Cannot read response body: %s", err.Error()),
- }, fmt.Errorf("error with monitorURL %s: %w", inputData.URL, err)
- }
-
- headers := make(map[string]string)
- for key := range response.Header {
- headers[key] = response.Header.Get(key)
- }
-
- // In TB we need to store them as string
- timingAsString, err := json.Marshal(timing)
- if err != nil {
- return PingData{}, fmt.Errorf("error while parsing timing data %s: %w", inputData.URL, err)
- }
-
- headersAsString, err := json.Marshal(headers)
- if err != nil {
- return PingData{}, fmt.Errorf("error while parsing headers %s: %w", inputData.URL, err)
- }
-
- return PingData{
- Latency: latency,
- StatusCode: response.StatusCode,
- MonitorID: inputData.MonitorID,
- Region: region,
- WorkspaceID: inputData.WorkspaceID,
- Timestamp: start.UTC().UnixMilli(),
- CronTimestamp: inputData.CronTimestamp,
- URL: inputData.URL,
- Timing: string(timingAsString),
- Headers: string(headersAsString),
- Body: string(body),
- }, nil
-}
-
-func SinglePing(ctx context.Context, client *http.Client, inputData request.PingRequest) (Response, error) {
- logger := log.Ctx(ctx).With().Str("monitor", inputData.URL).Logger()
-
- b := []byte(inputData.Body)
- if inputData.Headers["Content-Type"] == "application/octet-stream" {
-
- // split the body by comma and convert it to bytes
- data := strings.Split(inputData.Body, ",")
- if len(data) == 2 {
-
- decoded, err := base64.StdEncoding.DecodeString(data[1])
- if err != nil {
- return Response{}, fmt.Errorf("error while decoding base64: %w", err)
- }
-
- b = decoded
-
- }
- }
-
- req, err := http.NewRequestWithContext(ctx, inputData.Method, inputData.URL, bytes.NewReader(b))
- if err != nil {
- logger.Error().Err(err).Msg("error while creating req")
- return Response{}, fmt.Errorf("unable to create req: %w", err)
- }
-
- req.Header.Set("User-Agent", "OpenStatus/1.0")
- for key, value := range inputData.Headers {
- req.Header.Set(key, value)
- }
-
- if inputData.Method != http.MethodGet {
- head := req.Header
- _, ok := head["Content-Type"]
- if !ok {
- // by default we set the content type to application/json if it's a POST request
- req.Header.Set("Content-Type", "application/json")
- }
- // if the content type is octet-stream, we need to set the body as bytes
-
- }
-
- timing := Timing{}
-
- trace := &httptrace.ClientTrace{
- DNSStart: func(_ httptrace.DNSStartInfo) { timing.DnsStart = time.Now().UTC().UnixMilli() },
- DNSDone: func(_ httptrace.DNSDoneInfo) { timing.DnsDone = time.Now().UTC().UnixMilli() },
- ConnectStart: func(_, _ string) { timing.ConnectStart = time.Now().UTC().UnixMilli() },
- ConnectDone: func(_, _ string, _ error) { timing.ConnectDone = time.Now().UTC().UnixMilli() },
- TLSHandshakeStart: func() { timing.TlsHandshakeStart = time.Now().UTC().UnixMilli() },
- TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { timing.TlsHandshakeDone = time.Now().UTC().UnixMilli() },
- GotConn: func(_ httptrace.GotConnInfo) {
- timing.FirstByteStart = time.Now().UTC().UnixMilli()
- },
- GotFirstResponseByte: func() {
- timing.FirstByteDone = time.Now().UTC().UnixMilli()
- timing.TransferStart = time.Now().UTC().UnixMilli()
- },
- }
-
- req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
-
- start := time.Now()
- res, err := client.Do(req)
- timing.TransferDone = time.Now().UTC().UnixMilli()
- latency := time.Since(start).Milliseconds()
-
- if err != nil {
- var urlErr *url.Error
- if errors.As(err, &urlErr) && urlErr.Timeout() {
- return Response{
- Latency: latency,
- Timing: timing,
- Time: start.UTC().UnixMilli(),
- Error: fmt.Sprintf("Timeout after %d ms", latency),
- }, nil
- }
-
- logger.Error().Err(err).Msg("error while pinging")
- return Response{}, fmt.Errorf("error with monitorURL %s: %w", inputData.URL, err)
- }
- defer res.Body.Close()
- body, err := io.ReadAll(res.Body)
-
- if err != nil {
- return Response{
- Latency: latency,
- Timing: timing,
- Time: start.UTC().UnixMilli(),
- Error: fmt.Sprintf("Cannot read response body: %s", err.Error()),
- }, fmt.Errorf("error with monitorURL %s: %w", inputData.URL, err)
- }
-
- headers := make(map[string]string)
- for key := range res.Header {
- headers[key] = res.Header.Get(key)
- }
-
- return Response{
- Time: start.UTC().UnixMilli(),
- Status: res.StatusCode,
- Headers: headers,
- Timing: timing,
- Latency: latency,
- Body: string(body),
- }, nil
-}
diff --git a/apps/checker/request/request.go b/apps/checker/request/request.go
index c59b967b8..1bb338f54 100644
--- a/apps/checker/request/request.go
+++ b/apps/checker/request/request.go
@@ -45,7 +45,7 @@ type Assertion struct {
RawTarget json.RawMessage `json:"target"`
}
-type CheckerRequest struct {
+type HttpCheckerRequest struct {
Headers []struct {
Key string `json:"key"`
Value string `json:"value"`
@@ -62,6 +62,26 @@ type CheckerRequest struct {
DegradedAfter int64 `json:"degradedAfter,omitempty"`
}
+type TCPCheckerRequest struct {
+ Status string `json:"status"`
+ WorkspaceID string `json:"workspaceId"`
+ URL string `json:"url"`
+ MonitorID string `json:"monitorId"`
+ RawAssertions []json.RawMessage `json:"assertions,omitempty"`
+ RequestId int64 `json:"requestId,omitempty"`
+ CronTimestamp int64 `json:"cronTimestamp"`
+ Timeout int64 `json:"timeout"`
+ DegradedAfter int64 `json:"degradedAfter,omitempty"`
+}
+
+type TCPRequest struct {
+ WorkspaceID string `json:"workspaceId"`
+ URL string `json:"url"`
+ MonitorID string `json:"monitorId"`
+ CronTimestamp int64 `json:"cronTimestamp"`
+ Timeout int64 `json:"timeout"`
+}
+
type PingRequest struct {
Headers map[string]string `json:"headers"`
URL string `json:"url"`
diff --git a/apps/checker/tcp.go b/apps/checker/tcp.go
new file mode 100644
index 000000000..b097f9e95
--- /dev/null
+++ b/apps/checker/tcp.go
@@ -0,0 +1,38 @@
+package checker
+
+import (
+ "fmt"
+ "net"
+ "strings"
+ "time"
+)
+
+type TCPData struct {
+ WorkspaceID string `json:"workspaceId"`
+ MonitorID string `json:"monitorId"`
+ Timestamp int64 `json:"timestamp"`
+}
+
+type TCPResponseTiming struct {
+ TCPStart int64 `json:"tcpStart"`
+ TCPDone int64 `json:"tcpDone"`
+}
+
+func PingTcp(timeout int, url string) (TCPResponseTiming, error) {
+ start := time.Now().UTC().UnixMilli()
+ conn, err := net.DialTimeout("tcp", url, time.Duration(timeout)*time.Second)
+
+ if err != nil {
+ if e := err.(*net.OpError).Timeout(); e {
+ return TCPResponseTiming{}, fmt.Errorf("timeout after %d ms", timeout*1000)
+ }
+ if strings.Contains(err.Error(), "connection refused") {
+ return TCPResponseTiming{}, fmt.Errorf("connection refused")
+ }
+ return TCPResponseTiming{}, fmt.Errorf("dial error: %v", err)
+ }
+ stop := time.Now().UTC().UnixMilli()
+ defer conn.Close()
+
+ return TCPResponseTiming{TCPStart: start, TCPDone: stop}, nil
+}
diff --git a/apps/checker/tcp_test.go b/apps/checker/tcp_test.go
new file mode 100644
index 000000000..a2439d70f
--- /dev/null
+++ b/apps/checker/tcp_test.go
@@ -0,0 +1,41 @@
+package checker_test
+
+import (
+ "testing"
+
+ "github.com/openstatushq/openstatus/apps/checker"
+)
+
+func TestPingTcp(t *testing.T) {
+ type args struct {
+ url string
+ timeout int
+ }
+ tests := []struct {
+ name string
+ args args
+ want checker.TCPResponseTiming
+ wantErr bool
+ }{
+ {name: "will failed", args: args{url: "error", timeout: 60}, wantErr: true},
+ {name: "will be ok", args: args{url: "openstat.us:443", timeout: 60}, wantErr: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got, err := checker.PingTcp(tt.args.timeout, tt.args.url)
+ if (err != nil) != tt.wantErr {
+ t.Errorf("PingTcp() error = %v, wantErr %v", err, tt.wantErr)
+ return
+ }
+ if got.TCPStart == 0 && tt.wantErr == false {
+ t.Errorf("PingTcp() = %v", got)
+ return
+ }
+ if got.TCPDone == 0 && tt.wantErr == false {
+ t.Errorf("PingTcp() = %v", got)
+ return
+ }
+
+ })
+ }
+}
diff --git a/apps/web/src/app/api/checker/cron/_cron.ts b/apps/web/src/app/api/checker/cron/_cron.ts
index 8f7cdc478..2e3e8c8ac 100644
--- a/apps/web/src/app/api/checker/cron/_cron.ts
+++ b/apps/web/src/app/api/checker/cron/_cron.ts
@@ -168,7 +168,7 @@ const createCronTask = async ({
Authorization: `Basic ${env.CRON_SECRET}`,
},
httpMethod: "POST",
- url: `https://openstatus-checker.fly.dev/checker?monitor_id=${row.id}`,
+ url: generateUrl({ row }),
body: Buffer.from(JSON.stringify(payload)).toString("base64"),
},
scheduleTime: {
@@ -179,3 +179,16 @@ const createCronTask = async ({
const request = { parent: parent, task: newTask };
return client.createTask(request);
};
+
+function generateUrl({ row }: { row: z.infer<typeof selectMonitorSchema> }) {
+ switch (row.jobType) {
+ case "http":
+ // FIXME: remove this after the migration
+ case "other":
+ return `https://openstatus-checker.fly.dev/checker/http?monitor_id=${row.id}`;
+ case "tcp":
+ return `https://openstatus-checker.fly.dev/checker/tcp?monitor_id=${row.id}`;
+ default:
+ throw new Error("Invalid jobType");
+ }
+}
diff --git a/apps/web/src/app/api/checker/test/http/route.ts b/apps/web/src/app/api/checker/test/http/route.ts
new file mode 100644
index 000000000..43bd0f3bf
--- /dev/null
+++ b/apps/web/src/app/api/checker/test/http/route.ts
@@ -0,0 +1,44 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import { monitorFlyRegionSchema } from "@openstatus/db/src/schema/constants";
+
+import { checkRegion } from "@/components/ping-response-analysis/utils";
+import { payloadSchema } from "../../schema";
+import { isAnInvalidTestUrl } from "../../utils";
+
+export const runtime = "edge";
+export const preferredRegion = "auto";
+export const dynamic = "force-dynamic";
+export const revalidate = 0;
+
+export function GET() {
+ return NextResponse.json({ success: true });
+}
+
+export async function POST(request: Request) {
+ try {
+ const json = await request.json();
+ const _valid = payloadSchema
+ .pick({ url: true, method: true, headers: true, body: true })
+ .merge(z.object({ region: monitorFlyRegionSchema.default("ams") }))
+ .safeParse(json);
+
+ if (!_valid.success) {
+ return NextResponse.json({ success: false }, { status: 400 });
+ }
+
+ const { url, region, method, headers, body } = _valid.data;
+ // 🧑‍💻 for the smart one who want to create a loop hole
+ if (isAnInvalidTestUrl(url)) {
+ return NextResponse.json({ success: true }, { status: 200 });
+ }
+
+ const res = await checkRegion(url, region, { method, headers, body });
+
+ return NextResponse.json(res);
+ } catch (e) {
+ console.error(e);
+ return NextResponse.json({ success: false }, { status: 400 });
+ }
+}
diff --git a/apps/web/src/app/api/checker/test/tcp/route.ts b/apps/web/src/app/api/checker/test/tcp/route.ts
new file mode 100644
index 000000000..df8abd299
--- /dev/null
+++ b/apps/web/src/app/api/checker/test/tcp/route.ts
@@ -0,0 +1,69 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import {
+ type MonitorFlyRegion,
+ monitorFlyRegionSchema,
+} from "@openstatus/db/src/schema/constants";
+
+import { TCPResponse, tcpPayload } from "./schema";
+
+export const runtime = "edge";
+export const preferredRegion = "auto";
+export const dynamic = "force-dynamic";
+export const revalidate = 0;
+
+export function GET() {
+ return NextResponse.json({ success: true });
+}
+
+export async function POST(request: Request) {
+ try {
+ const json = await request.json();
+ const _valid = tcpPayload
+ .merge(z.object({ region: monitorFlyRegionSchema.default("ams") }))
+ .safeParse(json);
+
+ if (!_valid.success) {
+ return NextResponse.json({ success: false }, { status: 400 });
+ }
+
+ const { url, region } = _valid.data;
+
+ const res = await checkTCP(url, region);
+
+ return NextResponse.json(res);
+ } catch (e) {
+ console.error(e);
+ return NextResponse.json({ success: false }, { status: 400 });
+ }
+}
+async function checkTCP(url: string, region: MonitorFlyRegion) {
+ //
+ const res = await fetch(`https://checker.openstatus.dev/ping/tcp/${region}`, {
+ headers: {
+ Authorization: `Basic ${process.env.CRON_SECRET}`,
+ "Content-Type": "application/json",
+ "fly-prefer-region": region,
+ },
+ method: "POST",
+ body: JSON.stringify({
+ url,
+ }),
+ next: { revalidate: 0 },
+ });
+
+ const json = await res.json();
+
+ const data = TCPResponse.safeParse(json);
+
+ if (!data.success) {
+ console.log(json);
+ console.error(
+ `something went wrong with result ${json} request to ${url} error ${data.error.message}`,
+ );
+ throw new Error(data.error.message);
+ }
+
+ return data.data;
+}
diff --git a/apps/web/src/app/api/checker/test/tcp/schema.ts b/apps/web/src/app/api/checker/test/tcp/schema.ts
new file mode 100644
index 000000000..af234693a
--- /dev/null
+++ b/apps/web/src/app/api/checker/test/tcp/schema.ts
@@ -0,0 +1,27 @@
+import { z } from "zod";
+
+import { monitorFlyRegionSchema } from "@openstatus/db/src/schema/constants";
+
+export const tcpPayload = z.object({
+ workspaceId: z.string(),
+ monitorId: z.string(),
+ url: z.string(),
+ cronTimestamp: z.number(),
+ timeout: z.number().default(45000),
+ degradedAfter: z.number().nullable(),
+});
+
+export const TCPResponse = z.object({
+ requestId: z.string().optional(),
+ workspaceId: z.string(),
+ monitorId: z.string(),
+ timestamp: z.number(),
+ timing: z.object({
+ tcpStart: z.number(),
+ tcpDone: z.number(),
+ }),
+ error: z.string().optional(),
+ region: monitorFlyRegionSchema,
+});
+
+export type tcpPayload = z.infer<typeof tcpPayload>;
diff --git a/apps/web/src/components/forms/monitor/form.tsx b/apps/web/src/components/forms/monitor/form.tsx
index 3a4d15903..0ad1890ce 100644
--- a/apps/web/src/components/forms/monitor/form.tsx
+++ b/apps/web/src/components/forms/monitor/form.tsx
@@ -97,12 +97,17 @@ export function MonitorForm({
) as any, // TS considers a.type === "textBody"
degradedAfter: defaultValues?.degradedAfter,
timeout: defaultValues?.timeout || 45000,
+ jobType: defaultValues?.jobType || "http",
},
});
const router = useRouter();
const pathname = usePathname();
const [isPending, setPending] = React.useState(false);
const [pingFailed, setPingFailed] = React.useState(false);
+ const type = React.useMemo(
+ () => (defaultValues ? "update" : "create"),
+ [defaultValues],
+ );
const handleDataUpdateOrInsertion = async (props: InsertMonitor) => {
if (defaultValues) {
@@ -176,8 +181,13 @@ export function MonitorForm({
statusAssertions,
headerAssertions,
textBodyAssertions,
+ jobType,
} = form.getValues();
+ // FIXME: add support for TCP
+ if (jobType !== "http")
+ return { error: "Only HTTP tests are supported. Coming soon..." };
+
if (
body &&
body !== "" &&
@@ -311,7 +321,7 @@ export function MonitorForm({
) : null}
</TabsList>
<TabsContent value="request">
- <SectionRequests {...{ form, pingEndpoint }} />
+ <SectionRequests {...{ form, pingEndpoint, type }} />
</TabsContent>
<TabsContent value="assertions">
<SectionAssertions {...{ form }} />
diff --git a/apps/web/src/components/forms/monitor/general.tsx b/apps/web/src/components/forms/monitor/general.tsx
index dc64eeb73..b0a9bfeb3 100644
--- a/apps/web/src/components/forms/monitor/general.tsx
+++ b/apps/web/src/components/forms/monitor/general.tsx
@@ -83,7 +83,7 @@ export function General({ form, tags }: Props) {
/>
</FormControl>
<FormDescription>
- Easily categorize your monitors.
+ Categorize your monitors. Create new tags by typing a name.
</FormDescription>
<FormMessage />
</FormItem>
diff --git a/apps/web/src/components/forms/monitor/section-assertions.tsx b/apps/web/src/components/forms/monitor/section-assertions.tsx
index a6f88b79b..7179e889c 100644
--- a/apps/web/src/components/forms/monitor/section-assertions.tsx
+++ b/apps/web/src/components/forms/monitor/section-assertions.tsx
@@ -25,6 +25,7 @@ import {
SelectValue,
} from "@openstatus/ui";
+import { EmptyState } from "@/components/dashboard/empty-state";
import { Icons } from "@/components/icons";
import { SectionHeader } from "../shared/section-header";
@@ -39,6 +40,9 @@ interface Props {
form: UseFormReturn<InsertMonitor>;
}
+// REMINDER: once we have different types of assertions based on different jobTypes
+// we shoulds start creating a mapping function with allowed assertions for each jobType
+
export function SectionAssertions({ form }: Props) {
const statusAssertions = useFieldArray({
control: form.control,
@@ -132,216 +136,224 @@ export function SectionAssertions({ form }: Props) {
</>
}
/>
- <div className="flex flex-col gap-4">
- {statusAssertions.fields.map((f, i) => (
- <div key={f.id} className="grid grid-cols-12 items-center gap-4">
- <p className="col-span-2 text-muted-foreground text-sm">
- Status Code
- </p>
- <div className="col-span-3" />
- <FormField
- control={form.control}
- name={`statusAssertions.${i}.compare`}
- render={({ field }) => (
- <FormItem className="col-span-3 w-full">
- <Select
- onValueChange={field.onChange}
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue defaultValue="eq" placeholder="Equal" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {Object.entries(numberCompareDictionary).map(
- ([key, value]) => (
- <SelectItem key={key} value={key}>
- {value}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
- <Input
- {...form.register(`statusAssertions.${i}.target`, {
- required: true,
- valueAsNumber: true,
- validate: (value) =>
- value <= 599 || "Value must be 599 or lower",
- })}
- type="number"
- placeholder="200"
- className="col-span-3"
- />
- <div className="col-span-1">
- <Button
- size="icon"
- onClick={() => statusAssertions.remove(i)}
- variant="ghost"
- type="button"
- >
- <Icons.trash className="h-4 w-4" />
- </Button>
+ {form.getValues("jobType") === "http" ? (
+ <div className="flex flex-col gap-4">
+ {statusAssertions.fields.map((f, i) => (
+ <div key={f.id} className="grid grid-cols-12 items-center gap-4">
+ <p className="col-span-2 text-muted-foreground text-sm">
+ Status Code
+ </p>
+ <div className="col-span-3" />
+ <FormField
+ control={form.control}
+ name={`statusAssertions.${i}.compare`}
+ render={({ field }) => (
+ <FormItem className="col-span-3 w-full">
+ <Select
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue defaultValue="eq" placeholder="Equal" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {Object.entries(numberCompareDictionary).map(
+ ([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </FormItem>
+ )}
+ />
+ <Input
+ {...form.register(`statusAssertions.${i}.target`, {
+ required: true,
+ valueAsNumber: true,
+ validate: (value) =>
+ value <= 599 || "Value must be 599 or lower",
+ })}
+ type="number"
+ placeholder="200"
+ className="col-span-3"
+ />
+ <div className="col-span-1">
+ <Button
+ size="icon"
+ onClick={() => statusAssertions.remove(i)}
+ variant="ghost"
+ type="button"
+ >
+ <Icons.trash className="h-4 w-4" />
+ </Button>
+ </div>
</div>
- </div>
- ))}
- {headerAssertions.fields.map((f, i) => (
- <div key={f.id} className="grid grid-cols-12 items-center gap-4">
- <p className="col-span-2 text-muted-foreground text-sm">
- Response Header
- </p>
- <Input
- {...form.register(`headerAssertions.${i}.key`, {
- required: true,
- setValueAs: setEmptyOrStr,
- })}
- className="col-span-3"
- placeholder="X-Header"
- />
- <FormField
- control={form.control}
- name={`headerAssertions.${i}.compare`}
- render={({ field }) => (
- <FormItem className="col-span-3 w-full">
- <Select
- onValueChange={field.onChange}
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue defaultValue="eq" placeholder="Equal" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {Object.entries(stringCompareDictionary).map(
- ([key, value]) => (
- <SelectItem key={key} value={key}>
- {value}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
- <Input
- {...form.register(`headerAssertions.${i}.target`)}
- className="col-span-3"
- placeholder="x-value"
- />
- <div className="col-span-1">
- <Button
- size="icon"
- onClick={() => headerAssertions.remove(i)}
- variant="ghost"
- >
- <Icons.trash className="h-4 w-4" />
- </Button>
+ ))}
+ {headerAssertions.fields.map((f, i) => (
+ <div key={f.id} className="grid grid-cols-12 items-center gap-4">
+ <p className="col-span-2 text-muted-foreground text-sm">
+ Response Header
+ </p>
+ <Input
+ {...form.register(`headerAssertions.${i}.key`, {
+ required: true,
+ setValueAs: setEmptyOrStr,
+ })}
+ className="col-span-3"
+ placeholder="X-Header"
+ />
+ <FormField
+ control={form.control}
+ name={`headerAssertions.${i}.compare`}
+ render={({ field }) => (
+ <FormItem className="col-span-3 w-full">
+ <Select
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue defaultValue="eq" placeholder="Equal" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {Object.entries(stringCompareDictionary).map(
+ ([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </FormItem>
+ )}
+ />
+ <Input
+ {...form.register(`headerAssertions.${i}.target`)}
+ className="col-span-3"
+ placeholder="x-value"
+ />
+ <div className="col-span-1">
+ <Button
+ size="icon"
+ onClick={() => headerAssertions.remove(i)}
+ variant="ghost"
+ >
+ <Icons.trash className="h-4 w-4" />
+ </Button>
+ </div>
</div>
- </div>
- ))}
- {textBodyAssertions.fields.map((f, i) => (
- <div key={f.id} className="grid grid-cols-12 items-center gap-4">
- <p className="col-span-2 text-muted-foreground text-sm">Body</p>
- <div className="col-span-3" />
- <FormField
- control={form.control}
- name={`textBodyAssertions.${i}.compare`}
- render={({ field }) => (
- <FormItem className="col-span-3 w-full">
- <Select
- onValueChange={field.onChange}
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue defaultValue="eq" placeholder="Equal" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {Object.entries(stringCompareDictionary).map(
- ([key, value]) => (
- <SelectItem key={key} value={key}>
- {value}
- </SelectItem>
- ),
- )}
- </SelectContent>
- </Select>
- </FormItem>
- )}
- />
- <Input
- {...form.register(`textBodyAssertions.${i}.target`, {
- required: true,
- })}
- placeholder="<html>...</html>"
- className="col-span-3"
- />
- <div className="col-span-1">
- <Button
- size="icon"
- onClick={() => textBodyAssertions.remove(i)}
- variant="ghost"
- type="button"
- >
- <Icons.trash className="h-4 w-4" />
- </Button>
+ ))}
+ {textBodyAssertions.fields.map((f, i) => (
+ <div key={f.id} className="grid grid-cols-12 items-center gap-4">
+ <p className="col-span-2 text-muted-foreground text-sm">Body</p>
+ <div className="col-span-3" />
+ <FormField
+ control={form.control}
+ name={`textBodyAssertions.${i}.compare`}
+ render={({ field }) => (
+ <FormItem className="col-span-3 w-full">
+ <Select
+ onValueChange={field.onChange}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue defaultValue="eq" placeholder="Equal" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {Object.entries(stringCompareDictionary).map(
+ ([key, value]) => (
+ <SelectItem key={key} value={key}>
+ {value}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+ </FormItem>
+ )}
+ />
+ <Input
+ {...form.register(`textBodyAssertions.${i}.target`, {
+ required: true,
+ })}
+ placeholder="<html>...</html>"
+ className="col-span-3"
+ />
+ <div className="col-span-1">
+ <Button
+ size="icon"
+ onClick={() => textBodyAssertions.remove(i)}
+ variant="ghost"
+ type="button"
+ >
+ <Icons.trash className="h-4 w-4" />
+ </Button>
+ </div>
</div>
- </div>
- ))}
- <div className="flex flex-wrap gap-4">
- <Button
- variant="outline"
- type="button"
- onClick={() =>
- statusAssertions.append({
- version: "v1",
- type: "status",
- compare: "eq",
- target: 200,
- })
- }
- >
- Add Status Code Assertion
- </Button>
- <Button
- variant="outline"
- type="button"
- onClick={() =>
- headerAssertions.append({
- version: "v1",
- type: "header",
- key: "Content-Type",
- compare: "eq",
- target: "application/json",
- })
- }
- >
- Add Header Assertion
- </Button>
+ ))}
+ <div className="flex flex-wrap gap-4">
+ <Button
+ variant="outline"
+ type="button"
+ onClick={() =>
+ statusAssertions.append({
+ version: "v1",
+ type: "status",
+ compare: "eq",
+ target: 200,
+ })
+ }
+ >
+ Add Status Code Assertion
+ </Button>
+ <Button
+ variant="outline"
+ type="button"
+ onClick={() =>
+ headerAssertions.append({
+ version: "v1",
+ type: "header",
+ key: "Content-Type",
+ compare: "eq",
+ target: "application/json",
+ })
+ }
+ >
+ Add Header Assertion
+ </Button>
- <Button
- variant="outline"
- type="button"
- onClick={() =>
- textBodyAssertions.append({
- version: "v1",
- type: "textBody",
- compare: "eq",
- target: "",
- })
- }
- >
- Add String Body Assertion
- </Button>
+ <Button
+ variant="outline"
+ type="button"
+ onClick={() =>
+ textBodyAssertions.append({
+ version: "v1",
+ type: "textBody",
+ compare: "eq",
+ target: "",
+ })
+ }
+ >
+ Add String Body Assertion
+ </Button>
+ </div>
</div>
- </div>
+ ) : (
+ <EmptyState
+ icon="alert-triangle"
+ title="No Assertions"
+ description="Assertions are only available for HTTP monitors."
+ />
+ )}
</div>
);
}
diff --git a/apps/web/src/components/forms/monitor/section-request-http.tsx b/apps/web/src/components/forms/monitor/section-request-http.tsx
new file mode 100644
index 000000000..85bf538d9
--- /dev/null
+++ b/apps/web/src/components/forms/monitor/section-request-http.tsx
@@ -0,0 +1,331 @@
+"use client";
+
+import { Wand2, X } from "lucide-react";
+import type * as React from "react";
+import { useFieldArray } from "react-hook-form";
+import type { UseFormReturn } from "react-hook-form";
+
+import {
+ monitorMethods,
+ monitorMethodsSchema,
+} from "@openstatus/db/src/schema";
+import type { InsertMonitor } from "@openstatus/db/src/schema";
+import {
+ Button,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+ Input,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ Textarea,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@openstatus/ui";
+
+import { toast } from "@/lib/toast";
+import { useRef, useState } from "react";
+
+const contentTypes = [
+ { value: "application/octet-stream", label: "Binary File" },
+ { value: "application/json", label: "JSON" },
+ { value: "application/xml", label: "XML" },
+ { value: "application/yaml", label: "YAML" },
+ { value: "application/edn", label: "EDN" },
+ { value: "application/other", label: "Other" },
+ { value: "none", label: "None" },
+];
+
+interface Props {
+ form: UseFormReturn<InsertMonitor>;
+}
+
+// TODO: add Dialog with response informations when pingEndpoint!
+
+export function SectionRequestHTTP({ form }: Props) {
+ const { fields, append, prepend, remove, update } = useFieldArray({
+ name: "headers",
+ control: form.control,
+ });
+ const inputRef = useRef<HTMLInputElement>(null);
+ const watchMethod = form.watch("method");
+ const [file, setFile] = useState<string | undefined>(undefined);
+ const [content, setContent] = useState<string | undefined>(
+ fields.find((field) => field.key === "Content-Type")?.value,
+ );
+
+ const validateJSON = (value?: string) => {
+ if (!value) return;
+ try {
+ const obj = JSON.parse(value) as Record<string, unknown>;
+ form.clearErrors("body");
+ return obj;
+ } catch (_e) {
+ form.setError("body", {
+ message: "Not a valid JSON object",
+ });
+ return false;
+ }
+ };
+
+ const uploadFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
+ if (event.target.files?.[0]) {
+ const file = event.target.files[0];
+
+ // File too big, return error
+ const fileSize = file.size / 1024 / 1024; // in MiB
+ if (fileSize > 10) {
+ // Display error message
+ toast.error("File size is too big. Max 10MB allowed.");
+ return;
+ }
+
+ const reader = new FileReader();
+ reader.onload = (event) => {
+ if (event.target?.result && typeof event.target.result === "string") {
+ form.setValue("body", event.target?.result);
+ setFile(file.name);
+ }
+ };
+
+ reader.readAsDataURL(file);
+ }
+ };
+
+ const onPrettifyJSON = () => {
+ const body = form.getValues("body");
+ const obj = validateJSON(body);
+ if (obj) {
+ const pretty = JSON.stringify(obj, undefined, 4);
+ form.setValue("body", pretty);
+ }
+ };
+
+ return (
+ <div className="grid w-full gap-4">
+ <div className="grid gap-4 sm:grid-cols-7">
+ <FormField
+ control={form.control}
+ name="method"
+ render={({ field }) => (
+ <FormItem className="sm:col-span-1">
+ <FormLabel>Method</FormLabel>
+ <Select
+ onValueChange={(value) => {
+ field.onChange(monitorMethodsSchema.parse(value));
+ form.resetField("body", { defaultValue: "" });
+ setContent(undefined);
+ }}
+ defaultValue={field.value}
+ >
+ <FormControl>
+ <SelectTrigger>
+ <SelectValue placeholder="Select" />
+ </SelectTrigger>
+ </FormControl>
+ <SelectContent>
+ {monitorMethods.map((method) => (
+ <SelectItem key={method} value={method}>
+ {method}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="url"
+ render={({ field }) => (
+ <FormItem className="sm:col-span-6">
+ <FormLabel>URL</FormLabel>
+ <FormControl>
+ <Input
+ className="bg-muted"
+ placeholder="https://documenso.com/api/health"
+ {...field}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ </div>
+ <div className="space-y-2 sm:col-span-full">
+ <FormLabel>Request Header</FormLabel>
+ {fields.map((field, index) => (
+ <div key={field.id} className="grid grid-cols-6 gap-4">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.key`}
+ render={({ field }) => (
+ <FormItem className="col-span-2">
+ <FormControl>
+ <Input placeholder="key" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <div className="col-span-4 flex items-center space-x-2">
+ <FormField
+ control={form.control}
+ name={`headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem className="w-full">
+ <FormControl>
+ <Input placeholder="value" {...field} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+ <Button
+ size="icon"
+ variant="ghost"
+ type="button"
+ onClick={() => remove(index)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ <div>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => append({ key: "", value: "" })}
+ >
+ Add Custom Header
+ </Button>
+ </div>
+ </div>
+ {watchMethod === "POST" && (
+ <div className="sm:col-span-full">
+ <FormField
+ control={form.control}
+ name="body"
+ render={({ field }) => (
+ <FormItem className="space-y-1.5">
+ <div className="flex items-end justify-between">
+ <FormLabel className="flex items-center space-x-2">
+ Body
+ <Select
+ defaultValue={content}
+ onValueChange={(value) => {
+ setContent(value);
+
+ if (content === "application/octet-stream") {
+ form.setValue("body", "");
+ setFile(undefined);
+ }
+
+ const contentIndex = fields.findIndex(
+ (field) => field.key === "Content-Type",
+ );
+
+ if (contentIndex >= 0) {
+ if (value === "none") {
+ remove(contentIndex);
+ } else {
+ update(contentIndex, {
+ key: "Content-Type",
+ value,
+ });
+ }
+ } else {
+ prepend({ key: "Content-Type", value });
+ }
+ }}
+ >
+ <SelectTrigger
+ variant={"ghost"}
+ className="ml-1 h-7 text-muted-foreground text-xs"
+ >
+ <SelectValue placeholder="Content-Type" />
+ </SelectTrigger>
+ <SelectContent>
+ {contentTypes.map((type) => (
+ <SelectItem key={type.value} value={type.value}>
+ {type.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </FormLabel>
+ {watchMethod === "POST" &&
+ fields.some(
+ (field) =>
+ field.key === "Content-Type" &&
+ field.value === "application/json",
+ ) && (
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7"
+ onClick={onPrettifyJSON}
+ >
+ <Wand2 className="h-3 w-3" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Prettify JSON</p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
+ </div>
+ <div className="space-y-2">
+ <FormControl>
+ {content === "application/octet-stream" ? (
+ <>
+ <Button
+ type="button"
+ variant="outline"
+ onClick={() => inputRef.current?.click()}
+ className="max-w-56"
+ >
+ <span className="truncate">
+ {file || form.getValues("body") || "Upload file"}
+ </span>
+ </Button>
+ <input
+ type="file"
+ onChange={uploadFile}
+ ref={inputRef}
+ hidden
+ />
+ </>
+ ) : (
+ <>
+ <Textarea
+ rows={8}
+ placeholder='{ "hello": "world" }'
+ {...field}
+ />
+ <FormDescription>Write your payload.</FormDescription>
+ </>
+ )}
+ </FormControl>
+ <FormMessage />
+ </div>
+ </FormItem>
+ )}
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/src/components/forms/monitor/section-request-tcp.tsx b/apps/web/src/components/forms/monitor/section-request-tcp.tsx
new file mode 100644
index 000000000..69134c23a
--- /dev/null
+++ b/apps/web/src/components/forms/monitor/section-request-tcp.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import * as React from "react";
+import type { UseFormReturn } from "react-hook-form";
+
+import type { InsertMonitor } from "@openstatus/db/src/schema";
+import {
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+ Input,
+} from "@openstatus/ui";
+
+// TODO: add `port` and `host` field instead!
+
+interface Props {
+ form: UseFormReturn<InsertMonitor>;
+}
+
+export function SectionRequestTCP({ form }: Props) {
+ return (
+ <div className="grid w-full gap-4">
+ <div className="grid gap-4 sm:grid-cols-7">
+ <FormField
+ control={form.control}
+ name="url"
+ render={({ field }) => (
+ <FormItem className="sm:col-span-5">
+ <FormLabel>Host:Port</FormLabel>
+ <FormControl>
+ <Input
+ className="bg-muted"
+ placeholder="192.168.1.1:80"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ <FormDescription>
+ The input supports both IPv4 addresses and IPv6 addresses.
+ </FormDescription>
+ </FormItem>
+ )}
+ />
+ </div>
+ <div className="text-sm">
+ <p>Examples:</p>
+ <ul className="list-inside list-disc text-muted-foreground">
+ <li>
+ Domain: <code className="text-foreground">openstatus.dev:443</code>
+ </li>
+ <li>
+ IPv4: <code className="text-foreground">192.168.1.1:443</code>
+ </li>
+ <li>
+ IPv6:{" "}
+ <code className="text-foreground">
+ [2001:db8:85a3:8d3:1319:8a2e:370:7348]:443
+ </code>
+ </li>
+ </ul>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/components/forms/monitor/section-requests.tsx b/apps/web/src/components/forms/monitor/section-requests.tsx
index 86eb23ace..df9a009f4 100644
--- a/apps/web/src/components/forms/monitor/section-requests.tsx
+++ b/apps/web/src/components/forms/monitor/section-requests.tsx
@@ -1,338 +1,131 @@
"use client";
-import { Wand2, X } from "lucide-react";
-import type * as React from "react";
-import { useFieldArray } from "react-hook-form";
+import * as React from "react";
import type { UseFormReturn } from "react-hook-form";
-import {
- monitorMethods,
- monitorMethodsSchema,
-} from "@openstatus/db/src/schema";
+import { monitorJobTypesSchema } from "@openstatus/db/src/schema";
import type { InsertMonitor } from "@openstatus/db/src/schema";
+
import {
- Button,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Textarea,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/components/dashboard/tabs";
-import { toast } from "@/lib/toast";
-import { useRef, useState } from "react";
+import { Alert, AlertDescription, AlertTitle, Badge } from "@openstatus/ui";
import { SectionHeader } from "../shared/section-header";
-
-const contentTypes = [
- { value: "application/octet-stream", label: "Binary File" },
- { value: "application/json", label: "JSON" },
- { value: "application/xml", label: "XML" },
- { value: "application/yaml", label: "YAML" },
- { value: "application/edn", label: "EDN" },
- { value: "application/other", label: "Other" },
- { value: "none", label: "None" },
-];
+import { SectionRequestHTTP } from "./section-request-http";
+import { SectionRequestTCP } from "./section-request-tcp";
interface Props {
form: UseFormReturn<InsertMonitor>;
+ type: "create" | "update";
}
// TODO: add Dialog with response informations when pingEndpoint!
-export function SectionRequests({ form }: Props) {
- const { fields, append, prepend, remove, update } = useFieldArray({
- name: "headers",
- control: form.control,
- });
- const inputRef = useRef<HTMLInputElement>(null);
- const watchMethod = form.watch("method");
- const [file, setFile] = useState<string | undefined>(undefined);
- const [content, setContent] = useState<string | undefined>(
- fields.find((field) => field.key === "Content-Type")?.value,
- );
-
- const validateJSON = (value?: string) => {
- if (!value) return;
- try {
- const obj = JSON.parse(value) as Record<string, unknown>;
- form.clearErrors("body");
- return obj;
- } catch (_e) {
- form.setError("body", {
- message: "Not a valid JSON object",
- });
- return false;
+export function SectionRequests({ form, type }: Props) {
+ const jobType = form.getValues("jobType");
+ const [prevJobType, setPrevJobType] = React.useState(jobType);
+
+ if (prevJobType !== jobType) {
+ setPrevJobType(jobType);
+ if (type === "create") {
+ form.resetField("url");
+ form.resetField("method");
+ form.resetField("body");
+ form.resetField("headers");
+ form.resetField("headerAssertions");
+ form.resetField("statusAssertions");
+ form.resetField("textBodyAssertions");
}
- };
-
- const uploadFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
- if (event.target.files?.[0]) {
- const file = event.target.files[0];
-
- // File too big, return error
- const fileSize = file.size / 1024 / 1024; // in MiB
- if (fileSize > 10) {
- // Display error message
- toast.error("File size is too big. Max 10MB allowed.");
- return;
- }
-
- const reader = new FileReader();
- reader.onload = (event) => {
- if (event.target?.result && typeof event.target.result === "string") {
- form.setValue("body", event.target?.result);
- setFile(file.name);
- }
- };
-
- reader.readAsDataURL(file);
- }
- };
-
- const onPrettifyJSON = () => {
- const body = form.getValues("body");
- const obj = validateJSON(body);
- if (obj) {
- const pretty = JSON.stringify(obj, undefined, 4);
- form.setValue("body", pretty);
- }
- };
+ }
return (
<div className="grid w-full gap-4">
<SectionHeader
- title="HTTP Request Settings"
- description="Create your HTTP. Add custom headers, payload and test your endpoint before submitting."
+ title="Request Settings"
+ description={
+ type === "create" ? (
+ <>
+ Create your{" "}
+ <span className="font-medium font-mono text-foreground">
+ HTTP
+ </span>{" "}
+ or{" "}
+ <span className="font-medium font-mono text-foreground">TCP</span>{" "}
+ request type. Add custom headers, payload and test your endpoint
+ before submitting.{" "}
+ <span className="font-medium">
+ You will not be able to switch type after saving.
+ </span>
+ </>
+ ) : (
+ <>
+ Update your{" "}
+ <span className="font-medium font-mono text-foreground">
+ {jobType?.toUpperCase()}
+ </span>{" "}
+ request. Add custom headers, payload and test your endpoint before
+ submitting.
+ </>
+ )
+ }
/>
- <div className="grid gap-4 sm:grid-cols-7">
- <FormField
- control={form.control}
- name="method"
- render={({ field }) => (
- <FormItem className="sm:col-span-1">
- <FormLabel>Method</FormLabel>
- <Select
- onValueChange={(value) => {
- field.onChange(monitorMethodsSchema.parse(value));
- form.resetField("body", { defaultValue: "" });
- setContent(undefined);
- }}
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="Select" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {monitorMethods.map((method) => (
- <SelectItem key={method} value={method}>
- {method}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="url"
- render={({ field }) => (
- <FormItem className="sm:col-span-6">
- <FormLabel>URL</FormLabel>
- <FormControl>
- <Input
- className="bg-muted"
- placeholder="https://documenso.com/api/health"
- {...field}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </div>
- <div className="space-y-2 sm:col-span-full">
- <FormLabel>Request Header</FormLabel>
- {fields.map((field, index) => (
- <div key={field.id} className="grid grid-cols-6 gap-4">
- <FormField
- control={form.control}
- name={`headers.${index}.key`}
- render={({ field }) => (
- <FormItem className="col-span-2">
- <FormControl>
- <Input placeholder="key" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <div className="col-span-4 flex items-center space-x-2">
- <FormField
- control={form.control}
- name={`headers.${index}.value`}
- render={({ field }) => (
- <FormItem className="w-full">
- <FormControl>
- <Input placeholder="value" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => {
- remove(index);
- }}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- </div>
- ))}
- <div>
- <Button
- type="button"
- variant="outline"
- onClick={() => append({ key: "", value: "" })}
- >
- Add Custom Header
- </Button>
- </div>
- </div>
- {watchMethod === "POST" && (
- <div className="sm:col-span-full">
- <FormField
- control={form.control}
- name="body"
- render={({ field }) => (
- <FormItem className="space-y-1.5">
- <div className="flex items-end justify-between">
- <FormLabel className="flex items-center space-x-2">
- Body
- <Select
- defaultValue={content}
- onValueChange={(value) => {
- setContent(value);
-
- if (content === "application/octet-stream") {
- form.setValue("body", "");
- setFile(undefined);
- }
-
- const contentIndex = fields.findIndex(
- (field) => field.key === "Content-Type",
- );
-
- if (contentIndex >= 0) {
- if (value === "none") {
- remove(contentIndex);
- } else {
- update(contentIndex, {
- key: "Content-Type",
- value,
- });
- }
- } else {
- prepend({ key: "Content-Type", value });
- }
- }}
- >
- <SelectTrigger
- variant={"ghost"}
- className="ml-1 h-7 text-muted-foreground text-xs"
- >
- <SelectValue placeholder="Content-Type" />
- </SelectTrigger>
- <SelectContent>
- {contentTypes.map((type) => (
- <SelectItem key={type.value} value={type.value}>
- {type.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormLabel>
- {watchMethod === "POST" &&
- fields.some(
- (field) =>
- field.key === "Content-Type" &&
- field.value === "application/json",
- ) && (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="h-7 w-7"
- onClick={onPrettifyJSON}
- >
- <Wand2 className="h-3 w-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Prettify JSON</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )}
- </div>
- <div className="space-y-2">
- <FormControl>
- {content === "application/octet-stream" ? (
- <>
- <Button
- type="button"
- variant="outline"
- onClick={() => inputRef.current?.click()}
- className="max-w-56"
- >
- <span className="truncate">
- {file || form.getValues("body") || "Upload file"}
- </span>
- </Button>
- <input
- type="file"
- onChange={uploadFile}
- ref={inputRef}
- hidden
- />
- </>
- ) : (
- <>
- <Textarea
- rows={8}
- placeholder='{ "hello": "world" }'
- {...field}
- />
- <FormDescription>Write your payload.</FormDescription>
- </>
- )}
- </FormControl>
- <FormMessage />
- </div>
- </FormItem>
- )}
- />
- </div>
- )}
+ {type === "create" ? (
+ <Tabs
+ value={jobType}
+ onValueChange={(value) => {
+ const validate = monitorJobTypesSchema.safeParse(value);
+ if (!validate.success) return;
+ form.setValue("jobType", validate.data, {
+ shouldDirty: true,
+ shouldTouch: true,
+ shouldValidate: true,
+ });
+ }}
+ >
+ <TabsList>
+ <TabsTrigger value="http">HTTP</TabsTrigger>
+ <TabsTrigger value="tcp" disabled={true}>
+ TCP{" "}
+ <Badge className="ml-2" variant="default">
+ Coming soon
+ </Badge>
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent value="http">
+ <SectionRequestHTTP {...{ form }} />
+ </TabsContent>
+ <TabsContent value="tcp">
+ <SectionRequestTCP {...{ form }} />
+ </TabsContent>
+ </Tabs>
+ ) : null}
+ {type === "update"
+ ? (() => {
+ switch (jobType) {
+ case "http":
+ return <SectionRequestHTTP {...{ form }} />;
+ case "tcp":
+ return <SectionRequestTCP {...{ form }} />;
+ default:
+ return (
+ <Alert>
+ <AlertTitle>Missing Type</AlertTitle>
+ <AlertDescription>
+ The job type{" "}
+ <span className="font-mono text-foreground uppercase">
+ {jobType}
+ </span>{" "}
+ is missing. Please select a valid job type.
+ </AlertDescription>
+ </Alert>
+ );
+ }
+ })()
+ : null}
</div>
);
}
diff --git a/apps/web/src/components/forms/monitor/section-scheduling.tsx b/apps/web/src/components/forms/monitor/section-scheduling.tsx
index 76afbb9ea..3e713b1e0 100644
--- a/apps/web/src/components/forms/monitor/section-scheduling.tsx
+++ b/apps/web/src/components/forms/monitor/section-scheduling.tsx
@@ -24,6 +24,7 @@ import { groupByContinent } from "@openstatus/utils";
import type { Limits } from "@openstatus/db/src/schema/plan/schema";
import { CheckboxLabel } from "../shared/checkbox-label";
import { SectionHeader } from "../shared/section-header";
+import { SelectRegion } from "./select-region";
// TODO: centralize in a shared file!
const cronJobs = [
@@ -95,16 +96,23 @@ export function SectionScheduling({ form, limits, plan }: Props) {
render={({ field }) => {
return (
<FormItem>
- <div className="mb-4">
- <FormLabel className="text-base">Regions</FormLabel>
- <FormDescription>
- Select the regions you want to monitor your endpoint from.{" "}
- <br />
- {plan === "free"
- ? "Only a few regions are available in the free plan. Upgrade to access all regions."
- : ""}
- </FormDescription>
+ <FormLabel className="text-base">Regions</FormLabel>
+ <div>
+ <FormControl>
+ <SelectRegion
+ value={field.value}
+ allowedRegions={regionsLimit}
+ onChange={field.onChange}
+ />
+ </FormControl>
</div>
+ <FormDescription>
+ Select the regions you want to monitor your endpoint from.{" "}
+ <br />
+ {plan === "free"
+ ? "Only a few regions are available in the free plan. Upgrade to access all regions."
+ : ""}
+ </FormDescription>
<div>
{Object.entries(groupByContinent)
.sort((a, b) => a[0].localeCompare(b[0]))
@@ -114,9 +122,10 @@ export function SectionScheduling({ form, limits, plan }: Props) {
.map((current) => {
return (
<div key={current.continent} className="py-2">
- {current.continent}
-
- <div className="grid grid-cols-3 grid-rows-1 gap-2 pt-1">
+ <p className="font-medium text-muted-foreground text-sm">
+ {current.continent}
+ </p>
+ <div className="grid grid-cols-3 gap-2">
{current.regions
.sort((a, b) =>
a.location.localeCompare(b.location),
@@ -160,6 +169,7 @@ export function SectionScheduling({ form, limits, plan }: Props) {
),
);
}}
+ className="p-3"
>
{location} {flag}
</CheckboxLabel>
diff --git a/apps/web/src/components/forms/monitor/select-region.tsx b/apps/web/src/components/forms/monitor/select-region.tsx
new file mode 100644
index 000000000..7e8e04272
--- /dev/null
+++ b/apps/web/src/components/forms/monitor/select-region.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { Check, ChevronsUpDown, Globe2 } from "lucide-react";
+import * as React from "react";
+
+import type { Region } from "@openstatus/tinybird";
+import { Button, type ButtonProps } from "@openstatus/ui/src/components/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@openstatus/ui/src/components/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@openstatus/ui/src/components/popover";
+import {
+ type Continent,
+ type RegionInfo,
+ flyRegionsDict,
+} from "@openstatus/utils";
+
+import { cn } from "@/lib/utils";
+import { flyRegions } from "@openstatus/db/src/schema/constants";
+
+interface SelectRegionProps extends Omit<ButtonProps, "onChange"> {
+ allowedRegions: Region[];
+ value?: Region[];
+ onChange?: (value: Region[]) => void;
+}
+
+export function SelectRegion({
+ value = [],
+ onChange,
+ allowedRegions,
+ className,
+ ...props
+}: SelectRegionProps) {
+ const regionsByContinent = flyRegions.reduce(
+ (prev, curr) => {
+ const region = flyRegionsDict[curr];
+
+ const item = prev.find((r) => r.continent === region.continent);
+
+ if (item) {
+ item.data.push(region);
+ } else {
+ prev.push({
+ continent: region.continent,
+ data: [region],
+ });
+ }
+
+ return prev;
+ },
+ [] as { continent: Continent; data: RegionInfo[] }[],
+ );
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ size="lg"
+ variant="outline"
+ className={cn("px-3 shadow-none", className)}
+ {...props}
+ >
+ <Globe2 className="mr-2 h-4 w-4" />
+ <span className="whitespace-nowrap">
+ <code>{value.length}</code> Regions
+ </span>
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="p-0" align="start">
+ <Command>
+ <CommandInput placeholder="Search regions..." />
+ <CommandList className="max-h-64">
+ <CommandEmpty>No results found.</CommandEmpty>
+ <CommandGroup>
+ <CommandItem
+ onSelect={() => onChange?.(value.length ? [] : allowedRegions)}
+ >
+ {value.length ? "Clear all" : "Select all"}
+ </CommandItem>
+ </CommandGroup>
+ <CommandSeparator />
+ {regionsByContinent.map(({ continent, data }) => {
+ return (
+ <CommandGroup key={continent} heading={continent}>
+ {data.map((region) => {
+ const { code, flag, location, continent } = region;
+ const isSelected = value.includes(code);
+ return (
+ <CommandItem
+ key={code}
+ value={code}
+ keywords={[code, location, continent]}
+ disabled={!allowedRegions.includes(code)}
+ onSelect={(checked) => {
+ const newValue = !value.includes(checked as Region)
+ ? [...value, code]
+ : value.filter((r) => r !== code);
+ onChange?.(newValue);
+ }}
+ >
+ <div
+ className={cn(
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
+ isSelected
+ ? "bg-primary text-primary-foreground"
+ : "opacity-50 [&_svg]:invisible",
+ )}
+ >
+ <Check className={cn("h-4 w-4")} />
+ </div>
+ <div className="flex w-full justify-between">
+ <span>
+ {code}{" "}
+ <span className="truncate text-muted-foreground">
+ {location}
+ </span>
+ </span>
+ <span>{flag}</span>
+ </div>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ );
+ })}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/apps/web/src/components/forms/monitor/tags-multi-box.tsx b/apps/web/src/components/forms/monitor/tags-multi-box.tsx
index 01b299258..d44af2f36 100644
--- a/apps/web/src/components/forms/monitor/tags-multi-box.tsx
+++ b/apps/web/src/components/forms/monitor/tags-multi-box.tsx
@@ -366,9 +366,11 @@ const DialogListItem = ({
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you sure sure?</AlertDialogTitle>
- <AlertDialogDescription>
- You are about to delete the tag{" "}
- <TagBadge color={color} name={name} /> .
+ <AlertDialogDescription asChild>
+ <div>
+ You are about to delete the tag{" "}
+ <TagBadge color={color} name={name} /> .
+ </div>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
diff --git a/apps/web/src/components/forms/shared/checkbox-label.tsx b/apps/web/src/components/forms/shared/checkbox-label.tsx
index b6f3f534a..bbec27364 100644
--- a/apps/web/src/components/forms/shared/checkbox-label.tsx
+++ b/apps/web/src/components/forms/shared/checkbox-label.tsx
@@ -36,7 +36,7 @@ export function CheckboxLabel({
<Label
htmlFor={`${name}-${id}`}
className={cn(
- "flex h-full items-center gap-1 rounded-md border border-border bg-popover p-4 pr-10 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary",
+ "flex h-full items-center gap-1 rounded-md border border-border bg-popover p-4 pr-10 hover:bg-accent hover:text-accent-foreground peer-data-[state=checked]:border-primary [&:has([data-state=checked])]:border-primary peer-disabled:hover:bg-background peer-disabled:text-muted-foreground",
className,
)}
>
diff --git a/package.json b/package.json
index 539a29261..87ba9781d 100644
--- a/package.json
+++ b/package.json
@@ -4,7 +4,7 @@
"build": "turbo run build",
"dev": "turbo run dev",
"lint": "biome lint .",
- "format": "pnpm biome format . --write && pnpm biome check . --apply-unsafe ",
+ "format": "pnpm biome format . --write && pnpm biome check . --write ",
"lint:turbo": "turbo run lint",
"dev:web": "turbo run dev --filter='./apps/web' --filter='./packages/db'",
"dx": "turbo run dx",
diff --git a/packages/db/drizzle/0036_gifted_deathbird.sql b/packages/db/drizzle/0036_gifted_deathbird.sql
new file mode 100644
index 000000000..ee3f9dc71
--- /dev/null
+++ b/packages/db/drizzle/0036_gifted_deathbird.sql
@@ -0,0 +1 @@
+UPDATE `monitor` SET `job_type` = 'http' ;
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/0036_snapshot.json b/packages/db/drizzle/meta/0036_snapshot.json
new file mode 100644
index 000000000..2bf4910c4
--- /dev/null
+++ b/packages/db/drizzle/meta/0036_snapshot.json
@@ -0,0 +1,2197 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "7321a546-31be-4313-8e3f-235db16ddee4",
+ "prevId": "d42f0027-40b6-4d43-9d76-160e0a6e35e7",
+ "tables": {
+ "status_report_to_monitors": {
+ "name": "status_report_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "status_report_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "status_report_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "status_report_to_monitors_status_report_id_status_report_id_fk": {
+ "name": "status_report_to_monitors_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_to_monitors",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "status_report_to_monitors_monitor_id_status_report_id_pk": {
+ "columns": [
+ "monitor_id",
+ "status_report_id"
+ ],
+ "name": "status_report_to_monitors_monitor_id_status_report_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "status_report": {
+ "name": "status_report",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_workspace_id_workspace_id_fk": {
+ "name": "status_report_workspace_id_workspace_id_fk",
+ "tableFrom": "status_report",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "status_report_page_id_page_id_fk": {
+ "name": "status_report_page_id_page_id_fk",
+ "tableFrom": "status_report",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "status_report_update": {
+ "name": "status_report_update",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text(4)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "date": {
+ "name": "date",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status_report_id": {
+ "name": "status_report_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "status_report_update_status_report_id_status_report_id_fk": {
+ "name": "status_report_update_status_report_id_status_report_id_fk",
+ "tableFrom": "status_report_update",
+ "tableTo": "status_report",
+ "columnsFrom": [
+ "status_report_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "integration": {
+ "name": "integration",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "credential": {
+ "name": "credential",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "external_id": {
+ "name": "external_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "data": {
+ "name": "data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "integration_workspace_id_workspace_id_fk": {
+ "name": "integration_workspace_id_workspace_id_fk",
+ "tableFrom": "integration",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "page": {
+ "name": "page",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "custom_domain": {
+ "name": "custom_domain",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "published": {
+ "name": "published",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "password_protected": {
+ "name": "password_protected",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "page_slug_unique": {
+ "name": "page_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "page_workspace_id_workspace_id_fk": {
+ "name": "page_workspace_id_workspace_id_fk",
+ "tableFrom": "page",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "monitor": {
+ "name": "monitor",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "job_type": {
+ "name": "job_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'http'"
+ },
+ "periodicity": {
+ "name": "periodicity",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'other'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "active": {
+ "name": "active",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(2048)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'GET'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "timeout": {
+ "name": "timeout",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 45000
+ },
+ "degraded_after": {
+ "name": "degraded_after",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "assertions": {
+ "name": "assertions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "deleted_at": {
+ "name": "deleted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_workspace_id_workspace_id_fk": {
+ "name": "monitor_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "monitors_to_pages": {
+ "name": "monitors_to_pages",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 0
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitors_to_pages_monitor_id_monitor_id_fk": {
+ "name": "monitors_to_pages_monitor_id_monitor_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitors_to_pages_page_id_page_id_fk": {
+ "name": "monitors_to_pages_page_id_page_id_fk",
+ "tableFrom": "monitors_to_pages",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitors_to_pages_monitor_id_page_id_pk": {
+ "columns": [
+ "monitor_id",
+ "page_id"
+ ],
+ "name": "monitors_to_pages_monitor_id_page_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "workspace": {
+ "name": "workspace",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripe_id": {
+ "name": "stripe_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "subscription_id": {
+ "name": "subscription_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "plan": {
+ "name": "plan",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ends_at": {
+ "name": "ends_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "paid_until": {
+ "name": "paid_until",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "limits": {
+ "name": "limits",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "workspace_slug_unique": {
+ "name": "workspace_slug_unique",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ },
+ "workspace_stripe_id_unique": {
+ "name": "workspace_stripe_id_unique",
+ "columns": [
+ "stripe_id"
+ ],
+ "isUnique": true
+ },
+ "workspace_id_dsn_unique": {
+ "name": "workspace_id_dsn_unique",
+ "columns": [
+ "id",
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "account": {
+ "name": "account",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider_account_id": {
+ "name": "provider_account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "session_state": {
+ "name": "session_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "account_provider_provider_account_id_pk": {
+ "columns": [
+ "provider",
+ "provider_account_id"
+ ],
+ "name": "account_provider_provider_account_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "session": {
+ "name": "session",
+ "columns": {
+ "session_token": {
+ "name": "session_token",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "user": {
+ "name": "user",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tenant_id": {
+ "name": "tenant_id",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "first_name": {
+ "name": "first_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "last_name": {
+ "name": "last_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "photo_url": {
+ "name": "photo_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "user_tenant_id_unique": {
+ "name": "user_tenant_id_unique",
+ "columns": [
+ "tenant_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "users_to_workspaces": {
+ "name": "users_to_workspaces",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "users_to_workspaces_user_id_user_id_fk": {
+ "name": "users_to_workspaces_user_id_user_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "users_to_workspaces_workspace_id_workspace_id_fk": {
+ "name": "users_to_workspaces_workspace_id_workspace_id_fk",
+ "tableFrom": "users_to_workspaces",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "users_to_workspaces_user_id_workspace_id_pk": {
+ "columns": [
+ "user_id",
+ "workspace_id"
+ ],
+ "name": "users_to_workspaces_user_id_workspace_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "verification_token": {
+ "name": "verification_token",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_token_identifier_token_pk": {
+ "columns": [
+ "identifier",
+ "token"
+ ],
+ "name": "verification_token_identifier_token_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "page_subscriber": {
+ "name": "page_subscriber",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "page_subscriber_page_id_page_id_fk": {
+ "name": "page_subscriber_page_id_page_id_fk",
+ "tableFrom": "page_subscriber",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "notification": {
+ "name": "notification",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "data": {
+ "name": "data",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "notification_workspace_id_workspace_id_fk": {
+ "name": "notification_workspace_id_workspace_id_fk",
+ "tableFrom": "notification",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "notifications_to_monitors": {
+ "name": "notifications_to_monitors",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "notification_id": {
+ "name": "notification_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "notifications_to_monitors_monitor_id_monitor_id_fk": {
+ "name": "notifications_to_monitors_monitor_id_monitor_id_fk",
+ "tableFrom": "notifications_to_monitors",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "notifications_to_monitors_notification_id_notification_id_fk": {
+ "name": "notifications_to_monitors_notification_id_notification_id_fk",
+ "tableFrom": "notifications_to_monitors",
+ "tableTo": "notification",
+ "columnsFrom": [
+ "notification_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "notifications_to_monitors_monitor_id_notification_id_pk": {
+ "columns": [
+ "monitor_id",
+ "notification_id"
+ ],
+ "name": "notifications_to_monitors_monitor_id_notification_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "monitor_status": {
+ "name": "monitor_status",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "monitor_status_idx": {
+ "name": "monitor_status_idx",
+ "columns": [
+ "monitor_id",
+ "region"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "monitor_status_monitor_id_monitor_id_fk": {
+ "name": "monitor_status_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_status",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitor_status_monitor_id_region_pk": {
+ "columns": [
+ "monitor_id",
+ "region"
+ ],
+ "name": "monitor_status_monitor_id_region_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "invitation": {
+ "name": "invitation",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'member'"
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "incident": {
+ "name": "incident",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'triage'"
+ },
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "acknowledged_at": {
+ "name": "acknowledged_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "acknowledged_by": {
+ "name": "acknowledged_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_at": {
+ "name": "resolved_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "resolved_by": {
+ "name": "resolved_by",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "incident_screenshot_url": {
+ "name": "incident_screenshot_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "recovery_screenshot_url": {
+ "name": "recovery_screenshot_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "auto_resolved": {
+ "name": "auto_resolved",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "incident_monitor_id_started_at_unique": {
+ "name": "incident_monitor_id_started_at_unique",
+ "columns": [
+ "monitor_id",
+ "started_at"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "incident_monitor_id_monitor_id_fk": {
+ "name": "incident_monitor_id_monitor_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set default",
+ "onUpdate": "no action"
+ },
+ "incident_workspace_id_workspace_id_fk": {
+ "name": "incident_workspace_id_workspace_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "incident_acknowledged_by_user_id_fk": {
+ "name": "incident_acknowledged_by_user_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "user",
+ "columnsFrom": [
+ "acknowledged_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "incident_resolved_by_user_id_fk": {
+ "name": "incident_resolved_by_user_id_fk",
+ "tableFrom": "incident",
+ "tableTo": "user",
+ "columnsFrom": [
+ "resolved_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "monitor_tag": {
+ "name": "monitor_tag",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_tag_workspace_id_workspace_id_fk": {
+ "name": "monitor_tag_workspace_id_workspace_id_fk",
+ "tableFrom": "monitor_tag",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "monitor_tag_to_monitor": {
+ "name": "monitor_tag_to_monitor",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "monitor_tag_id": {
+ "name": "monitor_tag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "monitor_tag_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "monitor_tag_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "monitor_tag_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk": {
+ "name": "monitor_tag_to_monitor_monitor_tag_id_monitor_tag_id_fk",
+ "tableFrom": "monitor_tag_to_monitor",
+ "tableTo": "monitor_tag",
+ "columnsFrom": [
+ "monitor_tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk": {
+ "columns": [
+ "monitor_id",
+ "monitor_tag_id"
+ ],
+ "name": "monitor_tag_to_monitor_monitor_id_monitor_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "application": {
+ "name": "application",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "dsn": {
+ "name": "dsn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {
+ "application_dsn_unique": {
+ "name": "application_dsn_unique",
+ "columns": [
+ "dsn"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "application_workspace_id_workspace_id_fk": {
+ "name": "application_workspace_id_workspace_id_fk",
+ "tableFrom": "application",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "maintenance": {
+ "name": "maintenance",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "from": {
+ "name": "from",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "to": {
+ "name": "to",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "page_id": {
+ "name": "page_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_workspace_id_workspace_id_fk": {
+ "name": "maintenance_workspace_id_workspace_id_fk",
+ "tableFrom": "maintenance",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "maintenance_page_id_page_id_fk": {
+ "name": "maintenance_page_id_page_id_fk",
+ "tableFrom": "maintenance",
+ "tableTo": "page",
+ "columnsFrom": [
+ "page_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ },
+ "maintenance_to_monitor": {
+ "name": "maintenance_to_monitor",
+ "columns": {
+ "monitor_id": {
+ "name": "monitor_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "maintenance_id": {
+ "name": "maintenance_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "maintenance_to_monitor_monitor_id_monitor_id_fk": {
+ "name": "maintenance_to_monitor_monitor_id_monitor_id_fk",
+ "tableFrom": "maintenance_to_monitor",
+ "tableTo": "monitor",
+ "columnsFrom": [
+ "monitor_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "maintenance_to_monitor_maintenance_id_maintenance_id_fk": {
+ "name": "maintenance_to_monitor_maintenance_id_maintenance_id_fk",
+ "tableFrom": "maintenance_to_monitor",
+ "tableTo": "maintenance",
+ "columnsFrom": [
+ "maintenance_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "maintenance_to_monitor_monitor_id_maintenance_id_pk": {
+ "columns": [
+ "maintenance_id",
+ "monitor_id"
+ ],
+ "name": "maintenance_to_monitor_monitor_id_maintenance_id_pk"
+ }
+ },
+ "uniqueConstraints": {}
+ },
+ "check": {
+ "name": "check",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "regions": {
+ "name": "regions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "url": {
+ "name": "url",
+ "type": "text(4096)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "headers": {
+ "name": "headers",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "body": {
+ "name": "body",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "''"
+ },
+ "method": {
+ "name": "method",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "'GET'"
+ },
+ "count_requests": {
+ "name": "count_requests",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": 1
+ },
+ "workspace_id": {
+ "name": "workspace_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false,
+ "default": "(strftime('%s', 'now'))"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "check_workspace_id_workspace_id_fk": {
+ "name": "check_workspace_id_workspace_id_fk",
+ "tableFrom": "check",
+ "tableTo": "workspace",
+ "columnsFrom": [
+ "workspace_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {}
+ }
+ },
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index ad37f5e84..746cb3230 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -253,6 +253,13 @@
"when": 1721159796428,
"tag": "0035_open_the_professor",
"breakpoints": true
+ },
+ {
+ "idx": 36,
+ "version": "6",
+ "when": 1723459608109,
+ "tag": "0036_gifted_deathbird",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/packages/db/src/schema/monitors/constants.ts b/packages/db/src/schema/monitors/constants.ts
index 2b05d96bd..b86207e7e 100644
--- a/packages/db/src/schema/monitors/constants.ts
+++ b/packages/db/src/schema/monitors/constants.ts
@@ -1,4 +1,13 @@
export const monitorMethods = ["GET", "POST", "HEAD"] as const;
export const monitorStatus = ["active", "error", "degraded"] as const;
-export const monitorJobTypes = ["website", "cron", "other"] as const;
+export const monitorJobTypes = [
+ "http",
+ "tcp",
+ "imcp",
+ "udp",
+ "dns",
+ "ssl",
+ // FIXME: remove this after the migration
+ "other",
+] as const;
diff --git a/packages/db/src/schema/monitors/monitor.ts b/packages/db/src/schema/monitors/monitor.ts
index f208f5689..2e521634a 100644
--- a/packages/db/src/schema/monitors/monitor.ts
+++ b/packages/db/src/schema/monitors/monitor.ts
@@ -18,7 +18,7 @@ import { monitorJobTypes, monitorMethods, monitorStatus } from "./constants";
export const monitor = sqliteTable("monitor", {
id: integer("id").primaryKey(),
jobType: text("job_type", { enum: monitorJobTypes })
- .default("other")
+ .default("http")
.notNull(),
periodicity: text("periodicity", { enum: monitorPeriodicity })
.default("other")
@@ -28,7 +28,7 @@ export const monitor = sqliteTable("monitor", {
regions: text("regions").default("").notNull(),
- url: text("url", { length: 2048 }).notNull(),
+ url: text("url", { length: 2048 }).notNull(), // URI
name: text("name", { length: 256 }).default("").notNull(),
description: text("description").default("").notNull(),
diff --git a/packages/db/src/schema/monitors/validation.ts b/packages/db/src/schema/monitors/validation.ts
index 72d6120e4..05ac9540b 100644
--- a/packages/db/src/schema/monitors/validation.ts
+++ b/packages/db/src/schema/monitors/validation.ts
@@ -43,7 +43,7 @@ const headersToArraySchema = z.preprocess(
export const selectMonitorSchema = createSelectSchema(monitor, {
periodicity: monitorPeriodicitySchema.default("10m"),
status: monitorStatusSchema.default("active"),
- jobType: monitorJobTypesSchema.default("other"),
+ jobType: monitorJobTypesSchema.default("http"),
timeout: z.number().default(45),
regions: regionsToArraySchema.default([]),
}).extend({
@@ -59,7 +59,6 @@ const headersSchema = z
export const insertMonitorSchema = createInsertSchema(monitor, {
name: z.string().min(1, "Name must be at least 1 character long"),
periodicity: monitorPeriodicitySchema.default("10m"),
- url: z.string().url(), // find a better way to not always start with "https://" including the `InputWithAddons`
status: monitorStatusSchema.default("active"),
regions: z.array(monitorRegionSchema).default([]).optional(),
headers: headersSchema.default([]),
diff --git a/temp/main.go b/temp/main.go
new file mode 100644
index 000000000..fedf64738
--- /dev/null
+++ b/temp/main.go
@@ -0,0 +1,16 @@
+package main
+
+import "fmt"
+
+type Person struct {
+ Test int
+ Other string
+}
+
+func HelloVet() {
+ fmt.Println("Hello Vet")
+
+ return
+
+ fmt.Println("This line will never be executed")
+}