Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
chore: assertions package (#727)
Maximilian Kaske0a12e3fbdc4d
diff --git a/.vscode/settings.json b/.vscode/settings.jsonindex 52af1ea16..5ae912fa5 100644--- a/.vscode/settings.json+++ b/.vscode/settings.json@@ -19,5 +19,8 @@},"[xml]": {"editor.defaultFormatter": "redhat.vscode-xml"+ },+ "[go]": {+ "editor.defaultFormatter": "golang.go"}}diff --git a/apps/checker/cmd/main.go b/apps/checker/cmd/main.goindex 3e3ea12c8..fae202467 100644--- a/apps/checker/cmd/main.go+++ b/apps/checker/cmd/main.go@@ -2,6 +2,7 @@ package mainimport ("context"+ "encoding/json""errors""fmt""net/http"@@ -12,6 +13,7 @@ import ("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/pkg/logger""github.com/openstatushq/openstatus/apps/checker/pkg/tinybird""github.com/openstatushq/openstatus/apps/checker/request"@@ -85,6 +87,14 @@ func main() {}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 intop := func() error {called++@@ -93,12 +103,58 @@ func main() {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.AssertionHeaders:+ 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)++ fmt.Println("assertion type", assert.AssertionType)+ case request.AssertionTextBody:+ fmt.Println("assertion type", assert.AssertionType)+ 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 !statusCode.IsSuccessful() && called < 2 {+ if !isSuccessfull && called < 2 {return fmt.Errorf("unable to ping: %v with status %v", res, res.StatusCode)}- if !statusCode.IsSuccessful() && req.Status == "active" {+ // it's in error if not successful+ if isSuccessfull {+ res.Error = 0+ } else {+ res.Error = 1+ }++ res.Assertions = assertionAsString+ 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,@@ -110,7 +166,7 @@ func main() {})}- if req.Status == "error" && statusCode.IsSuccessful() {+ if req.Status == "error" && isSuccessfull {// Q: Why here we check the data before updating the status in this scenario?checker.UpdateStatus(ctx, checker.UpdateData{MonitorId: req.MonitorID,@@ -120,6 +176,7 @@ func main() {CronTimestamp: req.CronTimestamp,})}+if err := tinybirdClient.SendEvent(ctx, res); err != nil {log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")}@@ -136,6 +193,8 @@ func main() {Timestamp: req.CronTimestamp,MonitorID: req.MonitorID,WorkspaceID: req.WorkspaceID,+ Error: 1,+ Assertions: assertionAsString,}); err != nil {log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")}@@ -157,7 +216,6 @@ func main() {router.GET("/health", func(c *gin.Context) {c.JSON(http.StatusOK, gin.H{"message": "pong", "fly_region": flyRegion})- return})router.POST("/ping/:region", func(c *gin.Context) {@@ -205,15 +263,22 @@ func main() {c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})return}-- res, err := checker.SinglePing(c.Request.Context(), requestClient, req)- if err != nil {+ 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)+ }+ res = r+ 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)- return})+httpServer := &http.Server{Addr: fmt.Sprintf("0.0.0.0:%s", env("PORT", "8080")),Handler: router,diff --git a/apps/checker/ping.go b/apps/checker/ping.goindex 5dbc3b721..acb6629f8 100644--- a/apps/checker/ping.go+++ b/apps/checker/ping.go@@ -30,6 +30,8 @@ type PingData struct {Message string `json:"message,omitempty"`Timing string `json:"timing,omitempty"`Headers string `json:"headers,omitempty"`+ Error uint8 `json:"error"`+ Assertions string `json:"assertions"`}type Timing struct {diff --git a/apps/checker/pkg/assertions/assertions.go b/apps/checker/pkg/assertions/assertions.gonew file mode 100644index 000000000..78a751d2b--- /dev/null+++ b/apps/checker/pkg/assertions/assertions.go@@ -0,0 +1,115 @@+package assertions++import (+ "encoding/json"+ "fmt"+ "strings"++ "github.com/openstatushq/openstatus/apps/checker/request"+)++type BodyString struct {+ AssertionType request.AssertionType `json:"type"`+ Comparator request.StringComparator `json:"compare"`+ Target string `json:"target"`+}++type StatusTarget struct {+ AssertionType request.AssertionType `json:"type"`+ Comparator request.NumberComparator `json:"compare"`+ Target int64 `json:"target"`+}++type HeaderTarget struct {+ AssertionType request.AssertionType `json:"type"`+ Comparator request.StringComparator `json:"compare"`+ Target string `json:"target"`+ Key string `json:"key"`+}++type StringTargetType struct {+ Comparator request.StringComparator+ Target string+}++func (target StringTargetType) StringEvaluate(s string) bool {+ switch target.Comparator {+ case request.StringContains:+ return strings.Contains(target.Target, s)+ case request.StringNotContains:+ return !strings.Contains(target.Target, s)+ case request.StringEmpty:+ return s == ""+ case request.StringNotEmpty:+ return s != ""+ case request.StringEquals:+ return s == target.Target+ case request.StringNotEquals:+ return s != target.Target+ case request.StringGreaterThan:+ return s > target.Target+ case request.StringGreaterThanEqual:+ return s >= target.Target+ case request.StringLowerThan:+ return s < target.Target+ case request.StringLowerThanEqual:+ return s <= target.Target+ }++ return false+}++func (target HeaderTarget) HeaderEvaluate(s string) bool {++ fmt.Println(s)++ headers := map[string]interface{}{}++ if err := json.Unmarshal([]byte(s), &headers); err != nil {+ panic(err)+ }+ v, found := headers[target.Key]+ if !found {+ return false+ }++ t := StringTargetType{Comparator: target.Comparator, Target: target.Target}+ // convert all headers to array+ str := fmt.Sprintf("%v", v)++ return t.StringEvaluate(str)+}++func (target StatusTarget) StatusEvaluate(value int64) bool {++ switch target.Comparator {+ case request.NumberEquals:+ if target.Target != value {+ return false+ }+ case request.NumberNotEquals:+ if target.Target == value {+ return false+ }++ case request.NumberGreaterThan:+ if target.Target >= value {+ return false+ }+ case request.NumberGreaterThanEqual:+ if target.Target > value {+ return false+ }+ case request.NumberLowerThan:+ if target.Target <= value {+ return false+ }+ case request.NumberLowerThanEqual:+ if target.Target < value {+ return false+ }+ default:+ fmt.Println("something strange ", target)+ }+ return true+}diff --git a/apps/checker/pkg/assertions/assertions_test.go b/apps/checker/pkg/assertions/assertions_test.gonew file mode 100644index 000000000..59eefc6c3--- /dev/null+++ b/apps/checker/pkg/assertions/assertions_test.go@@ -0,0 +1,119 @@+package assertions++import (+ "testing"++ "github.com/openstatushq/openstatus/apps/checker/request"+)++func TestIntTarget_IntEvaluate(t *testing.T) {+ type fields struct {+ AssertionType request.AssertionType+ Comparator request.NumberComparator+ Target int64+ }+ type args struct {+ value int64+ }+ tests := []struct {+ name string+ fields fields+ args args+ want bool+ }{+ {+ name: "Equals true", fields: fields{Comparator: request.NumberEquals, Target: 200}, args: args{value: 200}, want: true,+ },+ {+ name: "Equals false", fields: fields{Comparator: request.NumberEquals, Target: 200}, args: args{value: 201}, want: false,+ },+ {+ name: "Not Equals true", fields: fields{Comparator: request.NumberNotEquals, Target: 200}, args: args{value: 201}, want: true,+ },+ {+ name: "Not Equals false", fields: fields{Comparator: request.NumberNotEquals, Target: 200}, args: args{value: 200}, want: false,+ },+ {+ name: "greater than true", fields: fields{Comparator: request.NumberGreaterThan, Target: 200}, args: args{value: 201}, want: true,+ },+ {+ name: "greater than false 1", fields: fields{Comparator: request.NumberGreaterThan, Target: 200}, args: args{value: 200}, want: false,+ },+ {+ name: "greater than false", fields: fields{Comparator: request.NumberGreaterThan, Target: 200}, args: args{value: 199}, want: false,+ },+ {+ name: "greater than equal true", fields: fields{Comparator: request.NumberGreaterThanEqual, Target: 200}, args: args{value: 201}, want: true,+ },+ {+ name: "greater than equal true 1", fields: fields{Comparator: request.NumberGreaterThanEqual, Target: 200}, args: args{value: 200}, want: true,+ },+ {+ name: "greater than equal false", fields: fields{Comparator: request.NumberGreaterThanEqual, Target: 200}, args: args{value: 199}, want: false,+ },+ {+ name: "lower than true", fields: fields{Comparator: request.NumberLowerThan, Target: 200}, args: args{value: 199}, want: true,+ },+ {+ name: "lower than false 1", fields: fields{Comparator: request.NumberLowerThan, Target: 200}, args: args{value: 200}, want: false,+ },+ {+ name: "lower than false", fields: fields{Comparator: request.NumberLowerThan, Target: 200}, args: args{value: 201}, want: false,+ },+ {+ name: "lower than Equal true", fields: fields{Comparator: request.NumberLowerThanEqual, Target: 200}, args: args{value: 199}, want: true,+ },+ {+ name: "lower than equal true 1", fields: fields{Comparator: request.NumberLowerThanEqual, Target: 200}, args: args{value: 200}, want: true,+ },+ {+ name: "lower than equal false", fields: fields{Comparator: request.NumberLowerThan, Target: 200}, args: args{value: 201}, want: false,+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ target := StatusTarget{+ AssertionType: tt.fields.AssertionType,+ Comparator: tt.fields.Comparator,+ Target: tt.fields.Target,+ }+ if got := target.StatusEvaluate(tt.args.value); got != tt.want {+ t.Errorf("IntTarget.IntEvaluate() = %v, want %v", got, tt.want)+ }+ })+ }+}++func TestHeaderTarget_HeaderEvaluate(t *testing.T) {+ type fields struct {+ AssertionType request.AssertionType+ Comparator request.StringComparator+ Target string+ Key string+ }+ type args struct {+ s string+ }+ tests := []struct {+ name string+ fields fields+ args args+ want bool+ }{+ {name: "Header 1", fields: fields{Comparator: request.StringEmpty, Target: "", Key: "headers1"}, args: args{s: `{"Content-Type":"text/plain;charset=UTF-8","Strict-Transport-Security":"max-age=3153600000","Vary":"Accept-Encoding"}`}, want: false},+ {name: "Header 1", fields: fields{Comparator: request.StringEmpty, Target: "", Key: "headers1"}, args: args{s: `{"Content-Type":"text/plain;charset=UTF-8","Strict-Transport-Security":"max-age=3153600000","headers1":"Accept-Encoding"}`}, want: true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ target := HeaderTarget{+ AssertionType: tt.fields.AssertionType,+ Comparator: tt.fields.Comparator,+ Target: tt.fields.Target,+ Key: tt.fields.Key,+ }+ if got := target.HeaderEvaluate(tt.args.s); got != tt.want {+ t.Errorf("HeaderTarget.HeaderEvaluate() = %v, want %v", got, tt.want)+ }+ })+ }+}diff --git a/apps/checker/pkg/tinybird/client.go b/apps/checker/pkg/tinybird/client.goindex ec9761200..0261835be 100644--- a/apps/checker/pkg/tinybird/client.go+++ b/apps/checker/pkg/tinybird/client.go@@ -37,7 +37,7 @@ func (c client) SendEvent(ctx context.Context, event any) error {}q := requestURL.Query()- q.Add("name", "ping_response__v7")+ q.Add("name", "ping_response__v8")requestURL.RawQuery = q.Encode()var payload bytes.Bufferdiff --git a/apps/checker/pkg/tinybird/client_test.go b/apps/checker/pkg/tinybird/client_test.goindex abf03de42..9bf14bcab 100644--- a/apps/checker/pkg/tinybird/client_test.go+++ b/apps/checker/pkg/tinybird/client_test.go@@ -73,6 +73,6 @@ func TestSendEvent(t *testing.T) {err := client.SendEvent(ctx, "event")require.NoError(t, err)- require.Equal(t, "https://api.tinybird.co/v0/events?name=ping_response__v7", url)+ require.Equal(t, "https://api.tinybird.co/v0/events?name=ping_response__v8", url)})}diff --git a/apps/checker/request/request.go b/apps/checker/request/request.goindex a9152c9a7..17fad3956 100644--- a/apps/checker/request/request.go+++ b/apps/checker/request/request.go@@ -1,5 +1,48 @@package request+import "encoding/json"++type AssertionType string++const (+ AssertionHeaders AssertionType = "headers"+ AssertionTextBody AssertionType = "textBody"+ AssertionStatus AssertionType = "status"+ AssertionJsonBody AssertionType = "jsonBody"+)++type StringComparator string++const (+ StringContains StringComparator = "contains"+ StringNotContains StringComparator = "not_contains"+ StringEquals StringComparator = "eq"+ StringNotEquals StringComparator = "not_eq"+ StringEmpty StringComparator = "empty"+ StringNotEmpty StringComparator = "not_empty"+ StringGreaterThan StringComparator = "gt"+ StringGreaterThanEqual StringComparator = "gte"+ StringLowerThan StringComparator = "lt"+ StringLowerThanEqual StringComparator = "lte"+)++type NumberComparator string++const (+ NumberEquals NumberComparator = "eq"+ NumberNotEquals NumberComparator = "not_eq"+ NumberGreaterThan NumberComparator = "gt"+ NumberGreaterThanEqual NumberComparator = "gte"+ NumberLowerThan NumberComparator = "lt"+ NumberLowerThanEqual NumberComparator = "lte"+)++type Assertion struct {+ AssertionType AssertionType `json:"type"`+ Comparator json.RawMessage `json:"compare"`+ RawTarget json.RawMessage `json:"target"`+}+type CheckerRequest struct {WorkspaceID string `json:"workspaceId"`URL string `json:"url"`@@ -11,7 +54,8 @@ type CheckerRequest struct {Key string `json:"key"`Value string `json:"value"`} `json:"headers,omitempty"`- Status string `json:"status"`+ Status string `json:"status"`+ RawAssertions []json.RawMessage `json:"assertions,omitempty"`}type PingRequest struct {diff --git a/apps/server/src/checker/index.ts b/apps/server/src/checker/index.tsindex 70154da25..e5b084a0f 100644--- a/apps/server/src/checker/index.ts+++ b/apps/server/src/checker/index.ts@@ -4,7 +4,10 @@ import { z } from "zod";import { and, db, eq, isNull, schema } from "@openstatus/db";import { incidentTable } from "@openstatus/db/src/schema";import { flyRegions } from "@openstatus/db/src/schema/monitors/constants";-import { selectMonitorSchema } from "@openstatus/db/src/schema/monitors/validation";+import {+ monitorStatusSchema,+ selectMonitorSchema,+} from "@openstatus/db/src/schema/monitors/validation";import { Redis } from "@openstatus/upstash";import { env } from "../env";@@ -28,14 +31,16 @@ checkerRoute.post("/updateStatus", async (c) => {statusCode: z.number().optional(),region: z.enum(flyRegions),cronTimestamp: z.number(),- // status: z.enum(["active", "error"]),+ status: monitorStatusSchema,});const result = payloadSchema.safeParse(json);+if (!result.success) {return c.text("Unprocessable Entity", 422);}- const { monitorId, message, region, statusCode, cronTimestamp } = result.data;+ const { monitorId, message, region, statusCode, cronTimestamp, status } =+ result.data;console.log(`📝 update monitor status ${JSON.stringify(result.data)}`);@@ -59,18 +64,13 @@ checkerRoute.post("/updateStatus", async (c) => {.get();// if we are in error- if (!statusCode || statusCode < 200 || statusCode > 300) {- // create incident+ if (status === "error") {// trigger alertingawait checkerAudit.publishAuditLog({id: `monitor:${monitorId}`,action: "monitor.failed",targets: [{ id: monitorId, type: "monitor" }],- metadata: {- region: region,- statusCode: statusCode,- message,- },+ metadata: { region, statusCode, message },});// We upsert the status of the monitorawait upsertMonitorStatus({@@ -114,6 +114,7 @@ checkerRoute.post("/updateStatus", async (c) => {),).get();+if (incident === undefined) {await db.insert(incidentTable)@@ -135,7 +136,7 @@ checkerRoute.post("/updateStatus", async (c) => {}}// When the status is ok- if (statusCode && statusCode >= 200 && statusCode < 300) {+ if (status === "active") {await upsertMonitorStatus({monitorId: monitorId,status: "active",diff --git a/apps/web/package.json b/apps/web/package.jsonindex b36c94329..6fb18960e 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -16,6 +16,7 @@"@hookform/resolvers": "3.3.1","@openstatus/analytics": "workspace:*","@openstatus/api": "workspace:*",+ "@openstatus/assertions": "workspace:*","@openstatus/db": "workspace:*","@openstatus/emails": "workspace:*","@openstatus/notification-discord": "workspace:*",diff --git a/apps/web/src/app/api/checker/cron/_cron.ts b/apps/web/src/app/api/checker/cron/_cron.tsindex b1acf1cf3..2a0778bc1 100644--- a/apps/web/src/app/api/checker/cron/_cron.ts+++ b/apps/web/src/app/api/checker/cron/_cron.ts@@ -133,6 +133,7 @@ const createCronTask = async ({body: row.body,headers: row.headers,status: status,+ assertions: row.assertions,};const newTask: google.cloud.tasks.v2beta3.ITask = {diff --git a/apps/web/src/app/api/checker/schema.ts b/apps/web/src/app/api/checker/schema.tsindex 427e6f3bc..e9e0dd473 100644--- a/apps/web/src/app/api/checker/schema.ts+++ b/apps/web/src/app/api/checker/schema.ts@@ -11,6 +11,7 @@ export const payloadSchema = z.object({url: z.string(),cronTimestamp: z.number(),status: z.enum(monitorStatus),+ assertions: z.string().nullable(),});export type Payload = z.infer<typeof payloadSchema>;diff --git a/apps/web/src/app/api/test/timeout/route.ts b/apps/web/src/app/api/test/timeout/route.tsnew file mode 100644index 000000000..6513b15cb--- /dev/null+++ b/apps/web/src/app/api/test/timeout/route.ts@@ -0,0 +1,13 @@+import { NextResponse } from "next/server";++import { wait } from "@/lib/utils";++export async function POST() {+ await wait(10_000);+ return NextResponse.json({ message: "Hello, World!" });+}++export async function GET() {+ await wait(10_000);+ return NextResponse.json({ message: "Hello, World!" });+}diff --git a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsx b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsxindex f1ddbcd34..6873cf1f2 100644--- a/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsx+++ b/apps/web/src/app/app/[workspaceSlug]/(dashboard)/monitors/[id]/data/_components/data-table-wrapper.tsx@@ -6,6 +6,7 @@import { Suspense, use } from "react";import type { Row } from "@tanstack/react-table";+import * as assertions from "@openstatus/assertions";import type { OSTinybird } from "@openstatus/tinybird";import { ResponseDetailTabs } from "@/app/play/checker/[id]/_components/response-detail-tabs";@@ -28,6 +29,8 @@ type Monitor = {timestamp: number;workspaceId: string;cronTimestamp: number | null;+ error: boolean;+ assertions?: string | null;};export function DataTableWrapper({ data }: { data: Monitor[] }) {@@ -85,6 +88,7 @@ function Details({ row }: { row: Row<Monitor> }) {timing={first.timing}headers={first.headers}message={first.message}+ assertions={assertions.deserialize(first.assertions || "[]")}/></div>);diff --git a/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsx b/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsxindex 565740acc..509a3a725 100644--- a/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsx+++ b/apps/web/src/app/play/checker/[id]/_components/multi-region-table.tsx@@ -8,6 +8,7 @@ import {TableRow,} from "@openstatus/ui";+import { StatusCodeBadge } from "@/components/monitor/status-code-badge";import type { RegionChecker } from "../utils";import {getTimingPhases,@@ -15,7 +16,6 @@ import {latencyFormatter,regionFormatter,} from "../utils";-import { StatusBadge } from "./status-badge";// TBD: add the popover infos about timing details@@ -45,7 +45,7 @@ export function MultiRegionTable({ regions }: { regions: RegionChecker[] }) {{regionFormatter(region)}</TableCell><TableCell>- <StatusBadge statusCode={status} />+ <StatusCodeBadge statusCode={status} /></TableCell><TableCell className="text-muted-foreground"><code>{latencyFormatter(dns)}</code>diff --git a/apps/web/src/app/play/checker/[id]/_components/region-info.tsx b/apps/web/src/app/play/checker/[id]/_components/region-info.tsxindex 58913ad21..f97abf34e 100644--- a/apps/web/src/app/play/checker/[id]/_components/region-info.tsx+++ b/apps/web/src/app/play/checker/[id]/_components/region-info.tsx@@ -1,15 +1,17 @@+import { StatusCodeBadge } from "@/components/monitor/status-code-badge";import {latencyFormatter,regionFormatter,timestampFormatter,} from "../utils";import type { RegionChecker } from "../utils";-import { StatusBadge } from "./status-badge";export function RegionInfo({check,+ error,}: {check: Pick<RegionChecker, "region" | "time" | "latency" | "status">;+ error?: string;}) {return (<div className="grid grid-cols-5 gap-2 text-sm sm:grid-cols-9">@@ -37,8 +39,20 @@ export function RegionInfo({<p className="text-muted-foreground">Status:</p></div><div className="col-span-3 sm:col-span-6">- <StatusBadge statusCode={check.status} />- </div>+ <StatusCodeBadge statusCode={check.status} />+ </div>+ {error ? (+ <>+ <div className="col-span-2">+ <p className="text-muted-foreground">Error:</p>+ </div>+ <div className="col-span-3 sm:col-span-6">+ <p className="text-destructive font-medium before:content-['«_'] after:content-['_»']">+ {error}+ </p>+ </div>+ </>+ ) : null}</div>);}diff --git a/apps/web/src/app/play/checker/[id]/_components/response-assertion.tsx b/apps/web/src/app/play/checker/[id]/_components/response-assertion.tsxnew file mode 100644index 000000000..73b94756d--- /dev/null+++ b/apps/web/src/app/play/checker/[id]/_components/response-assertion.tsx@@ -0,0 +1,60 @@+import {+ numberCompareDictionary,+ stringCompareDictionary,+} from "@openstatus/assertions";+import type { Assertion } from "@openstatus/assertions";+import {+ Table,+ TableBody,+ TableCaption,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from "@openstatus/ui";++export function ResponseAssertion({ assertions }: { assertions: Assertion[] }) {+ return (+ <Table>+ <TableCaption className="mt-2">Response Assertions</TableCaption>+ <TableHeader>+ <TableRow>+ <TableHead>Source</TableHead>+ <TableHead>Key</TableHead>+ <TableHead>Comparison</TableHead>+ <TableHead>Target</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {assertions.map((a, i) => {+ if (a.schema.type === "status") {+ return (+ <TableRow key={i}>+ <TableCell className="text-muted-foreground">+ Status Code+ </TableCell>+ <TableCell />+ <TableCell>+ {numberCompareDictionary[a.schema.compare]}+ </TableCell>+ <TableCell className="font-mono">{a.schema.target}</TableCell>+ </TableRow>+ );+ } else if (a.schema.type === "header") {+ return (+ <TableRow key={i}>+ <TableCell className="text-muted-foreground">Header</TableCell>+ <TableCell className="font-mono">{a.schema.key}</TableCell>+ <TableCell>+ {stringCompareDictionary[a.schema.compare]}+ </TableCell>+ <TableCell className="font-mono">{a.schema.target}</TableCell>+ </TableRow>+ );+ }+ return null;+ })}+ </TableBody>+ </Table>+ );+}diff --git a/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx b/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsxindex b0bbe5afd..61e847c47 100644--- a/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx+++ b/apps/web/src/app/play/checker/[id]/_components/response-detail-tabs.tsx@@ -1,3 +1,5 @@+import type { Assertion } from "@openstatus/assertions";+import {Tabs,TabsContent,@@ -5,6 +7,7 @@ import {TabsTrigger,} from "@/components/dashboard/tabs";import type { Timing } from "../utils";+import { ResponseAssertion } from "./response-assertion";import { ResponseHeaderTable } from "./response-header-table";import { ResponseTimingTable } from "./response-timing-table";@@ -12,10 +15,12 @@ export async function ResponseDetailTabs({timing,headers,message,+ assertions,}: {timing: Timing | null;headers: Record<string, string> | null;message?: string | null;+ assertions?: Assertion[] | null;}) {return (<Tabs defaultValue="headers">@@ -25,6 +30,12 @@ export async function ResponseDetailTabs({<TabsTrigger value="message" disabled={!message}>Message</TabsTrigger>+ <TabsTrigger+ value="assertions"+ disabled={!assertions || assertions.length === 0}+ >+ Assertions+ </TabsTrigger></TabsList><TabsContent value="headers">{headers ? <ResponseHeaderTable headers={headers} /> : null}@@ -42,6 +53,9 @@ export async function ResponseDetailTabs({</div>) : null}</TabsContent>+ <TabsContent value="assertions">+ {assertions ? <ResponseAssertion {...{ assertions }} /> : null}+ </TabsContent></Tabs>);}diff --git a/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx b/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsxindex 7ac483246..69a49af35 100644--- a/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx+++ b/apps/web/src/app/play/checker/[id]/_components/response-header-table.tsx@@ -29,7 +29,7 @@ export function ResponseHeaderTable({<TableRow key={key}><TableCell className="group"><div className="flex items-center justify-between gap-4">- <code className="font-medium">{key}</code>+ <code className="break-all font-medium">{key}</code><CopyToClipboardButtoncopyValue={key}className="invisible group-hover:visible"@@ -38,7 +38,7 @@ export function ResponseHeaderTable({</TableCell><TableCell className="group"><div className="flex items-center justify-between gap-4">- <code>{value}</code>+ <code className="break-all">{value}</code><CopyToClipboardButtoncopyValue={value}className="invisible group-hover:visible"diff --git a/apps/web/src/components/data-table/columns.tsx b/apps/web/src/components/data-table/columns.tsxindex c336bca9b..5fbf3e2c4 100644--- a/apps/web/src/components/data-table/columns.tsx+++ b/apps/web/src/components/data-table/columns.tsx@@ -2,6 +2,7 @@import type { ColumnDef } from "@tanstack/react-table";import { format } from "date-fns";+import { Check, X } from "lucide-react";import * as z from "zod";import type { Ping } from "@openstatus/tinybird";@@ -17,6 +18,22 @@ import { DataTableColumnHeader } from "./data-table-column-header";import { DataTableStatusBadge } from "./data-table-status-badge";export const columns: ColumnDef<Ping>[] = [+ {+ id: "state",+ cell: ({ row }) => {+ if (row.original.error)+ return (+ <div className="max-w-max rounded-full bg-rose-500 p-1">+ <X className="text-background h-3 w-3" />+ </div>+ );+ return (+ <div className="max-w-max rounded-full bg-green-500 p-1">+ <Check className="text-background h-3 w-3" />+ </div>+ );+ },+ },{accessorKey: "cronTimestamp",header: ({ column }) => (diff --git a/apps/web/src/components/data-table/data-table-status-badge.tsx b/apps/web/src/components/data-table/data-table-status-badge.tsxindex f87f7d261..c69dffc04 100644--- a/apps/web/src/components/data-table/data-table-status-badge.tsx+++ b/apps/web/src/components/data-table/data-table-status-badge.tsx@@ -1,31 +1,22 @@import type { Ping } from "@openstatus/tinybird";import { Badge } from "@openstatus/ui";-import { cn } from "@/lib/utils";+import { StatusCodeBadge } from "../monitor/status-code-badge";export function DataTableStatusBadge({statusCode,}: {statusCode: Ping["statusCode"];}) {- const isOk = String(statusCode).startsWith("2");- return (- <Badge- variant="outline"- className={cn(- "px-2 py-0.5 text-xs",- isOk- ? "border-green-500/20 bg-green-500/10"- : "border-red-500/20 bg-red-500/10",- )}- >- {statusCode || "Error"}- <div- className={cn(- "bg-foreground ml-1 h-1.5 w-1.5 rounded-full",- isOk ? "bg-green-500" : "bg-red-500",- )}- />- </Badge>- );+ if (!statusCode) {+ return (+ <Badge+ variant="outline"+ className="border-rose-500/20 bg-rose-500/10 text-rose-800 dark:text-rose-300"+ >+ Error+ </Badge>+ );+ }+ return <StatusCodeBadge statusCode={statusCode} />;}diff --git a/apps/web/src/components/forms/monitor/form.tsx b/apps/web/src/components/forms/monitor/form.tsxindex fe70f7a5c..6c3268983 100644--- a/apps/web/src/components/forms/monitor/form.tsx+++ b/apps/web/src/components/forms/monitor/form.tsx@@ -5,6 +5,7 @@ import { usePathname, useRouter } from "next/navigation";import { zodResolver } from "@hookform/resolvers/zod";import { useForm } from "react-hook-form";+import * as assertions from "@openstatus/assertions";import type {InsertMonitor,MonitorFlyRegion,@@ -24,11 +25,14 @@ import {TabsTrigger,} from "@/components/dashboard/tabs";import { FailedPingAlertConfirmation } from "@/components/modals/failed-ping-alert-confirmation";-import { toastAction } from "@/lib/toast";+import { toast, toastAction } from "@/lib/toast";+import { formatDuration } from "@/lib/utils";import { api } from "@/trpc/client";import type { Writeable } from "@/types/utils";import { SaveButton } from "../shared/save-button";import { General } from "./general";+import { RequestTestButton } from "./request-test-button";+import { SectionAssertions } from "./section-assertions";import { SectionDanger } from "./section-danger";import { SectionNotifications } from "./section-notifications";import { SectionRequests } from "./section-requests";@@ -45,6 +49,8 @@ interface Props {nextUrl?: string;}+const ABORT_TIMEOUT = 7_000; // in ms+export function MonitorForm({defaultSection,defaultValues,@@ -54,6 +60,9 @@ export function MonitorForm({tags,nextUrl,}: Props) {+ const _assertions = defaultValues?.assertions+ ? assertions.deserialize(defaultValues?.assertions).map((a) => a.schema)+ : [];const form = useForm<InsertMonitor>({resolver: zodResolver(insertMonitorSchema),defaultValues: {@@ -73,6 +82,8 @@ export function MonitorForm({notifications: defaultValues?.notifications ?? [],pages: defaultValues?.pages ?? [],tags: defaultValues?.tags ?? [],+ statusAssertions: _assertions.filter((a) => a.type === "status") as any, // TS considers a.type === "header"+ headerAssertions: _assertions.filter((a) => a.type === "header") as any, // TS considers a.type === "status"},});const router = useRouter();@@ -102,12 +113,12 @@ export function MonitorForm({const onSubmit = ({ ...props }: InsertMonitor) => {startTransition(async () => {try {- // const pingResult = await pingEndpoint();- // const isOk = pingResult?.status >= 200 && pingResult?.status < 300;- // if (!isOk) {- // setPingFailed(true);- // return;- // }+ const { error } = await pingEndpoint();+ if (error) {+ setPingFailed(true);+ toast.error(error);+ return;+ }await handleDataUpdateOrInsertion(props);} catch {toastAction("error");@@ -116,16 +127,65 @@ export function MonitorForm({};const pingEndpoint = async (region?: MonitorFlyRegion) => {- const { url, body, method, headers } = form.getValues();- const res = await fetch(`/api/checker/test`, {- method: "POST",- headers: new Headers({- "Content-Type": "application/json",- }),- body: JSON.stringify({ url, body, method, headers, region }),- });- const data = (await res.json()) as RegionChecker;- return data;+ const { url, body, method, headers, statusAssertions, headerAssertions } =+ form.getValues();++ try {+ const res = await fetch(`/api/checker/test`, {+ method: "POST",+ headers: new Headers({+ "Content-Type": "application/json",+ }),+ body: JSON.stringify({ url, body, method, headers, region }),+ signal: AbortSignal.timeout(ABORT_TIMEOUT),+ });++ const as = assertions.deserialize(+ JSON.stringify([+ ...(statusAssertions || []),+ ...(headerAssertions || []),+ ]),+ );++ const data = (await res.json()) as RegionChecker;++ const _headers: Record<string, string> = {};+ res.headers.forEach((value, key) => (_headers[key] = value));++ if (as.length > 0) {+ for (const a of as) {+ const { success, message } = a.assert({+ body: "", // data.body ?? "",+ header: data.headers ?? {},+ status: data.status,+ });+ if (!success) {+ return { data, error: `Assertion error: ${message}` };+ }+ }+ } else {+ // default assertion if no assertions are provided+ if (res.status < 200 || res.status >= 300) {+ return {+ data,+ error: `Assertion error: The response status was not 2XX: ${data.status}.`,+ };+ }+ }++ return { data, error: undefined };+ } catch (error) {+ if (error instanceof Error && error.name === "AbortError") {+ return {+ error: `Abort error: request takes more then ${formatDuration(+ ABORT_TIMEOUT,+ )}.`,+ };+ }+ return {+ error: "Something went wrong. Please try again.",+ };+ }};function onValueChange(value: string) {@@ -153,6 +213,14 @@ export function MonitorForm({<TabsList><TabsTrigger value="request">Request</TabsTrigger><TabsTrigger value="scheduling">Scheduling</TabsTrigger>+ <TabsTrigger value="assertions">+ Assertions{" "}+ {_assertions.length ? (+ <Badge variant="secondary" className="ml-1">+ {_assertions.length}+ </Badge>+ ) : null}+ </TabsTrigger><TabsTrigger value="notifications">Notifications{" "}{defaultValues?.notifications?.length ? (@@ -176,6 +244,9 @@ export function MonitorForm({<TabsContent value="request"><SectionRequests {...{ form, plan, pingEndpoint }} /></TabsContent>+ <TabsContent value="assertions">+ <SectionAssertions {...{ form }} />+ </TabsContent><TabsContent value="scheduling"><SectionScheduling {...{ form, plan }} /></TabsContent>@@ -191,11 +262,14 @@ export function MonitorForm({</TabsContent>) : null}</Tabs>- <SaveButton- isPending={isPending}- isDirty={form.formState.isDirty}- onSubmit={form.handleSubmit(onSubmit)}- />+ <div className="grid gap-4 sm:flex sm:items-start sm:justify-end">+ <RequestTestButton {...{ form, pingEndpoint }} />+ <SaveButton+ isPending={isPending}+ isDirty={form.formState.isDirty}+ onSubmit={form.handleSubmit(onSubmit)}+ />+ </div></form></Form><FailedPingAlertConfirmationdiff --git a/apps/web/src/components/forms/monitor/general.tsx b/apps/web/src/components/forms/monitor/general.tsxindex 19d49937d..cccc6ab0a 100644--- a/apps/web/src/components/forms/monitor/general.tsx+++ b/apps/web/src/components/forms/monitor/general.tsx@@ -19,7 +19,6 @@ import {Switch,} from "@openstatus/ui";-import { TagBadge } from "@/components/monitor/tag-badge";import { SectionHeader } from "../shared/section-header";import { TagsMultiBox } from "./tags-multi-box";@@ -30,7 +29,6 @@ interface Props {}export function General({ form, tags }: Props) {- const watchTags = form.watch("tags");return (<div className="grid gap-4 sm:grid-cols-3 sm:gap-6"><SectionHeaderdiff --git a/apps/web/src/components/forms/monitor/request-test-button.tsx b/apps/web/src/components/forms/monitor/request-test-button.tsxindex 01aa0f36d..6519c8f1f 100644--- a/apps/web/src/components/forms/monitor/request-test-button.tsx+++ b/apps/web/src/components/forms/monitor/request-test-button.tsx@@ -2,6 +2,7 @@ import React from "react";import { Send } from "lucide-react";import type { UseFormReturn } from "react-hook-form";+import { deserialize } from "@openstatus/assertions";import type {InsertMonitor,MonitorFlyRegion,@@ -10,6 +11,8 @@ import {Button,Dialog,DialogContent,+ DialogHeader,+ DialogTitle,Select,SelectContent,SelectItem,@@ -26,15 +29,19 @@ import { RegionInfo } from "@/app/play/checker/[id]/_components/region-info";import { ResponseDetailTabs } from "@/app/play/checker/[id]/_components/response-detail-tabs";import type { RegionChecker } from "@/app/play/checker/[id]/utils";import { LoadingAnimation } from "@/components/loading-animation";-import { toastAction } from "@/lib/toast";+import { toast, toastAction } from "@/lib/toast";interface Props {form: UseFormReturn<InsertMonitor>;- pingEndpoint(region?: MonitorFlyRegion): Promise<RegionChecker>;+ pingEndpoint(+ region?: MonitorFlyRegion,+ ): Promise<{ data?: RegionChecker; error?: string }>;}export function RequestTestButton({ form, pingEndpoint }: Props) {- const [check, setCheck] = React.useState<RegionChecker | undefined>();+ const [check, setCheck] = React.useState<+ { data: RegionChecker; error?: string } | undefined+ >();const [value, setValue] = React.useState<MonitorFlyRegion>(flyRegions[0]);const [isPending, startTransition] = React.useTransition();@@ -50,13 +57,13 @@ export function RequestTestButton({ form, pingEndpoint }: Props) {startTransition(async () => {try {- const data = await pingEndpoint(value);- setCheck(data);- const isOk = data.status >= 200 && data.status < 300;+ const { data, error } = await pingEndpoint(value);+ if (data) setCheck({ data, error });+ const isOk = !error;if (isOk) {toastAction("test-success");} else {- toastAction("test-error");+ toast.error(error);}} catch {toastAction("error");@@ -66,6 +73,8 @@ export function RequestTestButton({ form, pingEndpoint }: Props) {const { flag } = flyRegionsDict[value as keyof typeof flyRegionsDict];+ const { statusAssertions, headerAssertions } = form.getValues();+return (<Dialog open={!!check} onOpenChange={() => setCheck(undefined)}><div className="ring-offset-background focus-within:ring-ring group flex h-10 items-center rounded-md bg-transparent text-sm focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2">@@ -74,7 +83,7 @@ export function RequestTestButton({ form, pingEndpoint }: Props) {onValueChange={(value: MonitorFlyRegion) => setValue(value)}><SelectTrigger- className="flex-1 rounded-r-none focus:ring-0"+ className="border-accent flex-1 rounded-r-none focus:ring-0"aria-label={value}><SelectValue>{flag}</SelectValue>@@ -97,27 +106,40 @@ export function RequestTestButton({ form, pingEndpoint }: Props) {onClick={onClick}disabled={isPending}className="h-full flex-1 rounded-l-none focus:ring-0"+ variant="secondary">{isPending ? (- <LoadingAnimation />+ <LoadingAnimation variant="inverse" />) : (<>- Ping <Send className="ml-2 h-4 w-4" />+ Test <Send className="ml-2 h-4 w-4" /></>)}</Button></TooltipTrigger><TooltipContent>- <p>Send a request to your endpoint</p>+ <p>Ping your endpoint</p></TooltipContent></Tooltip></TooltipProvider></div><DialogContent className="max-h-screen w-full overflow-auto sm:max-w-3xl sm:p-8">+ <DialogHeader>+ <DialogTitle>Response</DialogTitle>+ </DialogHeader>{check ? (<div className="grid gap-8">- <RegionInfo check={check} />- <ResponseDetailTabs timing={check.timing} headers={check.headers} />+ <RegionInfo check={check.data} error={check.error} />+ <ResponseDetailTabs+ timing={check.data.timing}+ headers={check.data.headers}+ assertions={deserialize(+ JSON.stringify([+ ...(statusAssertions || []),+ ...(headerAssertions || []),+ ]),+ )}+ /></div>) : null}</DialogContent>diff --git a/apps/web/src/components/forms/monitor/section-assertions.tsx b/apps/web/src/components/forms/monitor/section-assertions.tsxnew file mode 100644index 000000000..66e618aff--- /dev/null+++ b/apps/web/src/components/forms/monitor/section-assertions.tsx@@ -0,0 +1,192 @@+"use client";++import * as React from "react";+import { useFieldArray } from "react-hook-form";+import type { UseFormReturn } from "react-hook-form";++import {+ numberCompareDictionary,+ stringCompareDictionary,+} from "@openstatus/assertions";+import type { InsertMonitor } from "@openstatus/db/src/schema";+import {+ Button,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@openstatus/ui";++import { Icons } from "@/components/icons";+import { SectionHeader } from "../shared/section-header";++// IMPROVEMENT: use FormFields incl. error message++export const setEmptyOrStr = (v: unknown) => {+ if (typeof v === "string" && v.trim() === "") return undefined;+ return v;+};++interface Props {+ form: UseFormReturn<InsertMonitor>;+}++export function SectionAssertions({ form }: Props) {+ const statusAssertions = useFieldArray({+ control: form.control,+ name: "statusAssertions",+ });+ const headerAssertions = useFieldArray({+ control: form.control,+ name: "headerAssertions",+ });+ return (+ <div className="grid w-full gap-4">+ <SectionHeader+ title="Assertions"+ description={+ <>+ Validate the response to ensure your service is working as expected.+ <br />+ <span className="decoration-border underline underline-offset-4">+ By default, we check for a{" "}+ <span className="text-foreground font-medium">+ <code>2xx</code> status code+ </span>+ </span>+ .+ </>+ }+ />+ <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="text-muted-foreground col-span-2 text-sm">+ Status Code+ </p>+ <div className="col-span-3" />+ <Select+ {...form.register(`statusAssertions.${i}.compare`, {+ required: true,+ })}+ >+ <SelectTrigger className="col-span-3 w-full">+ <SelectValue defaultValue="eq" placeholder="Equal" />+ </SelectTrigger>+ <SelectContent>+ {Object.entries(numberCompareDictionary).map(([key, value]) => (+ <SelectItem key={key} value={key}>+ {value}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Input+ {...form.register(`statusAssertions.${i}.target`, {+ required: true,+ valueAsNumber: true,+ })}+ 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>+ ))}+ {headerAssertions.fields.map((f, i) => (+ <div key={f.id} className="grid grid-cols-12 items-center gap-4">+ <p className="text-muted-foreground col-span-2 text-sm">+ Response Header+ </p>+ <Input+ {...form.register(`headerAssertions.${i}.key`, {+ required: true,+ setValueAs: setEmptyOrStr,+ })}+ className="col-span-3"+ placeholder="X-Header"+ />++ <Select+ {...form.register(`headerAssertions.${i}.compare`, {+ required: true,+ })}+ >+ <SelectTrigger className="col-span-3 w-full">+ <SelectValue defaultValue="eq" placeholder="Equal" />+ </SelectTrigger>+ <SelectContent>+ {Object.entries(stringCompareDictionary).map(([key, value]) => (+ <SelectItem key={key} value={key}>+ {value}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>++ <Input+ {...form.register(`headerAssertions.${i}.target`, {+ required: true,+ setValueAs: setEmptyOrStr,+ })}+ 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 className="flex 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>+ </div>+ </div>+ );+}diff --git a/apps/web/src/components/forms/monitor/section-danger.tsx b/apps/web/src/components/forms/monitor/section-danger.tsxindex 3cb31af47..940466c1d 100644--- a/apps/web/src/components/forms/monitor/section-danger.tsx+++ b/apps/web/src/components/forms/monitor/section-danger.tsx@@ -19,6 +19,7 @@ import {import { LoadingAnimation } from "@/components/loading-animation";import { toastAction } from "@/lib/toast";import { api } from "@/trpc/client";+import { SectionHeader } from "../shared/section-header";interface Props {monitorId: number;@@ -44,13 +45,10 @@ export function SectionDanger({ monitorId }: Props) {return (<div className="grid w-full gap-4">- <div className="grid gap-1">- <h4 className="text-foreground font-medium">Delete monitor</h4>- <p className="text-muted-foreground">- This action cannot be undone. This will permanently delete the- monitor.- </p>- </div>+ <SectionHeader+ title="Danger Zone"+ description="This action cannot be undone. This will permanently delete the monitor."+ /><div><AlertDialog open={open} onOpenChange={setOpen}><AlertDialogTrigger asChild>diff --git a/apps/web/src/components/forms/monitor/section-limits.tsx b/apps/web/src/components/forms/monitor/section-limits.tsxnew file mode 100644index 000000000..24d30962a--- /dev/null+++ b/apps/web/src/components/forms/monitor/section-limits.tsx@@ -0,0 +1,102 @@+"use client";++import type { UseFormReturn } from "react-hook-form";++import type { InsertMonitor } from "@openstatus/db/src/schema";+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@openstatus/ui";++import { formatDuration } from "@/lib/utils";+import { SectionHeader } from "../shared/section-header";++interface Props {+ form: UseFormReturn<InsertMonitor>;+}++// FIXME: replace with enum+// TODO: can be also replaced by a custom number input with max value (+ validation)+const limits = [100, 250, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 40_000];++export function SectionLimits({ form }: Props) {+ return (+ <div className="grid w-full gap-4">+ <SectionHeader+ title="Response Time Limits"+ description="Check when your endpoint is taking too long to respond. And set the limit to be considered degraded."+ />+ <FormField+ control={form.control}+ name="id" // FIXME: should be something like 'limitDegraded'+ render={({ field }) => (+ <FormItem>+ <FormLabel>Degraded limit</FormLabel>+ <Select+ onValueChange={(value) => field.onChange(parseInt(value))}+ defaultValue={String(field.value)}+ >+ <FormControl>+ <SelectTrigger className="sm:w-[200px]">+ <SelectValue placeholder="Select" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {limits.map((limit) => (+ <SelectItem key={limit} value={String(limit)}>+ {formatDuration(limit)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ When the response time exceeds this limit, the monitor is will be+ considered as <span className="text-amber-500">degraded</span>.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="id" // FIXME: should be something like 'limitFailed'+ render={({ field }) => (+ <FormItem>+ <FormLabel>Failed limit</FormLabel>+ <Select+ onValueChange={(value) => field.onChange(parseInt(value))}+ defaultValue={String(field.value)}+ >+ <FormControl>+ <SelectTrigger className="sm:w-[200px]">+ <SelectValue placeholder="Select" />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {limits.map((limit) => (+ <SelectItem key={limit} value={String(limit)}>+ {formatDuration(limit)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormDescription>+ When the response time exceeds this limit, the monitor is will be+ considered as <span className="text-rose-500">failed</span>.+ </FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>+ );+}diff --git a/apps/web/src/components/forms/monitor/section-requests.tsx b/apps/web/src/components/forms/monitor/section-requests.tsxindex dfb9da46a..05da42726 100644--- a/apps/web/src/components/forms/monitor/section-requests.tsx+++ b/apps/web/src/components/forms/monitor/section-requests.tsx@@ -9,11 +9,7 @@ import {monitorMethods,monitorMethodsSchema,} from "@openstatus/db/src/schema";-import type {- InsertMonitor,- MonitorFlyRegion,- WorkspacePlan,-} from "@openstatus/db/src/schema";+import type { InsertMonitor, WorkspacePlan } from "@openstatus/db/src/schema";import {Button,FormControl,@@ -35,19 +31,17 @@ import {TooltipTrigger,} from "@openstatus/ui";-import type { RegionChecker } from "@/app/play/checker/[id]/utils";import { SectionHeader } from "../shared/section-header";import { RequestTestButton } from "./request-test-button";interface Props {form: UseFormReturn<InsertMonitor>;plan: WorkspacePlan;- pingEndpoint(region?: MonitorFlyRegion): Promise<RegionChecker>;}// TODO: add Dialog with response informations when pingEndpoint!-export function SectionRequests({ form, pingEndpoint }: Props) {+export function SectionRequests({ form }: Props) {const { fields, append, remove } = useFieldArray({name: "headers",control: form.control,@@ -83,12 +77,12 @@ export function SectionRequests({ form, pingEndpoint }: Props) {title="HTTP Request Settings"description="Create your HTTP. Add custom headers, payload and test your endpoint before submitting."/>- <div className="flex flex-col gap-4 sm:flex-row sm:items-end">+ <div className="grid gap-4 sm:grid-cols-7"><FormFieldcontrol={form.control}name="method"render={({ field }) => (- <FormItem>+ <FormItem className="sm:col-span-1"><FormLabel>Method</FormLabel><SelectonValueChange={(value) => {@@ -98,7 +92,7 @@ export function SectionRequests({ form, pingEndpoint }: Props) {defaultValue={field.value}><FormControl>- <SelectTrigger className="sm:w-[120px]">+ <SelectTrigger><SelectValue placeholder="Select" /></SelectTrigger></FormControl>@@ -118,7 +112,7 @@ export function SectionRequests({ form, pingEndpoint }: Props) {control={form.control}name="url"render={({ field }) => (- <FormItem className="w-full">+ <FormItem className="sm:col-span-5"><FormLabel>URL</FormLabel><FormControl>{/* <InputWithAddons@@ -136,7 +130,6 @@ export function SectionRequests({ form, pingEndpoint }: Props) {</FormItem>)}/>- <RequestTestButton {...{ form, pingEndpoint }} /></div><div className="space-y-2 sm:col-span-full"><FormLabel>Request Header</FormLabel>@@ -220,7 +213,13 @@ export function SectionRequests({ form, pingEndpoint }: Props) {{...field}/></FormControl>- <FormDescription>Write your json payload.</FormDescription>+ <FormDescription>+ Write your json payload. We automatically append{" "}+ <code>+ "Content-Type": "application/json"+ </code>{" "}+ to the request header.+ </FormDescription><FormMessage /></FormItem>)}diff --git a/apps/web/src/components/forms/shared/section-header.tsx b/apps/web/src/components/forms/shared/section-header.tsxindex 34505347a..b216debaf 100644--- a/apps/web/src/components/forms/shared/section-header.tsx+++ b/apps/web/src/components/forms/shared/section-header.tsx@@ -1,3 +1,5 @@+import * as React from "react";+import { cn } from "@/lib/utils";export function SectionHeader({@@ -6,7 +8,7 @@ export function SectionHeader({className,}: {title: string;- description: string;+ description: React.ReactNode;className?: string;}) {return (diff --git a/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx b/apps/web/src/components/monitor/status-code-badge.tsxsimilarity index 75%rename from apps/web/src/app/play/checker/[id]/_components/status-badge.tsxrename to apps/web/src/components/monitor/status-code-badge.tsxindex a9e6be43c..b5c21394b 100644--- a/apps/web/src/app/play/checker/[id]/_components/status-badge.tsx+++ b/apps/web/src/components/monitor/status-code-badge.tsx@@ -2,7 +2,8 @@ import { Badge } from "@openstatus/ui";import { cn } from "@/lib/utils";-export function StatusBadge({ statusCode }: { statusCode: number }) {+export function StatusCodeBadge({ statusCode }: { statusCode: number }) {+ const yellow = String(statusCode).startsWith("1");const green = String(statusCode).startsWith("2");const blue = String(statusCode).startsWith("3");const rose =@@ -17,6 +18,8 @@ export function StatusBadge({ statusCode }: { statusCode: number }) {blue,"border-rose-500/20 bg-rose-500/10 text-rose-800 dark:text-rose-300":rose,+ "border-yellow-500/20 bg-yellow-500/10 text-yellow-800 dark:text-yellow-300":+ yellow,})}>{statusCode}diff --git a/apps/web/src/components/monitor/status-dot-with-tooltip.tsx b/apps/web/src/components/monitor/status-dot-with-tooltip.tsxindex 51dd7fe74..856a77b33 100644--- a/apps/web/src/components/monitor/status-dot-with-tooltip.tsx+++ b/apps/web/src/components/monitor/status-dot-with-tooltip.tsx@@ -1,4 +1,3 @@-import type { Monitor } from "@openstatus/db/src/schema";import {Tooltip,TooltipContent,@@ -6,10 +5,10 @@ import {TooltipTrigger,} from "@openstatus/ui";+import type { StatusDotProps } from "./status-dot";import { StatusDot } from "./status-dot";-export interface StatusDotWithTooltipProps- extends Pick<Monitor, "active" | "status"> {}+export interface StatusDotWithTooltipProps extends StatusDotProps {}export function StatusDotWithTooltip({status,diff --git a/apps/web/src/lib/utils.ts b/apps/web/src/lib/utils.tsindex 17036ab58..e7a0fe9d3 100644--- a/apps/web/src/lib/utils.ts+++ b/apps/web/src/lib/utils.ts@@ -19,6 +19,21 @@ export function formatDateTime(date: Date) {return format(date, "LLL dd, y HH:mm:ss");}+export function formatDuration(ms: number) {+ if (ms < 0) ms = -ms;+ const time = {+ day: Math.floor(ms / 86400000),+ hour: Math.floor(ms / 3600000) % 24,+ min: Math.floor(ms / 60000) % 60,+ sec: Math.floor(ms / 1000) % 60,+ ms: Math.floor(ms) % 1000,+ };+ return Object.entries(time)+ .filter((val) => val[1] !== 0)+ .map(([key, val]) => `${val} ${key}${val !== 1 && key !== "ms" ? "s" : ""}`)+ .join(", ");+}+export function notEmpty<TValue>(value: TValue | null | undefined,): value is TValue {diff --git a/packages/api/package.json b/packages/api/package.jsonindex d21b3b3ad..12a7a052a 100644--- a/packages/api/package.json+++ b/packages/api/package.json@@ -9,6 +9,7 @@"dependencies": {"@clerk/nextjs": "4.29.9","@openstatus/analytics": "workspace:*",+ "@openstatus/assertions": "workspace:*","@openstatus/db": "workspace:*","@openstatus/emails": "workspace:*","@openstatus/plans": "workspace:*",diff --git a/packages/api/src/router/monitor.ts b/packages/api/src/router/monitor.tsindex 7e940c1f1..569d794c9 100644--- a/packages/api/src/router/monitor.ts+++ b/packages/api/src/router/monitor.ts@@ -1,13 +1,16 @@import { TRPCError } from "@trpc/server";import { z } from "zod";+import {+ Assertion,+ HeaderAssertion,+ serialize,+ StatusAssertion,+} from "@openstatus/assertions";import { and, eq, inArray, sql } from "@openstatus/db";import {insertMonitorSchema,- insertMonitorStatusSchema,monitor,- monitorPeriodicitySchema,- monitorStatusTable,monitorsToPages,monitorTag,monitorTagsToMonitors,@@ -15,7 +18,6 @@ import {notificationsToMonitors,page,selectMonitorSchema,- selectMonitorStatusSchema,selectMonitorTagSchema,selectNotificationSchema,} from "@openstatus/db/src/schema";@@ -59,8 +61,25 @@ export const monitorRouter = createTRPCRouter({}// FIXME: this is a hotfix- const { regions, headers, notifications, id, pages, tags, ...data } =- opts.input;+ const {+ regions,+ headers,+ notifications,+ id,+ pages,+ tags,+ statusAssertions,+ headerAssertions,+ ...data+ } = opts.input;++ const assertions: Assertion[] = [];+ for (const a of statusAssertions ?? []) {+ assertions.push(new StatusAssertion(a));+ }+ for (const a of headerAssertions ?? []) {+ assertions.push(new HeaderAssertion(a));+ }const newMonitor = await opts.ctx.db.insert(monitor)@@ -71,6 +90,7 @@ export const monitorRouter = createTRPCRouter({workspaceId: opts.ctx.workspace.id,regions: regions?.join(","),headers: headers ? JSON.stringify(headers) : undefined,+ assertions: assertions.length > 0 ? serialize(assertions) : undefined,}).returning().get();@@ -179,8 +199,24 @@ export const monitorRouter = createTRPCRouter({console.log(opts.input);- const { regions, headers, notifications, pages, tags, ...data } =- opts.input;+ const {+ regions,+ headers,+ notifications,+ pages,+ tags,+ statusAssertions,+ headerAssertions,+ ...data+ } = opts.input;++ const assertions: Assertion[] = [];+ for (const a of statusAssertions ?? []) {+ assertions.push(new StatusAssertion(a));+ }+ for (const a of headerAssertions ?? []) {+ assertions.push(new HeaderAssertion(a));+ }const currentMonitor = await opts.ctx.db.update(monitor)@@ -189,6 +225,7 @@ export const monitorRouter = createTRPCRouter({regions: regions?.join(","),updatedAt: new Date(),headers: headers ? JSON.stringify(headers) : undefined,+ assertions: serialize(assertions),}).where(and(diff --git a/packages/assertions/README.md b/packages/assertions/README.mdnew file mode 100644index 000000000..f3e9336e1--- /dev/null+++ b/packages/assertions/README.md@@ -0,0 +1,2 @@+Biggest props to [@chronark\_](https://twitter.com/chronark_/) for providing us+the snippets.diff --git a/packages/assertions/package.json b/packages/assertions/package.jsonnew file mode 100644index 000000000..1bd72924f--- /dev/null+++ b/packages/assertions/package.json@@ -0,0 +1,17 @@+{+ "name": "@openstatus/assertions",+ "version": "1.0.0",+ "description": "",+ "main": "src/index.ts",+ "scripts": {},+ "dependencies": {},+ "devDependencies": {+ "@openstatus/tsconfig": "workspace:*",+ "jsonpath-plus": "7.2.0",+ "typescript": "5.4.2",+ "zod": "3.22.2"+ },+ "keywords": [],+ "author": "",+ "license": "ISC"+}diff --git a/packages/assertions/src/dictionary.ts b/packages/assertions/src/dictionary.tsnew file mode 100644index 000000000..629bff60d--- /dev/null+++ b/packages/assertions/src/dictionary.ts@@ -0,0 +1,31 @@+import type { z } from "zod";++import type { numberCompare, stringCompare } from "./v1";++export const numberCompareDictionary: Record<+ z.infer<typeof numberCompare>,+ string+> = {+ eq: "Equal",+ not_eq: "Not Equal",+ gt: "Greater than",+ gte: "Greater than or equal",+ lt: "Less than",+ lte: "Less than or equal",+};++export const stringCompareDictionary: Record<+ z.infer<typeof stringCompare>,+ string+> = {+ contains: "Contains",+ not_contains: "Does not contain",+ eq: "Equal",+ not_eq: "Not Equal",+ empty: "Empty",+ not_empty: "Not Empty",+ gt: "Greater than",+ gte: "Greater than or equal",+ lt: "Less than",+ lte: "Less than or equal",+};diff --git a/packages/assertions/src/index.ts b/packages/assertions/src/index.tsnew file mode 100644index 000000000..c75e426c9--- /dev/null+++ b/packages/assertions/src/index.ts@@ -0,0 +1,4 @@+export * from "./dictionary";+export * from "./types";+export * from "./serializing";+export * from "./v1";diff --git a/packages/assertions/src/serializing.ts b/packages/assertions/src/serializing.tsnew file mode 100644index 000000000..213e902b8--- /dev/null+++ b/packages/assertions/src/serializing.ts@@ -0,0 +1,36 @@+import { z } from "zod";++import type { Assertion } from "./types";+import {+ base,+ HeaderAssertion,+ headerAssertion,+ JsonBodyAssertion,+ jsonBodyAssertion,+ StatusAssertion,+ statusAssertion,+ TextBodyAssertion,+ textBodyAssertion,+} from "./v1";++export function serialize(assertions: Assertion[]): string {+ return JSON.stringify(assertions.map((a) => a.schema));+}+export function deserialize(s: string): Assertion[] {+ const bases = z.array(base).parse(JSON.parse(s));+ return bases.map((b) => {+ switch (b.type) {+ case "status":+ return new StatusAssertion(statusAssertion.parse(b));+ case "header":+ return new HeaderAssertion(headerAssertion.parse(b));+ case "jsonBody":+ return new JsonBodyAssertion(jsonBodyAssertion.parse(b));+ case "textBody":+ return new TextBodyAssertion(textBodyAssertion.parse(b));++ default:+ throw new Error(`unknown assertion type: ${b.type}`);+ }+ });+}diff --git a/packages/assertions/src/types.ts b/packages/assertions/src/types.tsnew file mode 100644index 000000000..7ed97552e--- /dev/null+++ b/packages/assertions/src/types.ts@@ -0,0 +1,23 @@+import type { z } from "zod";++import type { assertion } from "./v1";++export type AssertionRequest = {+ body: string;+ header: Record<string, string>;+ status: number;+};++export type AssertionResult =+ | {+ success: true;+ message?: never;+ }+ | {+ success: false;+ message: string;+ };+export interface Assertion {+ schema: z.infer<typeof assertion>;+ assert: (req: AssertionRequest) => AssertionResult;+}diff --git a/packages/assertions/src/v1.ts b/packages/assertions/src/v1.tsnew file mode 100644index 000000000..02a11d7c2--- /dev/null+++ b/packages/assertions/src/v1.ts@@ -0,0 +1,293 @@+import { JSONPath } from "jsonpath-plus";+import { z } from "zod";++import type { Assertion, AssertionRequest, AssertionResult } from "./types";++export const stringCompare = z.enum([+ "contains",+ "not_contains",+ "eq",+ "not_eq",+ "empty",+ "not_empty",+ "gt",+ "gte",+ "lt",+ "lte",+]);+export const numberCompare = z.enum(["eq", "not_eq", "gt", "gte", "lt", "lte"]);++function evaluateNumber(+ value: number,+ compare: z.infer<typeof numberCompare>,+ target: number,+): AssertionResult {+ switch (compare) {+ case "eq":+ if (value !== target) {+ return {+ success: false,+ message: `Expected ${value} to be equal to ${target}`,+ };+ }+ break;+ case "not_eq":+ if (value === target) {+ return {+ success: false,+ message: `Expected ${value} to not be equal to ${target}`,+ };+ }+ break;+ case "gt":+ if (value <= target) {+ return {+ success: false,+ message: `Expected ${value} to be greater than ${target}`,+ };+ }+ break;+ case "gte":+ if (value < target) {+ return {+ success: false,+ message: `Expected ${value} to be greater than or equal to ${target}`,+ };+ }+ break;+ case "lt":+ if (value >= target) {+ return {+ success: false,+ message: `Expected ${value} to be less than ${target}`,+ };+ }+ break;+ case "lte":+ if (value > target) {+ return {+ success: false,+ message: `Expected ${value} to be less than or equal to ${target}`,+ };+ }+ break;+ }+ return { success: true };+}++function evaluateString(+ value: string,+ compare: z.infer<typeof stringCompare>,+ target: string,+): AssertionResult {+ switch (compare) {+ case "contains":+ if (!value.includes(target)) {+ return {+ success: false,+ message: `Expected ${value} to contain ${target}`,+ };+ }+ break;+ case "not_contains":+ if (value.includes(target)) {+ return {+ success: false,+ message: `Expected ${value} to not contain ${target}`,+ };+ }+ break;+ case "empty":+ if (value !== "") {+ return { success: false, message: `Expected ${value} to be empty` };+ }+ break;+ case "not_empty":+ if (value === "") {+ return { success: false, message: `Expected ${value} to not be empty` };+ }+ break;+ case "eq":+ if (value !== target) {+ return {+ success: false,+ message: `Expected ${value} to be equal to ${target}`,+ };+ }+ break;+ case "not_eq":+ if (value === target) {+ return {+ success: false,+ message: `Expected ${value} to not be equal to ${target}`,+ };+ }+ break;+ case "gt":+ if (value <= target) {+ return {+ success: false,+ message: `Expected ${value} to be greater than ${target}`,+ };+ }+ break;+ case "gte":+ if (value < target) {+ return {+ success: false,+ message: `Expected ${value} to be greater than or equal to ${target}`,+ };+ }+ break;+ case "lt":+ if (value >= target) {+ return {+ success: false,+ message: `Expected ${value} to be less than ${target}`,+ };+ }+ break;+ case "lte":+ if (value > target) {+ return {+ success: false,+ message: `Expected ${value} to be less than or equal to ${target}`,+ };+ }+ break;+ }+ return { success: true };+}++export const base = z+ .object({+ version: z.enum(["v1"]),+ type: z.string(),+ })+ .passthrough();+export const statusAssertion = base.merge(+ z.object({+ type: z.literal("status"),+ compare: numberCompare,+ target: z.number().int().positive(),+ }),+);++export const headerAssertion = base.merge(+ z.object({+ type: z.literal("header"),+ compare: stringCompare,+ key: z.string(),+ target: z.string(),+ }),+);++export const textBodyAssertion = base.merge(+ z.object({+ type: z.literal("textBody"),+ compare: stringCompare,+ target: z.string(),+ }),+);++export const jsonBodyAssertion = base.merge(+ z.object({+ type: z.literal("jsonBody"),+ path: z.string(), // https://www.npmjs.com/package/jsonpath-plus+ compare: stringCompare,+ target: z.string(),+ }),+);++export const assertion = z.discriminatedUnion("type", [+ statusAssertion,+ headerAssertion,+ textBodyAssertion,+ jsonBodyAssertion,+]);++export class StatusAssertion implements Assertion {+ readonly schema: z.infer<typeof statusAssertion>;++ constructor(schema: z.infer<typeof statusAssertion>) {+ this.schema = schema;+ }++ public assert(req: AssertionRequest): AssertionResult {+ const { success, message } = evaluateNumber(+ req.status,+ this.schema.compare,+ this.schema.target,+ );+ if (success) {+ return { success };+ }+ return { success, message: `Status: ${message}` };+ }+}++export class HeaderAssertion {+ readonly schema: z.infer<typeof headerAssertion>;++ constructor(schema: z.infer<typeof headerAssertion>) {+ this.schema = schema;+ }++ public assert(req: AssertionRequest): AssertionResult {+ const { success, message } = evaluateString(+ req.header[this.schema.key],+ this.schema.compare,+ this.schema.target,+ );+ if (success) {+ return { success };+ }+ return { success, message: `Header ${this.schema.key}: ${message}` };+ }+}++export class TextBodyAssertion {+ readonly schema: z.infer<typeof textBodyAssertion>;++ constructor(schema: z.infer<typeof textBodyAssertion>) {+ this.schema = schema;+ }++ public assert(req: AssertionRequest): AssertionResult {+ const { success, message } = evaluateString(+ req.body,+ this.schema.compare,+ this.schema.target,+ );+ if (success) {+ return { success };+ }+ return { success, message: `Body: ${message}` };+ }+}+export class JsonBodyAssertion implements Assertion {+ readonly schema: z.infer<typeof jsonBodyAssertion>;++ constructor(schema: z.infer<typeof jsonBodyAssertion>) {+ this.schema = schema;+ }++ public assert(req: AssertionRequest): AssertionResult {+ try {+ const json = JSON.parse(req.body);+ const value = JSONPath({ path: this.schema.path, json });+ const { success, message } = evaluateString(+ value,+ this.schema.compare,+ this.schema.target,+ );+ if (success) {+ return { success };+ }+ return { success, message: `Body: ${message}` };+ } catch (_e) {+ console.error("Unable to parse json");+ return { success: false, message: "Unable to parse json" };+ }+ }+}diff --git a/packages/assertions/tsconfig.json b/packages/assertions/tsconfig.jsonnew file mode 100644index 000000000..ec9f2821d--- /dev/null+++ b/packages/assertions/tsconfig.json@@ -0,0 +1,7 @@+{+ "extends": "@openstatus/tsconfig/base.json",+ "compilerOptions": {+ "lib": ["es2015", "dom"]+ },+ "include": ["src", "*.ts"]+}diff --git a/packages/db/drizzle/0022_chunky_rockslide.sql b/packages/db/drizzle/0022_chunky_rockslide.sqlnew file mode 100644index 000000000..4c6247f8c--- /dev/null+++ b/packages/db/drizzle/0022_chunky_rockslide.sql@@ -0,0 +1 @@+ALTER TABLE monitor ADD `assertions` text;\ No newline at end of filediff --git a/packages/db/drizzle/meta/0022_snapshot.json b/packages/db/drizzle/meta/0022_snapshot.jsonnew file mode 100644index 000000000..96fada26c--- /dev/null+++ b/packages/db/drizzle/meta/0022_snapshot.json@@ -0,0 +1,1612 @@+{+ "version": "5",+ "dialect": "sqlite",+ "id": "a53b01bf-cce5-411d-99cf-a0645f3bd125",+ "prevId": "44c2bbb5-69d5-40e8-b301-f2569bc2e499",+ "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_reports_to_pages": {+ "name": "status_reports_to_pages",+ "columns": {+ "page_id": {+ "name": "page_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_reports_to_pages_page_id_page_id_fk": {+ "name": "status_reports_to_pages_page_id_page_id_fk",+ "tableFrom": "status_reports_to_pages",+ "tableTo": "page",+ "columnsFrom": [+ "page_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "status_reports_to_pages_status_report_id_status_report_id_fk": {+ "name": "status_reports_to_pages_status_report_id_status_report_id_fk",+ "tableFrom": "status_reports_to_pages",+ "tableTo": "status_report",+ "columnsFrom": [+ "status_report_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {+ "status_reports_to_pages_page_id_status_report_id_pk": {+ "columns": [+ "page_id",+ "status_report_id"+ ],+ "name": "status_reports_to_pages_page_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+ },+ "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"+ }+ },+ "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+ },+ "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": "'other'"+ },+ "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+ },+ "assertions": {+ "name": "assertions",+ "type": "text",+ "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": {+ "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'))"+ }+ },+ "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": {}+ },+ "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": "''"+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": "''"+ },+ "photo_url": {+ "name": "photo_url",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "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'))"+ }+ },+ "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": {}+ },+ "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": {}+ },+ "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+ },+ "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": {+ "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+ }+ },+ "foreignKeys": {},+ "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+ },+ "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": {}+ }+ },+ "enums": {},+ "_meta": {+ "schemas": {},+ "tables": {},+ "columns": {}+ }+}\ No newline at end of filediff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.jsonindex 24efb5b40..a0e03c0fa 100644--- a/packages/db/drizzle/meta/_journal.json+++ b/packages/db/drizzle/meta/_journal.json@@ -155,6 +155,13 @@"when": 1710677383007,"tag": "0021_reflective_nico_minoru","breakpoints": true+ },+ {+ "idx": 22,+ "version": "5",+ "when": 1711307113089,+ "tag": "0022_chunky_rockslide",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/package.json b/packages/db/package.jsonindex 0d0550281..8c02d79db 100644--- a/packages/db/package.json+++ b/packages/db/package.json@@ -20,6 +20,7 @@"zod": "3.22.2"},"devDependencies": {+ "@openstatus/assertions": "workspace:*","@openstatus/tsconfig": "workspace:*","@types/node": "20.8.0","better-sqlite3": "9.4.1",diff --git a/packages/db/src/schema/monitors/monitor.ts b/packages/db/src/schema/monitors/monitor.tsindex af2905742..8388c2823 100644--- a/packages/db/src/schema/monitors/monitor.ts+++ b/packages/db/src/schema/monitors/monitor.ts@@ -41,6 +41,8 @@ export const monitor = sqliteTable("monitor", {method: text("method", { enum: monitorMethods }).default("GET"),workspaceId: integer("workspace_id").references(() => workspace.id),+ assertions: text("assertions"),+createdAt: integer("created_at", { mode: "timestamp" }).default(sql`(strftime('%s', 'now'))`,),diff --git a/packages/db/src/schema/monitors/validation.ts b/packages/db/src/schema/monitors/validation.tsindex 0f6f01e47..69dc675f1 100644--- a/packages/db/src/schema/monitors/validation.ts+++ b/packages/db/src/schema/monitors/validation.ts@@ -1,6 +1,8 @@import { createInsertSchema, createSelectSchema } from "drizzle-zod";import { z } from "zod";+import * as assertions from "@openstatus/assertions";+import {flyRegions,monitorJobTypes,@@ -73,6 +75,8 @@ export const insertMonitorSchema = createInsertSchema(monitor, {pages: z.array(z.number()).optional().default([]),body: z.string().default("").optional(),tags: z.array(z.number()).optional().default([]),+ statusAssertions: z.array(assertions.statusAssertion).optional(),+ headerAssertions: z.array(assertions.headerAssertion).optional(),});export type InsertMonitor = z.infer<typeof insertMonitorSchema>;diff --git a/packages/tinybird/_migration/ping_response.datasource b/packages/tinybird/_migration/ping_response.datasourceindex d5fbc382e..10b3ffa33 100644--- a/packages/tinybird/_migration/ping_response.datasource+++ b/packages/tinybird/_migration/ping_response.datasource@@ -1,17 +1,19 @@-VERSION 7+VERSION 8SCHEMA >`latency` Int64 `json:$.latency`,`monitorId` String `json:$.monitorId`,`region` LowCardinality(String) `json:$.region`,`statusCode` Nullable(Int16) `json:$.statusCode`,+ `error` Int8 `json:$.error`,`timestamp` Int64 `json:$.timestamp`,`url` String `json:$.url`,`workspaceId` String `json:$.workspaceId`,`cronTimestamp` Int64 `json:$.cronTimestamp`,`message` Nullable(String) `json:$.message`,`timing` Nullable(String) `json:$.timing`,- `headers` Nullable(String) `json:$.headers`+ `headers` Nullable(String) `json:$.headers`,+ `assertions` Nullable(String) `json:$.assertions`ENGINE "MergeTree"ENGINE_SORTING_KEY "monitorId, cronTimestamp"diff --git a/packages/tinybird/_migration/ping_response__v6.datasource b/packages/tinybird/_migration/ping_response__v6.datasourcedeleted file mode 100644index 62ce56dce..000000000--- a/packages/tinybird/_migration/ping_response__v6.datasource+++ /dev/null@@ -1,16 +0,0 @@-VERSION 6--SCHEMA >- `latency` Int64 `json:$.latency`,- `monitorId` String `json:$.monitorId`,- `region` LowCardinality(String) `json:$.region`,- `statusCode` Nullable(Int16) `json:$.statusCode`,- `timestamp` Int64 `json:$.timestamp`,- `url` String `json:$.url`,- `workspaceId` String `json:$.workspaceId`,- `cronTimestamp` Int64 `json:$.cronTimestamp`,- `message` Nullable(String) `json:$.message`--ENGINE "MergeTree"-ENGINE_SORTING_KEY "monitorId, cronTimestamp"-ENGINE_PARTITION_KEY "toYYYYMM(fromUnixTimestamp64Milli(cronTimestamp))"\ No newline at end of filediff --git a/packages/tinybird/_migration/tb_backfill_populate.pipe b/packages/tinybird/_migration/tb_backfill_populate.pipenew file mode 100644index 000000000..848b8974a--- /dev/null+++ b/packages/tinybird/_migration/tb_backfill_populate.pipe@@ -0,0 +1,21 @@+NODE mat_node+SQL >++ SELECT+ latency,+ monitorId,+ toLowCardinality(region) region,+ statusCode,+ if(statusCode >= 200 AND statusCode < 300, toInt8(0), toInt8(1)) AS error,+ timestamp,+ url,+ workspaceId,+ cronTimestamp,+ message,+ timing,+ headers,+ FROM ping_response__v7+ WHERE fromUnixTimestamp64Milli(cronTimestamp) <= '2024-03-29 13:16:00.000'++TYPE materialized+DATASOURCE ping_response__v8\ No newline at end of filediff --git a/packages/tinybird/_migration/tb_backfill_populate__v7.pipe b/packages/tinybird/_migration/tb_backfill_populate__v7.pipedeleted file mode 100644index b68d93a5e..000000000--- a/packages/tinybird/_migration/tb_backfill_populate__v7.pipe+++ /dev/null@@ -1,18 +0,0 @@-NODE mat_node-SQL >-- SELECT- latency,- monitorId,- toLowCardinality(region) region,- statusCode,- timestamp,- url,- workspaceId,- cronTimestamp,- message- FROM ping_response__v6- WHERE fromUnixTimestamp64Milli(cronTimestamp) <= '2024-01-16 18:16:00.000'--TYPE materialized-DATASOURCE ping_response__v7\ No newline at end of filediff --git a/packages/tinybird/_migration/tb_datasource_union.pipe b/packages/tinybird/_migration/tb_datasource_union.pipeindex 8c0033dee..2b60019c7 100644--- a/packages/tinybird/_migration/tb_datasource_union.pipe+++ b/packages/tinybird/_migration/tb_datasource_union.pipe@@ -1,6 +1,6 @@NODE union_allSQL >- SELECT count() FROM ping_response__v7+ SELECT count() FROM ping_response__v8UNION ALL- SELECT count() FROM ping_response__v6+ SELECT count() FROM ping_response__v7diff --git a/packages/tinybird/_migration/tb_materialize_until_change_ingest.pipe b/packages/tinybird/_migration/tb_materialize_until_change_ingest.pipenew file mode 100644index 000000000..bff97f1b1--- /dev/null+++ b/packages/tinybird/_migration/tb_materialize_until_change_ingest.pipe@@ -0,0 +1,21 @@+NODE mat_node+SQL >++ SELECT+ latency,+ monitorId,+ toLowCardinality(region) region,+ statusCode,+ if(statusCode >= 200 AND statusCode < 300, toInt8(0), toInt8(1)) AS error,+ timestamp,+ url,+ workspaceId,+ cronTimestamp,+ message,+ timing,+ headers,+ FROM ping_response__v7+ WHERE fromUnixTimestamp64Milli(cronTimestamp) > '2023-03-29 13:16:00.000'++TYPE materialized+DATASOURCE ping_response__v8\ No newline at end of filediff --git a/packages/tinybird/_migration/tb_materialized_until_change_ingest__v7.pipe b/packages/tinybird/_migration/tb_materialized_until_change_ingest__v7.pipedeleted file mode 100644index 7fa2fa138..000000000--- a/packages/tinybird/_migration/tb_materialized_until_change_ingest__v7.pipe+++ /dev/null@@ -1,18 +0,0 @@-NODE mat_node-SQL >-- SELECT- latency,- monitorId,- toLowCardinality(region) region,- statusCode,- timestamp,- url,- workspaceId,- cronTimestamp,- message- FROM ping_response__v6- WHERE fromUnixTimestamp64Milli(cronTimestamp) > '2023-11-16 18:16:00.000'--TYPE materialized-DATASOURCE ping_response__v7\ No newline at end of filediff --git a/packages/tinybird/pipes/__ttl_14d.pipe b/packages/tinybird/pipes/__ttl_14d.pipeindex dd942420c..f5969b226 100644--- a/packages/tinybird/pipes/__ttl_14d.pipe+++ b/packages/tinybird/pipes/__ttl_14d.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_14d_0SQL >@@ -7,6 +7,7 @@ SQL >toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,latency,monitorId,+ error,region,statusCode,url,@@ -15,6 +16,6 @@ SQL >FROM ping_response__v7TYPE materialized-DATASOURCE __ttl_14d_mv__v0+DATASOURCE __ttl_14d_mv__v1diff --git a/packages/tinybird/pipes/__ttl_14d_chart_get.pipe b/packages/tinybird/pipes/__ttl_14d_chart_get.pipeindex 325618689..24a12bbe7 100644--- a/packages/tinybird/pipes/__ttl_14d_chart_get.pipe+++ b/packages/tinybird/pipes/__ttl_14d_chart_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_14d_chart_get_endpoint_read_2504" READ+VERSION 1NODE __ttl_14d_chart_get_0SQL >@@ -18,7 +16,7 @@ SQL >round(quantile(0.9)(latency)) as p90Latency,round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency- FROM __ttl_14d_mv__v0+ FROM __ttl_14d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_14d_metrics_get.pipe b/packages/tinybird/pipes/__ttl_14d_metrics_get.pipeindex d31fdacb0..b0c9cccbb 100644--- a/packages/tinybird/pipes/__ttl_14d_metrics_get.pipe+++ b/packages/tinybird/pipes/__ttl_14d_metrics_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_14d_metrics_get_endpoint_read_3564" READ+VERSION 1NODE __ttl_14d_metrics_get_0SQL >@@ -13,9 +11,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_14d_mv__v0+ FROM __ttl_14d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}@@ -28,9 +26,9 @@ SQL >round(quantile(0.95)(latency)) AS p95Latency,round(quantile(0.99)(latency)) AS p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant- FROM __ttl_45d_mv__v0+ FROM __ttl_45d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_14d_metrics_get_by_region.pipe b/packages/tinybird/pipes/__ttl_14d_metrics_get_by_region.pipeindex 9cc1dadf2..02538b2c4 100644--- a/packages/tinybird/pipes/__ttl_14d_metrics_get_by_region.pipe+++ b/packages/tinybird/pipes/__ttl_14d_metrics_get_by_region.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_14d_metrics_get_by_region_endpoint_read_0048" READ+VERSION 1NODE __ttl_14d_metrics_get_by_region_0SQL >@@ -14,9 +12,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_14d_mv__v0+ FROM __ttl_14d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1d.pipe b/packages/tinybird/pipes/__ttl_1d.pipeindex 45366f12f..e12b539e5 100644--- a/packages/tinybird/pipes/__ttl_1d.pipe+++ b/packages/tinybird/pipes/__ttl_1d.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_1d_0SQL >@@ -7,15 +7,16 @@ SQL >toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,latency,monitorId,+ error,region,statusCode,url,workspaceId,timestamp,cronTimestamp- FROM ping_response__v7+ FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_1d_mv__v0+DATASOURCE __ttl_1d_mv__v1diff --git a/packages/tinybird/pipes/__ttl_1d_chart_get.pipe b/packages/tinybird/pipes/__ttl_1d_chart_get.pipeindex fc631bddf..bea1ba3d0 100644--- a/packages/tinybird/pipes/__ttl_1d_chart_get.pipe+++ b/packages/tinybird/pipes/__ttl_1d_chart_get.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1TOKEN "__ttl_1d_chart_get_endpoint_read_4815" READ@@ -18,7 +18,7 @@ SQL >round(quantile(0.9)(latency)) as p90Latency,round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency- FROM __ttl_1d_mv__v0+ FROM __ttl_1d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1d_list_get.pipe b/packages/tinybird/pipes/__ttl_1d_list_get.pipeindex b72aff148..4a92e68e0 100644--- a/packages/tinybird/pipes/__ttl_1d_list_get.pipe+++ b/packages/tinybird/pipes/__ttl_1d_list_get.pipe@@ -1,13 +1,11 @@-VERSION 0--TOKEN "__ttl_1d_list_get__v0_endpoint_read_1695" READ+VERSION 1NODE __ttl_1d_list_get__v0_0SQL >%- SELECT latency, monitorId, region, statusCode, timestamp, url, workspaceId, cronTimestamp- FROM __ttl_1d_mv__v0+ SELECT latency, monitorId, error, region, statusCode, timestamp, url, workspaceId, cronTimestamp+ FROM __ttl_1d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1d_metrics_get.pipe b/packages/tinybird/pipes/__ttl_1d_metrics_get.pipeindex a3842bc74..6579f2c39 100644--- a/packages/tinybird/pipes/__ttl_1d_metrics_get.pipe+++ b/packages/tinybird/pipes/__ttl_1d_metrics_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_1d_metrics_get_endpoint_read_1167" READ+VERSION 1NODE __ttl_1d_metrics_get_0SQL >@@ -13,9 +11,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_1d_mv__v0+ FROM __ttl_1d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}@@ -28,9 +26,9 @@ SQL >round(quantile(0.95)(latency)) AS p95Latency,round(quantile(0.99)(latency)) AS p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant- FROM __ttl_3d_mv__v0+ FROM __ttl_3d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1d_metrics_get_by_region.pipe b/packages/tinybird/pipes/__ttl_1d_metrics_get_by_region.pipeindex 3c1f16f62..97c5e5eed 100644--- a/packages/tinybird/pipes/__ttl_1d_metrics_get_by_region.pipe+++ b/packages/tinybird/pipes/__ttl_1d_metrics_get_by_region.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_1d_metrics_get_by_region_endpoint_read_3463" READ+VERSION 1NODE __ttl_1d_metrics_get_by_region_0SQL >@@ -14,8 +12,8 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok- FROM __ttl_1d_mv__v0+ count(if(error = 0, 1, NULL)) AS ok+ FROM __ttl_1d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1h.pipe b/packages/tinybird/pipes/__ttl_1h.pipeindex d8b40298e..3886bb361 100644--- a/packages/tinybird/pipes/__ttl_1h.pipe+++ b/packages/tinybird/pipes/__ttl_1h.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_1h_0SQL >@@ -7,15 +7,16 @@ SQL >toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,latency,monitorId,+ error,region,statusCode,url,workspaceId,timestamp,cronTimestamp- FROM ping_response__v7+ FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_1h_mv__v0+DATASOURCE __ttl_1h_mv__v1diff --git a/packages/tinybird/pipes/__ttl_1h_chart_get.pipe b/packages/tinybird/pipes/__ttl_1h_chart_get.pipeindex e40c9c4f6..f776c2d56 100644--- a/packages/tinybird/pipes/__ttl_1h_chart_get.pipe+++ b/packages/tinybird/pipes/__ttl_1h_chart_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_1h_chart_get__v0_endpoint_read_3603" READ+VERSION 1NODE __ttl_1h_chart_get_0SQL >@@ -18,7 +16,7 @@ SQL >round(quantile(0.9)(latency)) as p90Latency,round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency- FROM __ttl_1h_mv__v0+ FROM __ttl_1h_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1h_last_timestamp_monitor_get.pipe b/packages/tinybird/pipes/__ttl_1h_last_timestamp_monitor_get.pipeindex 4a20095d3..92dbc1b9e 100644--- a/packages/tinybird/pipes/__ttl_1h_last_timestamp_monitor_get.pipe+++ b/packages/tinybird/pipes/__ttl_1h_last_timestamp_monitor_get.pipe@@ -1,13 +1,11 @@-VERSION 0--TOKEN "__ttl_1h_last_timestamp_monitor_get__v0_endpoint_read_5766" READ+VERSION 1NODE __ttl_1h_last_timestamp_monitor_get__v0_0SQL >%SELECT max(cronTimestamp) as cronTimestamp- FROM __ttl_1h_mv__v0+ FROM __ttl_1h_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1h_last_timestamp_workspace_get.pipe b/packages/tinybird/pipes/__ttl_1h_last_timestamp_workspace_get.pipeindex c27ce7111..a86ee3131 100644--- a/packages/tinybird/pipes/__ttl_1h_last_timestamp_workspace_get.pipe+++ b/packages/tinybird/pipes/__ttl_1h_last_timestamp_workspace_get.pipe@@ -1,13 +1,11 @@-VERSION 0--TOKEN "__ttl_1h_last_timestamp_workspace_get__v0_endpoint_read_5322" READ+VERSION 1NODE __ttl_1h_last_timestamp_workspace_get__v0_0SQL >%SELECT max(cronTimestamp) as cronTimestamp- FROM __ttl_1h_mv__v0+ FROM __ttl_1h_mv__v1WHERE workspaceId = {{ String(workspaceId, '1') }}diff --git a/packages/tinybird/pipes/__ttl_1h_list_get.pipe b/packages/tinybird/pipes/__ttl_1h_list_get.pipeindex 15f110233..2231a81cf 100644--- a/packages/tinybird/pipes/__ttl_1h_list_get.pipe+++ b/packages/tinybird/pipes/__ttl_1h_list_get.pipe@@ -1,14 +1,12 @@-VERSION 0--TOKEN "__ttl_1h_list_get__v0_endpoint_read_0371" READ+VERSION 1NODE __ttl_1h_list_get__v0_0SQL >%-- FIXME: `timestamp` is missing on 1h, 3d, 7d, 45d mv!- SELECT latency, monitorId, region, statusCode, url, workspaceId, cronTimestamp, timestamp- FROM __ttl_1h_mv__v0+ SELECT latency, monitorId, error, region, statusCode, url, workspaceId, cronTimestamp, timestamp+ FROM __ttl_1h_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1h_metrics_get.pipe b/packages/tinybird/pipes/__ttl_1h_metrics_get.pipeindex 9403bde73..205aa2f5b 100644--- a/packages/tinybird/pipes/__ttl_1h_metrics_get.pipe+++ b/packages/tinybird/pipes/__ttl_1h_metrics_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_1h_metrics_get__v0_endpoint_read_0457" READ+VERSION 1NODE __ttl_1h_metrics_get_0SQL >@@ -13,9 +11,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_1h_mv__v0+ FROM __ttl_1h_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}@@ -28,9 +26,9 @@ SQL >round(quantile(0.95)(latency)) AS p95Latency,round(quantile(0.99)(latency)) AS p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant- FROM __ttl_1d_mv__v0+ FROM __ttl_1d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_1h_metrics_get_by_region.pipe b/packages/tinybird/pipes/__ttl_1h_metrics_get_by_region.pipeindex f41865eb8..e17730b1c 100644--- a/packages/tinybird/pipes/__ttl_1h_metrics_get_by_region.pipe+++ b/packages/tinybird/pipes/__ttl_1h_metrics_get_by_region.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_1h_metrics_get_by_region__v0_endpoint_read_0839" READ+VERSION 1NODE __ttl_1h_metrics_get_by_region_0SQL >@@ -14,8 +12,8 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok- FROM __ttl_1h_mv__v0+ count(if(error = 0, 1, NULL)) AS ok,+ FROM __ttl_1h_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_3d.pipe b/packages/tinybird/pipes/__ttl_3d.pipeindex 75d739963..a16114be7 100644--- a/packages/tinybird/pipes/__ttl_3d.pipe+++ b/packages/tinybird/pipes/__ttl_3d.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_3d_0SQL >@@ -7,14 +7,15 @@ SQL >toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,latency,monitorId,+ error,region,statusCode,url,workspaceId,cronTimestamp- FROM ping_response__v7+ FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_3d_mv__v0+DATASOURCE __ttl_3d_mv__v1diff --git a/packages/tinybird/pipes/__ttl_3d_chart_get.pipe b/packages/tinybird/pipes/__ttl_3d_chart_get.pipeindex 24589a86c..49970f659 100644--- a/packages/tinybird/pipes/__ttl_3d_chart_get.pipe+++ b/packages/tinybird/pipes/__ttl_3d_chart_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_3d_chart_get_endpoint_read_5551" READ+VERSION 1NODE __ttl_3d_chart_get_0SQL >diff --git a/packages/tinybird/pipes/__ttl_3d_metrics_get.pipe b/packages/tinybird/pipes/__ttl_3d_metrics_get.pipeindex 1ed3d3df5..5d80395a8 100644--- a/packages/tinybird/pipes/__ttl_3d_metrics_get.pipe+++ b/packages/tinybird/pipes/__ttl_3d_metrics_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_3d_metrics_get_endpoint_read_5801" READ+VERSION 1NODE __ttl_3d_metrics_get_0SQL >@@ -13,9 +11,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_3d_mv__v0+ FROM __ttl_3d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}@@ -28,9 +26,9 @@ SQL >round(quantile(0.95)(latency)) AS p95Latency,round(quantile(0.99)(latency)) AS p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant- FROM __ttl_7d_mv__v0+ FROM __ttl_7d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_3d_metrics_get_by_region.pipe b/packages/tinybird/pipes/__ttl_3d_metrics_get_by_region.pipeindex 938dd4f62..93a790e13 100644--- a/packages/tinybird/pipes/__ttl_3d_metrics_get_by_region.pipe+++ b/packages/tinybird/pipes/__ttl_3d_metrics_get_by_region.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_3d_metrics_get_by_region__v0_endpoint_read_3349" READ+VERSION 1NODE __ttl_3d_metrics_get_by_region_0SQL >@@ -14,7 +12,7 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestampFROM __ttl_3d_mv__v0WHEREdiff --git a/packages/tinybird/pipes/__ttl_45d.pipe b/packages/tinybird/pipes/__ttl_45d.pipeindex 779a9869e..f7287ee2c 100644--- a/packages/tinybird/pipes/__ttl_45d.pipe+++ b/packages/tinybird/pipes/__ttl_45d.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_45d_0SQL >@@ -12,9 +12,9 @@ SQL >url,workspaceId,cronTimestamp- FROM ping_response__v7+ FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_45d_mv__v0+DATASOURCE __ttl_45d_mv__v1diff --git a/packages/tinybird/pipes/__ttl_45d_all.pipe b/packages/tinybird/pipes/__ttl_45d_all.pipeindex a24b5c19b..3956a0fa0 100644--- a/packages/tinybird/pipes/__ttl_45d_all.pipe+++ b/packages/tinybird/pipes/__ttl_45d_all.pipe@@ -1,11 +1,11 @@-VERSION 0+VERSION 1NODE __ttl_45d_all_0SQL >- SELECT toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time, * FROM ping_response__v7+ SELECT toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time, * FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_45d_all_mv__v0+DATASOURCE __ttl_45d_all_mv__v1diff --git a/packages/tinybird/pipes/__ttl_45d_all_details_get.pipe b/packages/tinybird/pipes/__ttl_45d_all_details_get.pipeindex 1db5c96c2..bfec76174 100644--- a/packages/tinybird/pipes/__ttl_45d_all_details_get.pipe+++ b/packages/tinybird/pipes/__ttl_45d_all_details_get.pipe@@ -1,13 +1,11 @@-VERSION 0--TOKEN "__ttl_45d_all_details_get__v0_endpoint_read_7742" READ+VERSION 1NODE __ttl_45d_all_details_get_0SQL >%SELECT *- from __ttl_45d_all_mv__v0+ from __ttl_45d_all_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_45d_count.pipe b/packages/tinybird/pipes/__ttl_45d_count.pipeindex 2f921cf2e..3b277392d 100644--- a/packages/tinybird/pipes/__ttl_45d_count.pipe+++ b/packages/tinybird/pipes/__ttl_45d_count.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1DESCRIPTION >TODO: descripe what it is for!@@ -12,14 +12,14 @@ SQL >monitorId,url,countState() AS count,- countState(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok- FROM __ttl_45d_mv__v0+ countState(if(error = 0, 1, NULL)) AS ok+ FROM __ttl_45d_mv__v1GROUP BYtime,monitorId,urlTYPE materialized-DATASOURCE __ttl_45d_count_mv__v0+DATASOURCE __ttl_45d_count_mv__v1diff --git a/packages/tinybird/pipes/__ttl_45d_count_get.pipe b/packages/tinybird/pipes/__ttl_45d_count_get.pipeindex 7aa520164..42ebfd0f5 100644--- a/packages/tinybird/pipes/__ttl_45d_count_get.pipe+++ b/packages/tinybird/pipes/__ttl_45d_count_get.pipe@@ -1,13 +1,11 @@-VERSION 0--TOKEN "__ttl_45d_count_get__v0_endpoint_read_2389" READ+VERSION 1NODE __ttl_45d_count_get_0SQL >%SELECT time as day, countMerge(count) as count, countMerge(ok) as ok- FROM __ttl_45d_count_mv__v0+ FROM __ttl_45d_count_mv__v1WHEREmonitorId = {{ String(monitorId, '4') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_7d.pipe b/packages/tinybird/pipes/__ttl_7d.pipeindex 13e4917f9..f4d7e5a4a 100644--- a/packages/tinybird/pipes/__ttl_7d.pipe+++ b/packages/tinybird/pipes/__ttl_7d.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_7d_0SQL >@@ -7,14 +7,15 @@ SQL >toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time,latency,monitorId,+ errorregion,statusCode,url,workspaceId,cronTimestamp- FROM ping_response__v7+ FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_7d_mv__v0+DATASOURCE __ttl_7d_mv__v1diff --git a/packages/tinybird/pipes/__ttl_7d_all.pipe b/packages/tinybird/pipes/__ttl_7d_all.pipeindex 365d0710a..387f5981d 100644--- a/packages/tinybird/pipes/__ttl_7d_all.pipe+++ b/packages/tinybird/pipes/__ttl_7d_all.pipe@@ -1,11 +1,11 @@-VERSION 0+VERSION 1NODE __ttl_7d_all_0SQL >- SELECT toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time, * FROM ping_response__v7+ SELECT toDateTime(fromUnixTimestamp64Milli(cronTimestamp)) AS time, * FROM ping_response__v8TYPE materialized-DATASOURCE __ttl_7d_all_mv__v0+DATASOURCE __ttl_7d_all_mv__v1diff --git a/packages/tinybird/pipes/__ttl_7d_all_details_get.pipe b/packages/tinybird/pipes/__ttl_7d_all_details_get.pipeindex 61a402fdf..67612442a 100644--- a/packages/tinybird/pipes/__ttl_7d_all_details_get.pipe+++ b/packages/tinybird/pipes/__ttl_7d_all_details_get.pipe@@ -1,13 +1,11 @@-VERSION 0--TOKEN "__ttl_7d_all_details_get__v0_endpoint_read_7052" READ+VERSION 1NODE __ttl_7d_all_details_get_0SQL >%SELECT *- from __ttl_7d_all_mv__v0+ from __ttl_7d_all_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_7d_chart_get.pipe b/packages/tinybird/pipes/__ttl_7d_chart_get.pipeindex 3f6d99af1..1e11286a9 100644--- a/packages/tinybird/pipes/__ttl_7d_chart_get.pipe+++ b/packages/tinybird/pipes/__ttl_7d_chart_get.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_7d_chart_get_endpoint_read_8119" READ+VERSION 1NODE __ttl_7d_chart_get_0SQL >@@ -18,7 +16,7 @@ SQL >round(quantile(0.9)(latency)) as p90Latency,round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency- FROM __ttl_7d_mv__v0+ FROM __ttl_7d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_7d_count.pipe b/packages/tinybird/pipes/__ttl_7d_count.pipeindex c1f76a6c8..78527c1c2 100644--- a/packages/tinybird/pipes/__ttl_7d_count.pipe+++ b/packages/tinybird/pipes/__ttl_7d_count.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1DESCRIPTION >TODO: descripe what it is for!@@ -12,7 +12,7 @@ SQL >monitorId,url,countState() AS count,- countState(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok+ countState(if(error = 0, 1, NULL)) AS okFROM __ttl_45d_mv__v0GROUP BYtime,@@ -20,6 +20,6 @@ SQL >urlTYPE materialized-DATASOURCE __ttl_7d_count_mv__v0+DATASOURCE __ttl_7d_count_mv__v1diff --git a/packages/tinybird/pipes/__ttl_7d_count_get.pipe b/packages/tinybird/pipes/__ttl_7d_count_get.pipeindex 62b206b9e..6202a353b 100644--- a/packages/tinybird/pipes/__ttl_7d_count_get.pipe+++ b/packages/tinybird/pipes/__ttl_7d_count_get.pipe@@ -1,11 +1,11 @@-VERSION 0+VERSION 1NODE __ttl_7d_count_get_0SQL >%SELECT time as day, countMerge(count) as count, countMerge(ok) as ok- FROM __ttl_7d_count_mv__v0+ FROM __ttl_7d_count_mv__v1WHEREmonitorId = {{ String(monitorId, '4') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_7d_metrics_get.pipe b/packages/tinybird/pipes/__ttl_7d_metrics_get.pipeindex 2e54597b1..cf5dab69f 100644--- a/packages/tinybird/pipes/__ttl_7d_metrics_get.pipe+++ b/packages/tinybird/pipes/__ttl_7d_metrics_get.pipe@@ -1,4 +1,4 @@-VERSION 0+VERSION 1NODE __ttl_7d_metrics_get_0SQL >@@ -11,9 +11,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_7d_mv__v0+ FROM __ttl_7d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}@@ -26,9 +26,9 @@ SQL >round(quantile(0.95)(latency)) AS p95Latency,round(quantile(0.99)(latency)) AS p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,NULL as lastTimestamp -- no need to query the `lastTimestamp` as not relevant- FROM __ttl_14d_mv__v0+ FROM __ttl_14d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/pipes/__ttl_7d_metrics_get_by_region.pipe b/packages/tinybird/pipes/__ttl_7d_metrics_get_by_region.pipeindex 429e1216c..43c9148d7 100644--- a/packages/tinybird/pipes/__ttl_7d_metrics_get_by_region.pipe+++ b/packages/tinybird/pipes/__ttl_7d_metrics_get_by_region.pipe@@ -1,6 +1,4 @@-VERSION 0--TOKEN "__ttl_7d_metrics_get_by_region__v0_endpoint_read_4172" READ+VERSION 1NODE __ttl_7d_metrics_get_by_region_0SQL >@@ -14,9 +12,9 @@ SQL >round(quantile(0.95)(latency)) as p95Latency,round(quantile(0.99)(latency)) as p99Latency,count() as count,- count(multiIf((statusCode >= 200) AND (statusCode <= 299), 1, NULL)) AS ok,+ count(if(error = 0, 1, NULL)) AS ok,max(cronTimestamp) AS lastTimestamp- FROM __ttl_7d_mv__v0+ FROM __ttl_7d_mv__v1WHEREmonitorId = {{ String(monitorId, '1') }}{% if defined(url) %} AND url = {{ String(url) }} {% end %}diff --git a/packages/tinybird/src/os-client.ts b/packages/tinybird/src/os-client.tsindex 726615687..af2bd8ea5 100644--- a/packages/tinybird/src/os-client.ts+++ b/packages/tinybird/src/os-client.ts@@ -11,6 +11,8 @@ const MIN_CACHE = isProd ? 60 : DEV_CACHE; // 60sconst DEFAULT_CACHE = isProd ? 120 : DEV_CACHE; // 2minconst MAX_CACHE = 86_400; // 1d+const VERSION = "v1";+export const latencySchema = z.object({p50Latency: z.number().int().nullable(),p75Latency: z.number().int().nullable(),@@ -50,7 +52,7 @@ export class OSTinybird {return async (props: z.infer<typeof parameters>) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_${period}_chart_get__v0`,+ pipe: `__ttl_${period}_chart_get__${VERSION}`,parameters,data: z.object({@@ -78,7 +80,7 @@ export class OSTinybird {return async (props: z.infer<typeof parameters>) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_${period}_metrics_get__v0`,+ pipe: `__ttl_${period}_metrics_get__${VERSION}`,parameters,data: z.object({@@ -108,7 +110,7 @@ export class OSTinybird {return async (props: z.infer<typeof parameters>) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_${period}_metrics_get_by_region__v0`,+ pipe: `__ttl_${period}_metrics_get_by_region__${VERSION}`,parameters,data: z.object({@@ -141,7 +143,7 @@ export class OSTinybird {) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_${period}_count_get__v0`,+ pipe: `__ttl_${period}_count_get__${VERSION}`,parameters,data: z.object({day: z.string().transform((val) => {@@ -173,17 +175,22 @@ export class OSTinybird {return async (props: z.infer<typeof parameters>) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_${period}_list_get__v0`,+ pipe: `__ttl_${period}_list_get__${VERSION}`,parameters,data: z.object({latency: z.number().int(), // in msmonitorId: z.string(),region: z.enum(flyRegions),+ error: z+ .number()+ .default(0)+ .transform((val) => val !== 0),statusCode: z.number().int().nullable().default(null),timestamp: z.number().int(),url: z.string().url(),workspaceId: z.string(),cronTimestamp: z.number().int().nullable().default(Date.now()),+ assertions: z.string().nullable().optional(),}),opts: {revalidate: DEFAULT_CACHE,@@ -204,7 +211,7 @@ export class OSTinybird {return async (props: z.infer<typeof parameters>) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_1h_last_timestamp_${type}_get__v0`,+ pipe: `__ttl_1h_last_timestamp_${type}_get__${VERSION}`,parameters,data: z.object({ cronTimestamp: z.number().int() }),opts: {@@ -229,13 +236,17 @@ export class OSTinybird {return async (props: z.infer<typeof parameters>) => {try {const res = await this.tb.buildPipe({- pipe: `__ttl_${period}_all_details_get__v0`, // TODO: make it also a bit dynamic to avoid query through too much data+ pipe: `__ttl_${period}_all_details_get__${VERSION}`,parameters,data: z.object({latency: z.number().int(), // in msstatusCode: z.number().int().nullable().default(null),monitorId: z.string().default(""),url: z.string().url().optional(),+ error: z+ .number()+ .default(0)+ .transform((val) => val !== 0),region: z.enum(flyRegions),cronTimestamp: z.number().int().optional(),message: z.string().nullable().optional(),@@ -261,6 +272,7 @@ export class OSTinybird {if (value.success) return value.data;return null;}),+ assertions: z.string().nullable().optional(), // REMINDER: maybe include Assertions.serialize here}),opts: {revalidate: MAX_CACHE,diff --git a/packages/tinybird/src/validation.ts b/packages/tinybird/src/validation.tsindex 5557bbd05..cc05c36c5 100644--- a/packages/tinybird/src/validation.ts+++ b/packages/tinybird/src/validation.ts@@ -40,12 +40,17 @@ export const tbBuildResponseList = z.object({workspaceId: z.string(),monitorId: z.string(),timestamp: z.number().int(),+ error: z+ .number()+ .default(0)+ .transform((val) => val !== 0),statusCode: z.number().int().nullable().default(null),latency: z.number().int(), // in mscronTimestamp: z.number().int().nullable().default(Date.now()),url: z.string().url(),region: z.enum(flyRegions),message: z.string().nullable().optional(),+ assertions: z.string().nullable().optional(),});/**diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2ff927bea..2a405cb3a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -134,6 +134,9 @@ importers:'@openstatus/api':specifier: workspace:*version: link:../../packages/api+ '@openstatus/assertions':+ specifier: workspace:*+ version: link:../../packages/assertions'@openstatus/db':specifier: workspace:*version: link:../../packages/db@@ -397,6 +400,9 @@ importers:'@openstatus/analytics':specifier: workspace:*version: link:../analytics+ '@openstatus/assertions':+ specifier: workspace:*+ version: link:../assertions'@openstatus/db':specifier: workspace:*version: link:../db@@ -444,6 +450,21 @@ importers:specifier: 5.4.2version: 5.4.2+ packages/assertions:+ devDependencies:+ '@openstatus/tsconfig':+ specifier: workspace:*+ version: link:../tsconfig+ jsonpath-plus:+ specifier: 7.2.0+ version: 7.2.0+ typescript:+ specifier: 5.4.2+ version: 5.4.2+ zod:+ specifier: 3.22.2+ version: 3.22.2+packages/config/eslint:dependencies:'@types/eslint':@@ -499,6 +520,9 @@ importers:specifier: 3.22.2version: 3.22.2devDependencies:+ '@openstatus/assertions':+ specifier: workspace:*+ version: link:../assertions'@openstatus/tsconfig':specifier: workspace:*version: link:../tsconfig@@ -1407,6 +1431,10 @@ packages:peerDependencies:'@effect-ts/otel-node': '*'peerDependenciesMeta:+ '@effect-ts/core':+ optional: true+ '@effect-ts/otel':+ optional: true'@effect-ts/otel-node':optional: truedependencies:@@ -9361,6 +9389,11 @@ packages:optionalDependencies:graceful-fs: 4.2.11+ resolution: {integrity: sha512-zBfiUPM5nD0YZSBT/o/fbCUlCcepMIdP0CJZxM1+KgA4f2T206f6VAg9e7mX35+KlMaIc5qXW34f3BnwJ3w+RA==}+ engines: {node: '>=12.0.0'}+ dev: true+resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}engines: {node: '>=4.0'}