Skip to content

Open-source status page, incident response and uptime monitoring

private-location-update: add tests (#1766)

Thibault Le Ouay9a5ee9476b43
diff --git a/.stacked.toml b/.stacked.toml
new file mode 100644
index 000000000..5a7a33273
--- /dev/null
+++ b/.stacked.toml
@@ -0,0 +1,2 @@
+mainBranch = "main"
+draft = true
diff --git a/apps/checker/proto/private_location/v1/assertions.pb.go b/apps/checker/proto/private_location/v1/assertions.pb.go
index 0fd81a8d2..df95ef360 100644
--- a/apps/checker/proto/private_location/v1/assertions.pb.go
+++ b/apps/checker/proto/private_location/v1/assertions.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/assertions.proto
@@ -378,7 +378,7 @@ type RecordAssertion struct {
state protoimpl.MessageState `protogen:"open.v1"`
Record string `protobuf:"bytes,1,opt,name=record,proto3" json:"record,omitempty"`
Comparator RecordComparator `protobuf:"varint,2,opt,name=comparator,proto3,enum=private_location.v1.RecordComparator" json:"comparator,omitempty"`
- Targert string `protobuf:"bytes,3,opt,name=targert,proto3" json:"targert,omitempty"`
+ Target string `protobuf:"bytes,3,opt,name=target,proto3" json:"target,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -427,9 +427,9 @@ func (x *RecordAssertion) GetComparator() RecordComparator {
return RecordComparator_RECORD_COMPARATOR_UNSPECIFIED
}
-func (x *RecordAssertion) GetTargert() string {
+func (x *RecordAssertion) GetTarget() string {
if x != nil {
- return x.Targert
+ return x.Target
}
return ""
}
@@ -454,13 +454,13 @@ const file_private_location_v1_assertions_proto_rawDesc = "" +
"\n" +
"comparator\x18\x02 \x01(\x0e2%.private_location.v1.StringComparatorR\n" +
"comparator\x12\x10\n" +
- "\x03key\x18\x03 \x01(\tR\x03key\"\x8a\x01\n" +
+ "\x03key\x18\x03 \x01(\tR\x03key\"\x88\x01\n" +
"\x0fRecordAssertion\x12\x16\n" +
"\x06record\x18\x01 \x01(\tR\x06record\x12E\n" +
"\n" +
"comparator\x18\x02 \x01(\x0e2%.private_location.v1.RecordComparatorR\n" +
- "comparator\x12\x18\n" +
- "\atargert\x18\x03 \x01(\tR\atargert*\x8f\x02\n" +
+ "comparator\x12\x16\n" +
+ "\x06target\x18\x03 \x01(\tR\x06target*\x8f\x02\n" +
"\x10NumberComparator\x12!\n" +
"\x1dNUMBER_COMPARATOR_UNSPECIFIED\x10\x00\x12\x1b\n" +
"\x17NUMBER_COMPARATOR_EQUAL\x10\x01\x12\x1f\n" +
diff --git a/apps/checker/proto/private_location/v1/dns_monitor.pb.go b/apps/checker/proto/private_location/v1/dns_monitor.pb.go
index 6a86da108..e96c9bc87 100644
--- a/apps/checker/proto/private_location/v1/dns_monitor.pb.go
+++ b/apps/checker/proto/private_location/v1/dns_monitor.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/dns_monitor.proto
diff --git a/apps/checker/proto/private_location/v1/http_monitor.pb.go b/apps/checker/proto/private_location/v1/http_monitor.pb.go
index 866cdc4f1..e3527d5be 100644
--- a/apps/checker/proto/private_location/v1/http_monitor.pb.go
+++ b/apps/checker/proto/private_location/v1/http_monitor.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/http_monitor.proto
diff --git a/apps/checker/proto/private_location/v1/private_location.pb.go b/apps/checker/proto/private_location/v1/private_location.pb.go
index 29804740c..71a8399a1 100644
--- a/apps/checker/proto/private_location/v1/private_location.pb.go
+++ b/apps/checker/proto/private_location/v1/private_location.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/private_location.proto
diff --git a/apps/checker/proto/private_location/v1/tcp_monitor.pb.go b/apps/checker/proto/private_location/v1/tcp_monitor.pb.go
index d81c9b7d5..3cc2ba3a7 100644
--- a/apps/checker/proto/private_location/v1/tcp_monitor.pb.go
+++ b/apps/checker/proto/private_location/v1/tcp_monitor.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/tcp_monitor.proto
diff --git a/apps/private-location/internal/database/database.go b/apps/private-location/internal/database/database.go
index 951382dbd..bb0cecd07 100644
--- a/apps/private-location/internal/database/database.go
+++ b/apps/private-location/internal/database/database.go
@@ -1,27 +1,22 @@
package database
import (
- // "database/sql"
"database/sql"
"fmt"
-
- // "log"
"os"
"github.com/jmoiron/sqlx"
_ "github.com/joho/godotenv/autoload"
- // "github.com/tursodatabase/go-libsql"
_ "github.com/tursodatabase/libsql-client-go/libsql"
)
-var DB *sqlx.DB
-
var (
dbUrl = os.Getenv("DB_URL")
authToken = os.Getenv("DB_AUTH_TOKEN")
dbInstance *sqlx.DB
)
+// New returns a database connection, reusing an existing connection if available.
func New() *sqlx.DB {
// Reuse Connection
if dbInstance != nil {
@@ -36,6 +31,17 @@ func New() *sqlx.DB {
}
db := sqlx.NewDb(c, "sqlite3")
+ dbInstance = db
return db
}
+
+// Close closes the database connection.
+func Close() error {
+ if dbInstance != nil {
+ err := dbInstance.Close()
+ dbInstance = nil
+ return err
+ }
+ return nil
+}
diff --git a/apps/private-location/internal/logs/logs_test.go b/apps/private-location/internal/logs/logs_test.go
new file mode 100644
index 000000000..9e5699bb5
--- /dev/null
+++ b/apps/private-location/internal/logs/logs_test.go
@@ -0,0 +1,323 @@
+package logs_test
+
+import (
+ "log/slog"
+ "testing"
+ "time"
+
+ "github.com/openstatushq/openstatus/apps/private-location/internal/logs"
+)
+
+func TestShouldSample(t *testing.T) {
+ tests := []struct {
+ name string
+ event map[string]any
+ expected bool
+ }{
+ {
+ name: "server error 500 should always sample",
+ event: map[string]any{
+ "status_code": 500,
+ },
+ expected: true,
+ },
+ {
+ name: "server error 503 should always sample",
+ event: map[string]any{
+ "status_code": 503,
+ },
+ expected: true,
+ },
+ {
+ name: "server error 599 should always sample",
+ event: map[string]any{
+ "status_code": 599,
+ },
+ expected: true,
+ },
+ {
+ name: "explicit error should always sample",
+ event: map[string]any{
+ "status_code": 200,
+ "error": "something went wrong",
+ },
+ expected: true,
+ },
+ {
+ name: "slow request above 2000ms should always sample",
+ event: map[string]any{
+ "status_code": 200,
+ "duration_ms": 2001,
+ },
+ expected: true,
+ },
+ {
+ name: "slow request exactly 2000ms should not always sample",
+ event: map[string]any{
+ "status_code": 200,
+ "duration_ms": 2000,
+ },
+ expected: false, // This will be randomly sampled at 20%
+ },
+ {
+ name: "client error 400 should always sample",
+ event: map[string]any{
+ "status_code": 400,
+ },
+ expected: true,
+ },
+ {
+ name: "client error 404 should always sample",
+ event: map[string]any{
+ "status_code": 404,
+ },
+ expected: true,
+ },
+ {
+ name: "client error 499 should always sample",
+ event: map[string]any{
+ "status_code": 499,
+ },
+ expected: true,
+ },
+ {
+ name: "status code 399 should not always sample (below client error range)",
+ event: map[string]any{
+ "status_code": 399,
+ },
+ expected: false, // Random 20% sampling
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := logs.ShouldSample(tt.event)
+ if tt.expected && !result {
+ t.Errorf("ShouldSample() = %v, expected %v (should always sample)", result, tt.expected)
+ }
+ // For cases where expected is false, we can't deterministically test
+ // because the function uses random sampling. We just verify it doesn't
+ // always return true.
+ })
+ }
+}
+
+func TestShouldSample_RandomSampling(t *testing.T) {
+ // Test that successful, fast requests are sometimes sampled
+ event := map[string]any{
+ "status_code": 200,
+ "duration_ms": 100,
+ }
+
+ // Run multiple times to verify random sampling works
+ sampledCount := 0
+ iterations := 1000
+ for i := 0; i < iterations; i++ {
+ if logs.ShouldSample(event) {
+ sampledCount++
+ }
+ }
+
+ // With 20% sampling, we expect roughly 200 samples out of 1000
+ // Allow for some variance (between 10% and 30%)
+ minExpected := iterations / 10 // 10%
+ maxExpected := iterations * 3 / 10 // 30%
+
+ if sampledCount < minExpected || sampledCount > maxExpected {
+ t.Errorf("Random sampling seems off: got %d samples out of %d (expected roughly 20%%)", sampledCount, iterations)
+ }
+}
+
+func TestShouldSample_EmptyEvent(t *testing.T) {
+ // Empty event should fall through to random sampling
+ event := map[string]any{}
+
+ // Just verify it doesn't panic
+ _ = logs.ShouldSample(event)
+}
+
+func TestShouldSample_MissingFields(t *testing.T) {
+ // Event with no status_code or duration_ms
+ event := map[string]any{
+ "path": "/api/test",
+ "method": "GET",
+ }
+
+ // Should fall through to random sampling without panic
+ _ = logs.ShouldSample(event)
+}
+
+func TestMapToAttrs(t *testing.T) {
+ tests := []struct {
+ name string
+ input map[string]any
+ expected int // expected number of attributes
+ }{
+ {
+ name: "empty map",
+ input: map[string]any{},
+ expected: 0,
+ },
+ {
+ name: "single string value",
+ input: map[string]any{
+ "key": "value",
+ },
+ expected: 1,
+ },
+ {
+ name: "multiple types",
+ input: map[string]any{
+ "string_key": "value",
+ "int_key": 42,
+ "bool_key": true,
+ },
+ expected: 3,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ attrs := logs.MapToAttrs(tt.input)
+ if len(attrs) != tt.expected {
+ t.Errorf("MapToAttrs() returned %d attrs, expected %d", len(attrs), tt.expected)
+ }
+ })
+ }
+}
+
+func TestMapToAttrs_TypeConversions(t *testing.T) {
+ now := time.Now()
+ duration := 5 * time.Second
+
+ input := map[string]any{
+ "string_val": "hello",
+ "int_val": 42,
+ "int64_val": int64(1234567890),
+ "float64_val": 3.14,
+ "bool_val": true,
+ "time_val": now,
+ "duration_val": duration,
+ }
+
+ attrs := logs.MapToAttrs(input)
+
+ // Verify correct number of attributes
+ if len(attrs) != 7 {
+ t.Errorf("Expected 7 attributes, got %d", len(attrs))
+ }
+
+ // Verify each attribute type
+ attrMap := make(map[string]slog.Attr)
+ for _, attr := range attrs {
+ attrMap[attr.Key] = attr
+ }
+
+ // Check string
+ if attr, ok := attrMap["string_val"]; ok {
+ if attr.Value.Kind() != slog.KindString {
+ t.Errorf("string_val should be String kind, got %v", attr.Value.Kind())
+ }
+ if attr.Value.String() != "hello" {
+ t.Errorf("string_val should be 'hello', got %v", attr.Value.String())
+ }
+ }
+
+ // Check int
+ if attr, ok := attrMap["int_val"]; ok {
+ if attr.Value.Kind() != slog.KindInt64 {
+ t.Errorf("int_val should be Int64 kind, got %v", attr.Value.Kind())
+ }
+ if attr.Value.Int64() != 42 {
+ t.Errorf("int_val should be 42, got %v", attr.Value.Int64())
+ }
+ }
+
+ // Check bool
+ if attr, ok := attrMap["bool_val"]; ok {
+ if attr.Value.Kind() != slog.KindBool {
+ t.Errorf("bool_val should be Bool kind, got %v", attr.Value.Kind())
+ }
+ if attr.Value.Bool() != true {
+ t.Errorf("bool_val should be true, got %v", attr.Value.Bool())
+ }
+ }
+}
+
+func TestMapToAttrs_NestedMap(t *testing.T) {
+ input := map[string]any{
+ "outer": map[string]any{
+ "inner_string": "nested_value",
+ "inner_int": 123,
+ },
+ }
+
+ attrs := logs.MapToAttrs(input)
+
+ if len(attrs) != 1 {
+ t.Errorf("Expected 1 attribute (group), got %d", len(attrs))
+ }
+
+ // The nested map should be converted to a Group
+ if attrs[0].Key != "outer" {
+ t.Errorf("Expected key 'outer', got %s", attrs[0].Key)
+ }
+ if attrs[0].Value.Kind() != slog.KindGroup {
+ t.Errorf("Expected Group kind for nested map, got %v", attrs[0].Value.Kind())
+ }
+}
+
+func TestMapToAttrs_UnknownType(t *testing.T) {
+ type customType struct {
+ Field string
+ }
+
+ input := map[string]any{
+ "custom": customType{Field: "test"},
+ }
+
+ attrs := logs.MapToAttrs(input)
+
+ if len(attrs) != 1 {
+ t.Errorf("Expected 1 attribute, got %d", len(attrs))
+ }
+
+ // Unknown types should be converted using slog.Any
+ if attrs[0].Key != "custom" {
+ t.Errorf("Expected key 'custom', got %s", attrs[0].Key)
+ }
+ if attrs[0].Value.Kind() != slog.KindAny {
+ t.Errorf("Expected Any kind for unknown type, got %v", attrs[0].Value.Kind())
+ }
+}
+
+func TestMapToAny(t *testing.T) {
+ input := map[string]any{
+ "key1": "value1",
+ "key2": 42,
+ }
+
+ result := logs.MapToAny(input)
+
+ // MapToAny returns []any containing slog.Attr values
+ if len(result) != 2 {
+ t.Errorf("Expected 2 items, got %d", len(result))
+ }
+
+ // Verify each item is an slog.Attr
+ for _, item := range result {
+ if _, ok := item.(slog.Attr); !ok {
+ t.Errorf("Expected slog.Attr, got %T", item)
+ }
+ }
+}
+
+func TestMapToAny_EmptyMap(t *testing.T) {
+ input := map[string]any{}
+
+ result := logs.MapToAny(input)
+
+ if len(result) != 0 {
+ t.Errorf("Expected empty slice, got %d items", len(result))
+ }
+}
diff --git a/apps/private-location/internal/models/assertions.go b/apps/private-location/internal/models/assertions.go
index 7df12059e..6e0941e7a 100644
--- a/apps/private-location/internal/models/assertions.go
+++ b/apps/private-location/internal/models/assertions.go
@@ -5,10 +5,11 @@ import "encoding/json"
type AssertionType string
const (
- AssertionHeader AssertionType = "header"
- AssertionTextBody AssertionType = "textBody"
- AssertionStatus AssertionType = "status"
- AssertionJsonBody AssertionType = "jsonBody"
+ AssertionHeader AssertionType = "header"
+ AssertionTextBody AssertionType = "textBody"
+ AssertionStatus AssertionType = "status"
+ AssertionJsonBody AssertionType = "jsonBody"
+ AssertionDnsRecord AssertionType = "dnsRecord"
)
type StringComparator string
@@ -74,3 +75,19 @@ type BodyString struct {
Comparator StringComparator `json:"compare"`
Target string `json:"target"`
}
+
+type RecordComparator string
+
+const (
+ RecordEquals RecordComparator = "eq"
+ RecordNotEquals RecordComparator = "not_eq"
+ RecordContains RecordComparator = "contains"
+ RecordNotContains RecordComparator = "not_contains"
+)
+
+type RecordTarget struct {
+ AssertionType AssertionType `json:"type"`
+ Comparator RecordComparator `json:"compare"`
+ Target string `json:"target"`
+ Key string `json:"key"`
+}
diff --git a/apps/private-location/internal/server/db_testdata b/apps/private-location/internal/server/db_testdata
index 764739c7d..85d2e2e10 100644
--- a/apps/private-location/internal/server/db_testdata
+++ b/apps/private-location/internal/server/db_testdata
@@ -436,7 +436,9 @@ INSERT INTO "monitor" ("id", "job_type", "periodicity", "active", "url", "name",
('2', 'http', '10m', '0', 'https://www.google.com', '', '', '1', '', '', 'GET', '1760358329', 'gru', '1760358329', 'active', NULL, NULL, '1', '45000', NULL, NULL, NULL, '3', '1'),
('3', 'http', '1m', '1', 'https://www.openstatus.dev', 'OpenStatus', 'OpenStatus website', '1', '[{"key":"key", "value":"value"}]', '{"hello":"world"}', 'GET', '1760358329', 'ams', '1760358329', 'active', NULL, NULL, '0', '45000', NULL, NULL, NULL, '3', '1'),
('4', 'http', '10m', '1', 'https://www.google.com', '', '', '1', '', '', 'GET', '1760358329', 'gru', '1760358329', 'active', NULL, NULL, '1', '45000', NULL, 'https://otel.com:4337', '[{"key":"Authorization","value":"Basic"}]', '3', '1'),
-('5', 'http', '10m', '1', 'https://openstat.us', '', '', '3', '', '', 'GET', '1760358329', 'ams', '1760358329', 'active', NULL, NULL, '1', '45000', NULL, NULL, NULL, '3', '1');
+('5', 'http', '10m', '1', 'https://openstat.us', '', '', '3', '', '', 'GET', '1760358329', 'ams', '1760358329', 'active', NULL, NULL, '1', '45000', NULL, NULL, NULL, '3', '1'),
+('6', 'tcp', '5m', '1', 'tcp://db.example.com:5432', 'Database TCP', 'Database TCP check', '3', '', '', '', '1760358329', 'ams', '1760358329', 'active', NULL, NULL, '0', '30000', '5000', NULL, NULL, '2', '0'),
+('7', 'dns', '5m', '1', 'openstatus.dev', 'DNS Check', 'DNS check for openstatus.dev', '3', '', '', '', '1760358329', 'ams', '1760358329', 'active', '[{"version":"v1","type":"dnsRecord","key":"A","compare":"contains","target":"76.76.21.21"}]', NULL, '0', '30000', '3000', NULL, NULL, '2', '0');
INSERT INTO "notification" ("id", "name", "provider", "data", "workspace_id", "created_at", "updated_at") VALUES
('1', 'sample test notification', 'email', '{"email":"[email protected]"}', '1', '1760358329', '1760358329');
@@ -462,4 +464,6 @@ INSERT INTO "private_location" ("id", "name", "token", "last_seen_at", "workspac
('1', 'My Home', 'my-secret-key', NULL, '3', '1760358329', '1760358329');
INSERT INTO "private_location_to_monitor" ("private_location_id", "monitor_id", "created_at", "deleted_at") VALUES
-('1', '5', '1760358329', NULL);
+('1', '5', '1760358329', NULL),
+('1', '6', '1760358329', NULL),
+('1', '7', '1760358329', NULL);
diff --git a/apps/private-location/internal/server/errors.go b/apps/private-location/internal/server/errors.go
new file mode 100644
index 000000000..8e217f9e8
--- /dev/null
+++ b/apps/private-location/internal/server/errors.go
@@ -0,0 +1,10 @@
+package server
+
+import "errors"
+
+// Common errors used across the server package
+var (
+ ErrMissingToken = errors.New("missing token")
+ ErrMonitorNotFound = errors.New("monitor not found")
+ ErrPrivateLocationNotFound = errors.New("private location not found")
+)
diff --git a/apps/private-location/internal/server/ingest_common.go b/apps/private-location/internal/server/ingest_common.go
new file mode 100644
index 000000000..c755c42f9
--- /dev/null
+++ b/apps/private-location/internal/server/ingest_common.go
@@ -0,0 +1,52 @@
+package server
+
+import (
+ "context"
+ "time"
+
+ "github.com/openstatushq/openstatus/apps/private-location/internal/database"
+ "github.com/rs/zerolog/log"
+)
+
+// ingestContext holds common data needed for ingestion
+type ingestContext struct {
+ Monitor database.Monitor
+ Region database.PrivateLocation
+}
+
+// getIngestContext retrieves monitor and private location data for ingestion
+func (h *privateLocationHandler) getIngestContext(ctx context.Context, token string, monitorID string) (*ingestContext, error) {
+ var monitor database.Monitor
+ err := h.db.Get(&monitor, "SELECT monitor.id, monitor.workspace_id, monitor.url, monitor.method, monitor.assertions FROM monitor JOIN private_location_to_monitor a ON monitor.id = a.monitor_id JOIN private_location b ON a.private_location_id = b.id WHERE b.token = ? AND monitor.deleted_at IS NULL and monitor.id = ?", token, monitorID)
+ if err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to get monitor")
+ return nil, err
+ }
+
+ var region database.PrivateLocation
+ err = h.db.Get(&region, "SELECT private_location.id FROM private_location join private_location_to_monitor a ON private_location.id = a.private_location_id WHERE a.monitor_id = ? AND private_location.token = ?", monitor.ID, token)
+ if err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to get private location")
+ return nil, err
+ }
+
+ return &ingestContext{
+ Monitor: monitor,
+ Region: region,
+ }, nil
+}
+
+// sendEventAndUpdateLastSeen sends the event to Tinybird and updates the last_seen_at timestamp
+func (h *privateLocationHandler) sendEventAndUpdateLastSeen(ctx context.Context, data any, dataSourceName string, regionID int) {
+ if err := h.TbClient.SendEvent(ctx, data, dataSourceName); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
+ }
+
+ _, err := h.db.NamedExec("UPDATE private_location SET last_seen_at = :last_seen_at WHERE id = :id", map[string]any{
+ "last_seen_at": time.Now().Unix(),
+ "id": regionID,
+ })
+ if err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("failed to update private location")
+ }
+}
diff --git a/apps/private-location/internal/server/ingest_dns.go b/apps/private-location/internal/server/ingest_dns.go
index e871e9d84..9eab2f52c 100644
--- a/apps/private-location/internal/server/ingest_dns.go
+++ b/apps/private-location/internal/server/ingest_dns.go
@@ -2,14 +2,11 @@ package server
import (
"context"
- "errors"
"strconv"
- "time"
"connectrpc.com/connect"
- "github.com/openstatushq/openstatus/apps/private-location/internal/database"
+ "github.com/openstatushq/openstatus/apps/private-location/internal/tinybird"
private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
- "github.com/rs/zerolog/log"
)
type DNSResponse struct {
@@ -35,24 +32,26 @@ type DNSResponse struct {
func (h *privateLocationHandler) IngestDNS(ctx context.Context, req *connect.Request[private_locationv1.IngestDNSRequest]) (*connect.Response[private_locationv1.IngestDNSResponse], error) {
token := req.Header().Get("openstatus-token")
if token == "" {
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("missing token"))
+ return nil, connect.NewError(connect.CodeUnauthenticated, ErrMissingToken)
}
- dataSourceName := "tcp_dns__v0"
-
- var monitors database.Monitor
- err := h.db.Get(&monitors, "SELECT monitor.* FROM monitor JOIN private_location_to_monitor a ON monitor.id = a.monitor_id JOIN private_location b ON a.private_location_id = b.id WHERE b.token = ? AND monitor.deleted_at IS NULL and monitor.id = ?", token, req.Msg.Id)
+ if err := ValidateIngestDNSRequest(req.Msg); err != nil {
+ return nil, NewValidationError(err)
+ }
+ ic, err := h.getIngestContext(ctx, token, req.Msg.Id)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
- var region database.PrivateLocation
- err = h.db.Get(&region, "SELECT private_location.id FROM private_location join private_location_to_monitor a ON private_location.id = a.private_location_id WHERE a.monitor_id = ? and private_location.token = ?", monitors.ID, token)
-
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, err)
+ event := ctx.Value("event")
+ if eventMap, ok := event.(map[string]any); ok && eventMap != nil {
+ eventMap["private_location"] = map[string]any{
+ "monitor_id": req.Msg.MonitorId,
+ }
+ ctx = context.WithValue(ctx, "event", eventMap)
}
+
records := make(map[string][]string)
for _, record := range req.Msg.Records {
r := []string{}
@@ -63,31 +62,22 @@ func (h *privateLocationHandler) IngestDNS(ctx context.Context, req *connect.Req
}
data := DNSResponse{
- ID: req.Msg.Id,
- WorkspaceID: int64(monitors.WorkspaceID),
- Timestamp: req.Msg.Timestamp,
- Error: uint8(req.Msg.Error),
- // ErrorMessage: req.Msg.ErrorMessage,
- Region: strconv.Itoa(region.ID),
- MonitorID: int64(monitors.ID),
+ ID: req.Msg.Id,
+ WorkspaceID: int64(ic.Monitor.WorkspaceID),
+ Timestamp: req.Msg.Timestamp,
+ Error: uint8(req.Msg.Error),
+ Region: strconv.Itoa(ic.Region.ID),
+ MonitorID: int64(ic.Monitor.ID),
Timing: req.Msg.Timing,
Latency: req.Msg.Latency,
CronTimestamp: req.Msg.CronTimestamp,
Trigger: "cron",
URI: req.Msg.Uri,
RequestStatus: req.Msg.RequestStatus,
-
- Records: records,
- }
- if err := h.TbClient.SendEvent(ctx, data, dataSourceName); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
- }
- _, err = h.db.NamedExec("UPDATE private_location SET last_seen_at = :last_seen_at WHERE id = :id", map[string]any{
- "last_seen_at": time.Now().Unix(),
- "id": region.ID,
- })
- if err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to update private location")
+ Records: records,
}
+
+ h.sendEventAndUpdateLastSeen(ctx, data, tinybird.DatasourceDNS, ic.Region.ID)
+
return connect.NewResponse(&private_locationv1.IngestDNSResponse{}), nil
}
diff --git a/apps/private-location/internal/server/ingest_dns_test.go b/apps/private-location/internal/server/ingest_dns_test.go
new file mode 100644
index 000000000..098e9646f
--- /dev/null
+++ b/apps/private-location/internal/server/ingest_dns_test.go
@@ -0,0 +1,211 @@
+package server_test
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/openstatushq/openstatus/apps/private-location/internal/server"
+ "github.com/openstatushq/openstatus/apps/private-location/internal/tinybird"
+ private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
+)
+
+func TestIngestDNS_Unauthenticated(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{})
+ // No token header
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for missing token, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeUnauthenticated {
+ t.Errorf("expected unauthenticated code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestDNS_ValidationError_EmptyID(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "",
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestDNS_ValidationError_InvalidTimestamp(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Timestamp: 0, // Invalid - must be positive
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestDNS_ValidationError_NegativeLatency(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Latency: -100,
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestDNS_DBError(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "nonexistent-monitor",
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "invalid-token")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for db failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInternal {
+ t.Errorf("expected internal code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestDNS_MonitorNotExist(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "nonexistent-monitor",
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for monitor not found, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInternal {
+ t.Errorf("expected internal code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestDNS_MonitorExist(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "5",
+ Timestamp: 1234567890,
+ Latency: 50,
+ CronTimestamp: 1234567800,
+ Uri: "dns://example.com",
+ Timing: "50ms",
+ Records: nil,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
+ }
+}
+
+func TestIngestDNS_WithRecords(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "5",
+ Timestamp: 1234567890,
+ Latency: 50,
+ CronTimestamp: 1234567800,
+ Uri: "dns://example.com",
+ Timing: "50ms",
+ Records: map[string]*private_locationv1.Records{
+ "A": {
+ Record: []string{"192.168.1.1", "192.168.1.2"},
+ },
+ "AAAA": {
+ Record: []string{"::1"},
+ },
+ },
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
+ }
+}
+
+func TestIngestDNS_WithError(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestDNSRequest{
+ Id: "5",
+ Timestamp: 1234567890,
+ Latency: 0,
+ CronTimestamp: 1234567800,
+ Uri: "dns://example.com",
+ Error: 1, // Error occurred
+ Message: "DNS resolution failed",
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestDNS(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
+ }
+}
diff --git a/apps/private-location/internal/server/ingest_http.go b/apps/private-location/internal/server/ingest_http.go
index fcb1cefa7..ce378a594 100644
--- a/apps/private-location/internal/server/ingest_http.go
+++ b/apps/private-location/internal/server/ingest_http.go
@@ -2,14 +2,11 @@ package server
import (
"context"
- "errors"
"strconv"
- "time"
"connectrpc.com/connect"
- "github.com/openstatushq/openstatus/apps/private-location/internal/database"
+ "github.com/openstatushq/openstatus/apps/private-location/internal/tinybird"
private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
- "github.com/rs/zerolog/log"
)
type PingData struct {
@@ -34,28 +31,25 @@ type PingData struct {
}
func (h *privateLocationHandler) IngestHTTP(ctx context.Context, req *connect.Request[private_locationv1.IngestHTTPRequest]) (*connect.Response[private_locationv1.IngestHTTPResponse], error) {
+ event := ctx.Value("event")
+ if eventMap, ok := event.(map[string]any); ok && eventMap != nil {
+ eventMap["private_location"] = map[string]any{
+ "monitor_id": req.Msg.MonitorId,
+ }
+ ctx = context.WithValue(ctx, "event", eventMap)
+ }
+
token := req.Header().Get("openstatus-token")
if token == "" {
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("missing token"))
+ return nil, connect.NewError(connect.CodeUnauthenticated, ErrMissingToken)
}
- dataSourceName := "ping_response__v8"
-
- var monitors database.Monitor
- err := h.db.Get(&monitors, "SELECT monitor.* FROM monitor JOIN private_location_to_monitor a ON monitor.id = a.monitor_id JOIN private_location b ON a.private_location_id = b.id WHERE b.token = ? AND monitor.deleted_at IS NULL and monitor.id = ?", token, req.Msg.MonitorId)
-
- if err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("Failed to get monitors")
-
- return nil, connect.NewError(connect.CodeInternal, err)
+ if err := ValidateIngestHTTPRequest(req.Msg); err != nil {
+ return nil, NewValidationError(err)
}
- var region database.PrivateLocation
- err = h.db.Get(&region, "SELECT private_location.id FROM private_location join private_location_to_monitor a ON private_location.id = a.private_location_id WHERE a.monitor_id = ? AND private_location.token = ?", monitors.ID, token)
-
+ ic, err := h.getIngestContext(ctx, token, req.Msg.MonitorId)
if err != nil {
-
- log.Ctx(ctx).Error().Err(err).Msg("Failed to get private location")
return nil, connect.NewError(connect.CodeInternal, err)
}
@@ -64,29 +58,21 @@ func (h *privateLocationHandler) IngestHTTP(ctx context.Context, req *connect.Re
Latency: req.Msg.Latency,
StatusCode: int(req.Msg.StatusCode),
MonitorID: req.Msg.MonitorId,
- Region: strconv.Itoa(region.ID),
- WorkspaceID: strconv.Itoa(monitors.WorkspaceID),
+ Region: strconv.Itoa(ic.Region.ID),
+ WorkspaceID: strconv.Itoa(ic.Monitor.WorkspaceID),
Timestamp: req.Msg.Timestamp,
CronTimestamp: req.Msg.CronTimestamp,
- URL: monitors.URL,
- Method: monitors.Method,
+ URL: ic.Monitor.URL,
+ Method: ic.Monitor.Method,
Timing: req.Msg.Timing,
Headers: req.Msg.Headers,
Body: req.Msg.Body,
Trigger: "cron",
RequestStatus: req.Msg.RequestStatus,
- Assertions: monitors.Assertions.String,
- }
- if err := h.TbClient.SendEvent(ctx, data, dataSourceName); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
- }
- _, err = h.db.NamedExec("UPDATE private_location SET last_seen_at = :last_seen_at WHERE id = :id", map[string]any{
- "last_seen_at": time.Now().Unix(),
- "id": region.ID,
- })
- if err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to update private location")
+ Assertions: ic.Monitor.Assertions.String,
}
+ h.sendEventAndUpdateLastSeen(ctx, data, tinybird.DatasourceHTTP, ic.Region.ID)
+
return connect.NewResponse(&private_locationv1.IngestHTTPResponse{}), nil
}
diff --git a/apps/private-location/internal/server/ingest_http_test.go b/apps/private-location/internal/server/ingest_http_test.go
index a851f0180..0fdb55f48 100644
--- a/apps/private-location/internal/server/ingest_http_test.go
+++ b/apps/private-location/internal/server/ingest_http_test.go
@@ -81,6 +81,8 @@ func TestIngestHTTP_DBError(t *testing.T) {
req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{})
req.Header().Set("openstatus-token", "token123")
req.Msg.Id = "monitor1"
+ req.Msg.MonitorId = "nonexistent"
+ req.Msg.Timestamp = 1234567890
resp, err := h.IngestHTTP(context.Background(), req)
if err == nil {
t.Fatalf("expected error for db failure, got nil")
@@ -99,6 +101,8 @@ func TestIngestHTTP_MonitorNotExist(t *testing.T) {
req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{})
req.Header().Set("openstatus-token", "my-secret-key")
req.Msg.Id = "monitor1"
+ req.Msg.MonitorId = "nonexistent"
+ req.Msg.Timestamp = 1234567890
resp, err := h.IngestHTTP(context.Background(), req)
if err == nil {
t.Fatalf("expected error for db failure, got nil")
@@ -118,12 +122,127 @@ func TestIngestHTTP_MonitorExist(t *testing.T) {
req.Header().Set("openstatus-token", "my-secret-key")
req.Msg.Id = "monitor1"
req.Msg.MonitorId = "5"
+ req.Msg.Timestamp = 1234567890
resp, err := h.IngestHTTP(context.Background(), req)
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
if resp == nil {
- t.Errorf("expected not response, got %v", resp)
+ t.Errorf("expected not nil response, got %v", resp)
+ }
+}
+
+func TestIngestHTTP_ValidationError_EmptyMonitorID(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{
+ MonitorId: "",
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestHTTP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestHTTP_ValidationError_InvalidTimestamp(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{
+ MonitorId: "5",
+ Timestamp: 0,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestHTTP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestHTTP_ValidationError_NegativeLatency(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{
+ MonitorId: "5",
+ Latency: -100,
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestHTTP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestHTTP_WithFullData(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{
+ Id: "request-1",
+ MonitorId: "5",
+ Timestamp: 1234567890,
+ Latency: 150,
+ CronTimestamp: 1234567800,
+ Url: "https://example.com/api",
+ StatusCode: 200,
+ Timing: "150ms",
+ Body: `{"status": "ok"}`,
+ Headers: `{"Content-Type": "application/json"}`,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestHTTP(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
+ }
+}
+
+func TestIngestHTTP_WithError(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestHTTPRequest{
+ Id: "request-1",
+ MonitorId: "5",
+ Timestamp: 1234567890,
+ Latency: 0,
+ CronTimestamp: 1234567800,
+ Url: "https://example.com/api",
+ Error: 1,
+ Message: "Connection timeout",
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestHTTP(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
}
}
diff --git a/apps/private-location/internal/server/ingest_tcp.go b/apps/private-location/internal/server/ingest_tcp.go
index 538cdc796..2c96a7e59 100644
--- a/apps/private-location/internal/server/ingest_tcp.go
+++ b/apps/private-location/internal/server/ingest_tcp.go
@@ -2,14 +2,11 @@ package server
import (
"context"
- "errors"
"strconv"
- "time"
"connectrpc.com/connect"
- "github.com/openstatushq/openstatus/apps/private-location/internal/database"
+ "github.com/openstatushq/openstatus/apps/private-location/internal/tinybird"
private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
- "github.com/rs/zerolog/log"
)
type TCPData struct {
@@ -34,33 +31,33 @@ type TCPData struct {
func (h *privateLocationHandler) IngestTCP(ctx context.Context, req *connect.Request[private_locationv1.IngestTCPRequest]) (*connect.Response[private_locationv1.IngestTCPResponse], error) {
token := req.Header().Get("openstatus-token")
if token == "" {
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("missing token"))
+ return nil, connect.NewError(connect.CodeUnauthenticated, ErrMissingToken)
}
- dataSourceName := "tcp_response__v0"
-
- var monitors database.Monitor
- err := h.db.Get(&monitors, "SELECT monitor.* FROM monitor JOIN private_location_to_monitor a ON monitor.id = a.monitor_id JOIN private_location b ON a.private_location_id = b.id WHERE b.token = ? AND monitor.deleted_at IS NULL and monitor.id = ?", token, req.Msg.Id)
+ if err := ValidateIngestTCPRequest(req.Msg); err != nil {
+ return nil, NewValidationError(err)
+ }
+ ic, err := h.getIngestContext(ctx, token, req.Msg.Id)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
- var region database.PrivateLocation
- err = h.db.Get(&region, "SELECT private_location.id FROM private_location join private_location_to_monitor a ON private_location.id = a.private_location_id WHERE a.monitor_id = ? and private_location.token = ?", monitors.ID, token)
-
- if err != nil {
- return nil, connect.NewError(connect.CodeInternal, err)
+ event := ctx.Value("event")
+ if eventMap, ok := event.(map[string]any); ok && eventMap != nil {
+ eventMap["private_location"] = map[string]any{
+ "monitor_id": req.Msg.MonitorId,
+ }
+ ctx = context.WithValue(ctx, "event", eventMap)
}
data := TCPData{
- ID: req.Msg.Id,
- WorkspaceID: int64(monitors.WorkspaceID),
- Timestamp: req.Msg.Timestamp,
- Error: uint8(req.Msg.Error),
- // ErrorMessage: req.Msg.ErrorMessage,
- Region: strconv.Itoa(region.ID),
- MonitorID: int64(monitors.ID),
+ ID: req.Msg.Id,
+ WorkspaceID: int64(ic.Monitor.WorkspaceID),
+ Timestamp: req.Msg.Timestamp,
+ Error: uint8(req.Msg.Error),
+ Region: strconv.Itoa(ic.Region.ID),
+ MonitorID: int64(ic.Monitor.ID),
Timing: req.Msg.Timing,
Latency: req.Msg.Latency,
CronTimestamp: req.Msg.CronTimestamp,
@@ -68,15 +65,8 @@ func (h *privateLocationHandler) IngestTCP(ctx context.Context, req *connect.Req
URI: req.Msg.Uri,
RequestStatus: req.Msg.RequestStatus,
}
- if err := h.TbClient.SendEvent(ctx, data, dataSourceName); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to send event to tinybird")
- }
- _, err = h.db.NamedExec("UPDATE private_location SET last_seen_at = :last_seen_at WHERE id = :id", map[string]any{
- "last_seen_at": time.Now().Unix(),
- "id": region.ID,
- })
- if err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("failed to update private location")
- }
+
+ h.sendEventAndUpdateLastSeen(ctx, data, tinybird.DatasourceTCP, ic.Region.ID)
+
return connect.NewResponse(&private_locationv1.IngestTCPResponse{}), nil
}
diff --git a/apps/private-location/internal/server/ingest_tcp_test.go b/apps/private-location/internal/server/ingest_tcp_test.go
index 11f693b05..dc86f0b81 100644
--- a/apps/private-location/internal/server/ingest_tcp_test.go
+++ b/apps/private-location/internal/server/ingest_tcp_test.go
@@ -35,6 +35,7 @@ func TestIngestTCP_DBError(t *testing.T) {
req := connect.NewRequest(&private_locationv1.IngestTCPRequest{})
req.Header().Set("openstatus-token", "token123")
req.Msg.Id = "monitor1"
+ req.Msg.Timestamp = 1234567890
resp, err := h.IngestTCP(context.Background(), req)
if err == nil {
t.Fatalf("expected error for db failure, got nil")
@@ -46,3 +47,133 @@ func TestIngestTCP_DBError(t *testing.T) {
t.Errorf("expected nil response, got %v", resp)
}
}
+
+func TestIngestTCP_ValidationError_EmptyID(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestTCPRequest{
+ Id: "",
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestTCP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestTCP_ValidationError_InvalidTimestamp(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Timestamp: 0,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestTCP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestTCP_ValidationError_NegativeLatency(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Latency: -100,
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestTCP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for validation failure, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInvalidArgument {
+ t.Errorf("expected invalid argument code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestTCP_MonitorNotExist(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), tinybird.NewClient(http.DefaultClient, ""))
+
+ req := connect.NewRequest(&private_locationv1.IngestTCPRequest{
+ Id: "nonexistent-monitor",
+ Timestamp: 1234567890,
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestTCP(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for monitor not found, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeInternal {
+ t.Errorf("expected internal code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestIngestTCP_MonitorExist(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestTCPRequest{
+ Id: "5",
+ Timestamp: 1234567890,
+ Latency: 50,
+ CronTimestamp: 1234567800,
+ Uri: "tcp://example.com:8080",
+ Timing: "50ms",
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestTCP(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
+ }
+}
+
+func TestIngestTCP_WithError(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.IngestTCPRequest{
+ Id: "5",
+ Timestamp: 1234567890,
+ Latency: 0,
+ CronTimestamp: 1234567800,
+ Uri: "tcp://example.com:8080",
+ Error: 1,
+ Message: "Connection refused",
+ })
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.IngestTCP(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected nil error, got %v", err)
+ }
+ if resp == nil {
+ t.Errorf("expected not nil response, got nil")
+ }
+}
diff --git a/apps/private-location/internal/server/monitors.go b/apps/private-location/internal/server/monitors.go
index 74de31371..6fdff9335 100644
--- a/apps/private-location/internal/server/monitors.go
+++ b/apps/private-location/internal/server/monitors.go
@@ -4,7 +4,6 @@ import (
"context"
"database/sql"
"encoding/json"
- "errors"
"strconv"
"connectrpc.com/connect"
@@ -54,6 +53,22 @@ func convertStringComparator(m models.StringComparator) private_locationv1.Strin
}
}
+// Converts models.RecordComparator to proto RecordComparator
+func convertRecordComparator(m models.RecordComparator) private_locationv1.RecordComparator {
+ switch m {
+ case models.RecordEquals:
+ return private_locationv1.RecordComparator_RECORD_COMPARATOR_EQUAL
+ case models.RecordNotEquals:
+ return private_locationv1.RecordComparator_RECORD_COMPARATOR_NOT_EQUAL
+ case models.RecordContains:
+ return private_locationv1.RecordComparator_RECORD_COMPARATOR_CONTAINS
+ case models.RecordNotContains:
+ return private_locationv1.RecordComparator_RECORD_COMPARATOR_NOT_CONTAINS
+ default:
+ return private_locationv1.RecordComparator_RECORD_COMPARATOR_UNSPECIFIED
+ }
+}
+
// Helper to parse assertions
func ParseAssertions(assertions sql.NullString) (
statusAssertions []*private_locationv1.StatusCodeAssertion,
@@ -65,20 +80,20 @@ func ParseAssertions(assertions sql.NullString) (
}
var rawAssertions []json.RawMessage
if err := json.Unmarshal([]byte(assertions.String), &rawAssertions); err != nil {
- log.Printf("Failed to unmarshal assertions: %v", err)
+ log.Error().Err(err).Msg("failed to unmarshal assertions")
return
}
for _, a := range rawAssertions {
var assert models.Assertion
if err := json.Unmarshal(a, &assert); err != nil {
- log.Printf("Failed to unmarshal assertion: %v", err)
+ log.Error().Err(err).Msg("failed to unmarshal assertion")
continue
}
switch assert.AssertionType {
case models.AssertionStatus:
var target models.StatusTarget
if err := json.Unmarshal(a, &target); err != nil {
- log.Printf("Failed to unmarshal status target: %v", err)
+ log.Error().Err(err).Msg("failed to unmarshal status target")
continue
}
statusAssertions = append(statusAssertions, &private_locationv1.StatusCodeAssertion{
@@ -88,7 +103,7 @@ func ParseAssertions(assertions sql.NullString) (
case models.AssertionHeader:
var target models.HeaderTarget
if err := json.Unmarshal(a, &target); err != nil {
- log.Error().Err(err).Msg("unable to encode payload")
+ log.Error().Err(err).Msg("failed to unmarshal header target")
continue
}
headerAssertions = append(headerAssertions, &private_locationv1.HeaderAssertion{
@@ -99,7 +114,7 @@ func ParseAssertions(assertions sql.NullString) (
case models.AssertionTextBody:
var target models.BodyString
if err := json.Unmarshal(a, &target); err != nil {
- log.Printf("Failed to unmarshal body target: %v", err)
+ log.Error().Err(err).Msg("failed to unmarshal body target")
continue
}
bodyAssertions = append(bodyAssertions, &private_locationv1.BodyAssertion{
@@ -111,49 +126,121 @@ func ParseAssertions(assertions sql.NullString) (
return
}
+// Helper to parse DNS record assertions
+func ParseRecordAssertions(assertions sql.NullString) []*private_locationv1.RecordAssertion {
+ if !assertions.Valid {
+ return nil
+ }
+ var rawAssertions []json.RawMessage
+ if err := json.Unmarshal([]byte(assertions.String), &rawAssertions); err != nil {
+ log.Error().Err(err).Msg("failed to unmarshal assertions")
+ return nil
+ }
+ var recordAssertions []*private_locationv1.RecordAssertion
+ for _, a := range rawAssertions {
+ var assert models.Assertion
+ if err := json.Unmarshal(a, &assert); err != nil {
+ log.Error().Err(err).Msg("failed to unmarshal assertion")
+ continue
+ }
+ if assert.AssertionType == models.AssertionDnsRecord {
+ var target models.RecordTarget
+ if err := json.Unmarshal(a, &target); err != nil {
+ log.Error().Err(err).Msg("failed to unmarshal record target")
+ continue
+ }
+ recordAssertions = append(recordAssertions, &private_locationv1.RecordAssertion{
+ Record: target.Key,
+ Comparator: convertRecordComparator(target.Comparator),
+ Target: target.Target,
+ })
+ }
+ }
+ return recordAssertions
+}
+
func (h *privateLocationHandler) Monitors(ctx context.Context, req *connect.Request[private_locationv1.MonitorsRequest]) (*connect.Response[private_locationv1.MonitorsResponse], error) {
token := req.Header().Get("openstatus-token")
if token == "" {
- return nil, connect.NewError(connect.CodeUnauthenticated, errors.New("missing token"))
+ return nil, connect.NewError(connect.CodeUnauthenticated, ErrMissingToken)
}
var monitors []database.Monitor
- err := h.db.Select(&monitors, "SELECT monitor.* FROM monitor JOIN private_location_to_monitor a ON monitor.id = a.monitor_id JOIN private_location b ON a.private_location_id = b.id WHERE b.token = ? AND monitor.deleted_at IS NULL and monitor.active = 1", token)
+ err := h.db.Select(&monitors, "SELECT monitor.id, monitor.job_type, monitor.url, monitor.periodicity, monitor.method, monitor.body, monitor.timeout, monitor.degraded_after, monitor.follow_redirects, monitor.headers, monitor.assertions, monitor.workspace_id, monitor.retry FROM monitor JOIN private_location_to_monitor a ON monitor.id = a.monitor_id JOIN private_location b ON a.private_location_id = b.id WHERE b.token = ? AND monitor.deleted_at IS NULL and monitor.active = 1", token)
if err != nil {
return nil, connect.NewError(connect.CodeInternal, err)
}
-
+ var workspaceId int
var httpMonitors []*private_locationv1.HTTPMonitor
+ var tcpMonitors []*private_locationv1.TCPMonitor
+ var dnsMonitors []*private_locationv1.DNSMonitor
for _, monitor := range monitors {
- if monitor.JobType != "http" {
- continue
+ if workspaceId == 0 {
+ workspaceId = monitor.WorkspaceID
}
- var headers []*private_locationv1.Headers
- if err := json.Unmarshal([]byte(monitor.Headers), &headers); err != nil {
- log.Ctx(ctx).Error().Err(err).Msg("unable to unmarshal headers")
- headers = nil
+ switch monitor.JobType {
+ case database.JobTypeHTTP:
+ var headers []*private_locationv1.Headers
+ if err := json.Unmarshal([]byte(monitor.Headers), &headers); err != nil {
+ log.Ctx(ctx).Error().Err(err).Msg("unable to unmarshal headers")
+ headers = nil
+ }
+
+ statusAssertions, headerAssertions, bodyAssertions := ParseAssertions(monitor.Assertions)
+
+ httpMonitors = append(httpMonitors, &private_locationv1.HTTPMonitor{
+ Url: monitor.URL,
+ Periodicity: monitor.Periodicity,
+ Id: strconv.Itoa(monitor.ID),
+ Method: monitor.Method,
+ Body: monitor.Body,
+ Timeout: monitor.Timeout,
+ DegradedAt: &monitor.DegradedAfter.Int64,
+ Retry: int64(monitor.Retry),
+ FollowRedirects: monitor.FollowRedirects,
+ Headers: headers,
+ StatusCodeAssertions: statusAssertions,
+ HeaderAssertions: headerAssertions,
+ BodyAssertions: bodyAssertions,
+ })
+
+ case database.JobTypeTCP:
+ tcpMonitors = append(tcpMonitors, &private_locationv1.TCPMonitor{
+ Id: strconv.Itoa(monitor.ID),
+ Uri: monitor.URL,
+ Timeout: monitor.Timeout,
+ DegradedAt: &monitor.DegradedAfter.Int64,
+ Periodicity: monitor.Periodicity,
+ Retry: int64(monitor.Retry),
+ })
+
+ case database.JobTypeDNS:
+ recordAssertions := ParseRecordAssertions(monitor.Assertions)
+ dnsMonitors = append(dnsMonitors, &private_locationv1.DNSMonitor{
+ Id: strconv.Itoa(monitor.ID),
+ Uri: monitor.URL,
+ Timeout: monitor.Timeout,
+ DegradedAt: &monitor.DegradedAfter.Int64,
+ Periodicity: monitor.Periodicity,
+ Retry: int64(monitor.Retry),
+ RecordAssertions: recordAssertions,
+ })
}
+ }
- statusAssertions, headerAssertions, bodyAssertions := ParseAssertions(monitor.Assertions)
-
- httpMonitors = append(httpMonitors, &private_locationv1.HTTPMonitor{
- Url: monitor.URL,
- Periodicity: monitor.Periodicity,
- Id: strconv.Itoa(monitor.ID),
- Method: monitor.Method,
- Body: monitor.Body,
- Timeout: monitor.Timeout,
- DegradedAt: &monitor.DegradedAfter.Int64,
- FollowRedirects: monitor.FollowRedirects,
- Headers: headers,
- StatusCodeAssertions: statusAssertions,
- HeaderAssertions: headerAssertions,
- BodyAssertions: bodyAssertions,
- })
+
+ event := ctx.Value("event")
+ if eventMap, ok := event.(map[string]any); ok && eventMap != nil {
+ eventMap["private_location"] = map[string]any{
+ "workspace_id": workspaceId,
+ }
+ ctx = context.WithValue(ctx, "event", eventMap)
}
return connect.NewResponse(&private_locationv1.MonitorsResponse{
HttpMonitors: httpMonitors,
+ TcpMonitors: tcpMonitors,
+ DnsMonitors: dnsMonitors,
}), nil
}
diff --git a/apps/private-location/internal/server/monitors_test.go b/apps/private-location/internal/server/monitors_test.go
index 5a4c45def..ce39d87ba 100644
--- a/apps/private-location/internal/server/monitors_test.go
+++ b/apps/private-location/internal/server/monitors_test.go
@@ -1,9 +1,11 @@
package server_test
import (
+ "context"
"database/sql"
"testing"
+ "connectrpc.com/connect"
"github.com/openstatushq/openstatus/apps/private-location/internal/server"
private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
)
@@ -55,3 +57,533 @@ func TestParseAssertions_HttpStatusEquals(t *testing.T) {
t.Errorf("expected Comparator to be STRING_COMPARATOR_CONTAINS, got %v", got.Comparator)
}
}
+
+func TestParseAssertions_InvalidJSON(t *testing.T) {
+ assertions := sql.NullString{
+ String: "not valid json",
+ Valid: true,
+ }
+
+ statusAssertions, headerAssertions, bodyAssertions := server.ParseAssertions(assertions)
+
+ if len(statusAssertions) != 0 || len(headerAssertions) != 0 || len(bodyAssertions) != 0 {
+ t.Errorf("expected empty assertions for invalid JSON, got status=%d, header=%d, body=%d",
+ len(statusAssertions), len(headerAssertions), len(bodyAssertions))
+ }
+}
+
+func TestParseAssertions_NullString(t *testing.T) {
+ assertions := sql.NullString{
+ String: "",
+ Valid: false,
+ }
+
+ statusAssertions, headerAssertions, bodyAssertions := server.ParseAssertions(assertions)
+
+ if len(statusAssertions) != 0 || len(headerAssertions) != 0 || len(bodyAssertions) != 0 {
+ t.Errorf("expected empty assertions for null string, got status=%d, header=%d, body=%d",
+ len(statusAssertions), len(headerAssertions), len(bodyAssertions))
+ }
+}
+
+func TestParseAssertions_HeaderAssertion(t *testing.T) {
+ input := `[{"version":"v1","type":"header","compare":"eq","key":"Content-Type","target":"application/json"}]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ _, headerAssertions, _ := server.ParseAssertions(assertions)
+
+ if len(headerAssertions) != 1 {
+ t.Fatalf("expected 1 header assertion, got %d", len(headerAssertions))
+ }
+
+ got := headerAssertions[0]
+ if got.Key != "Content-Type" {
+ t.Errorf("expected Key to be 'Content-Type', got '%s'", got.Key)
+ }
+ if got.Target != "application/json" {
+ t.Errorf("expected Target to be 'application/json', got '%s'", got.Target)
+ }
+ if got.Comparator != private_locationv1.StringComparator_STRING_COMPARATOR_EQUAL {
+ t.Errorf("expected Comparator to be STRING_COMPARATOR_EQUAL, got %v", got.Comparator)
+ }
+}
+
+func TestParseAssertions_MultipleAssertions(t *testing.T) {
+ input := `[
+ {"version":"v1","type":"status","compare":"eq","target":200},
+ {"version":"v1","type":"header","compare":"contains","key":"X-Request-Id","target":"req-"},
+ {"version":"v1","type":"textBody","compare":"notContains","target":"error"}
+ ]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ statusAssertions, headerAssertions, bodyAssertions := server.ParseAssertions(assertions)
+
+ if len(statusAssertions) != 1 {
+ t.Errorf("expected 1 status assertion, got %d", len(statusAssertions))
+ }
+ if len(headerAssertions) != 1 {
+ t.Errorf("expected 1 header assertion, got %d", len(headerAssertions))
+ }
+ if len(bodyAssertions) != 1 {
+ t.Errorf("expected 1 body assertion, got %d", len(bodyAssertions))
+ }
+}
+
+func TestMonitors_Unauthenticated(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ // No token header
+ resp, err := h.Monitors(context.Background(), req)
+ if err == nil {
+ t.Fatalf("expected error for missing token, got nil")
+ }
+ if connect.CodeOf(err) != connect.CodeUnauthenticated {
+ t.Errorf("expected unauthenticated code, got %v", connect.CodeOf(err))
+ }
+ if resp != nil {
+ t.Errorf("expected nil response, got %v", resp)
+ }
+}
+
+func TestMonitors_InvalidToken(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ req.Header().Set("openstatus-token", "invalid-token")
+
+ resp, err := h.Monitors(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected no error for invalid token (just empty results), got %v", err)
+ }
+ if resp == nil {
+ t.Fatalf("expected non-nil response")
+ }
+ if len(resp.Msg.HttpMonitors) != 0 {
+ t.Errorf("expected 0 HTTP monitors for invalid token, got %d", len(resp.Msg.HttpMonitors))
+ }
+ if len(resp.Msg.TcpMonitors) != 0 {
+ t.Errorf("expected 0 TCP monitors for invalid token, got %d", len(resp.Msg.TcpMonitors))
+ }
+ if len(resp.Msg.DnsMonitors) != 0 {
+ t.Errorf("expected 0 DNS monitors for invalid token, got %d", len(resp.Msg.DnsMonitors))
+ }
+}
+
+func TestMonitors_ReturnsHTTPTCPAndDNSMonitors(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.Monitors(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if resp == nil {
+ t.Fatalf("expected non-nil response")
+ }
+
+ // Should have HTTP monitor (monitor ID 5)
+ if len(resp.Msg.HttpMonitors) != 1 {
+ t.Errorf("expected 1 HTTP monitor, got %d", len(resp.Msg.HttpMonitors))
+ }
+
+ // Should have TCP monitor (monitor ID 6)
+ if len(resp.Msg.TcpMonitors) != 1 {
+ t.Errorf("expected 1 TCP monitor, got %d", len(resp.Msg.TcpMonitors))
+ }
+
+ // Should have DNS monitor (monitor ID 7)
+ if len(resp.Msg.DnsMonitors) != 1 {
+ t.Errorf("expected 1 DNS monitor, got %d", len(resp.Msg.DnsMonitors))
+ }
+}
+
+func TestMonitors_HTTPMonitorFields(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.Monitors(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if len(resp.Msg.HttpMonitors) != 1 {
+ t.Fatalf("expected 1 HTTP monitor, got %d", len(resp.Msg.HttpMonitors))
+ }
+
+ httpMonitor := resp.Msg.HttpMonitors[0]
+ if httpMonitor.Id != "5" {
+ t.Errorf("expected ID '5', got '%s'", httpMonitor.Id)
+ }
+ if httpMonitor.Url != "https://openstat.us" {
+ t.Errorf("expected URL 'https://openstat.us', got '%s'", httpMonitor.Url)
+ }
+ if httpMonitor.Periodicity != "10m" {
+ t.Errorf("expected Periodicity '10m', got '%s'", httpMonitor.Periodicity)
+ }
+ if httpMonitor.Method != "GET" {
+ t.Errorf("expected Method 'GET', got '%s'", httpMonitor.Method)
+ }
+ if httpMonitor.Timeout != 45000 {
+ t.Errorf("expected Timeout 45000, got %d", httpMonitor.Timeout)
+ }
+}
+
+func TestMonitors_TCPMonitorFields(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.Monitors(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if len(resp.Msg.TcpMonitors) != 1 {
+ t.Fatalf("expected 1 TCP monitor, got %d", len(resp.Msg.TcpMonitors))
+ }
+
+ tcpMonitor := resp.Msg.TcpMonitors[0]
+ if tcpMonitor.Id != "6" {
+ t.Errorf("expected ID '6', got '%s'", tcpMonitor.Id)
+ }
+ if tcpMonitor.Uri != "tcp://db.example.com:5432" {
+ t.Errorf("expected URI 'tcp://db.example.com:5432', got '%s'", tcpMonitor.Uri)
+ }
+ if tcpMonitor.Periodicity != "5m" {
+ t.Errorf("expected Periodicity '5m', got '%s'", tcpMonitor.Periodicity)
+ }
+ if tcpMonitor.Timeout != 30000 {
+ t.Errorf("expected Timeout 30000, got %d", tcpMonitor.Timeout)
+ }
+ if tcpMonitor.Retry != 2 {
+ t.Errorf("expected Retry 2, got %d", tcpMonitor.Retry)
+ }
+ if tcpMonitor.DegradedAt == nil || *tcpMonitor.DegradedAt != 5000 {
+ t.Errorf("expected DegradedAt 5000, got %v", tcpMonitor.DegradedAt)
+ }
+}
+
+func TestParseRecordAssertions_DnsRecordContains(t *testing.T) {
+ input := `[{"version":"v1","type":"dnsRecord","key":"A","compare":"contains","target":"76.76.21.21"}]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions))
+ }
+
+ got := recordAssertions[0]
+ if got.Record != "A" {
+ t.Errorf("expected Record to be 'A', got '%s'", got.Record)
+ }
+ if got.Target != "76.76.21.21" {
+ t.Errorf("expected Target to be '76.76.21.21', got '%s'", got.Target)
+ }
+ if got.Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_CONTAINS {
+ t.Errorf("expected Comparator to be RECORD_COMPARATOR_CONTAINS, got %v", got.Comparator)
+ }
+}
+
+func TestParseRecordAssertions_DnsRecordEquals(t *testing.T) {
+ input := `[{"version":"v1","type":"dnsRecord","key":"CNAME","compare":"eq","target":"openstatus.dev"}]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions))
+ }
+
+ got := recordAssertions[0]
+ if got.Record != "CNAME" {
+ t.Errorf("expected Record to be 'CNAME', got '%s'", got.Record)
+ }
+ if got.Target != "openstatus.dev" {
+ t.Errorf("expected Target to be 'openstatus.dev', got '%s'", got.Target)
+ }
+ if got.Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_EQUAL {
+ t.Errorf("expected Comparator to be RECORD_COMPARATOR_EQUAL, got %v", got.Comparator)
+ }
+}
+
+func TestParseRecordAssertions_MultipleRecordTypes(t *testing.T) {
+ input := `[
+ {"version":"v1","type":"dnsRecord","key":"A","compare":"eq","target":"192.168.1.1"},
+ {"version":"v1","type":"dnsRecord","key":"AAAA","compare":"not_eq","target":"::1"},
+ {"version":"v1","type":"dnsRecord","key":"MX","compare":"not_contains","target":"spam"}
+ ]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 3 {
+ t.Fatalf("expected 3 record assertions, got %d", len(recordAssertions))
+ }
+
+ // Check A record
+ if recordAssertions[0].Record != "A" {
+ t.Errorf("expected first Record to be 'A', got '%s'", recordAssertions[0].Record)
+ }
+ if recordAssertions[0].Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_EQUAL {
+ t.Errorf("expected first Comparator to be RECORD_COMPARATOR_EQUAL, got %v", recordAssertions[0].Comparator)
+ }
+
+ // Check AAAA record
+ if recordAssertions[1].Record != "AAAA" {
+ t.Errorf("expected second Record to be 'AAAA', got '%s'", recordAssertions[1].Record)
+ }
+ if recordAssertions[1].Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_NOT_EQUAL {
+ t.Errorf("expected second Comparator to be RECORD_COMPARATOR_NOT_EQUAL, got %v", recordAssertions[1].Comparator)
+ }
+
+ // Check MX record
+ if recordAssertions[2].Record != "MX" {
+ t.Errorf("expected third Record to be 'MX', got '%s'", recordAssertions[2].Record)
+ }
+ if recordAssertions[2].Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_NOT_CONTAINS {
+ t.Errorf("expected third Comparator to be RECORD_COMPARATOR_NOT_CONTAINS, got %v", recordAssertions[2].Comparator)
+ }
+}
+
+func TestParseRecordAssertions_InvalidJSON(t *testing.T) {
+ assertions := sql.NullString{
+ String: "not valid json",
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 0 {
+ t.Errorf("expected empty assertions for invalid JSON, got %d", len(recordAssertions))
+ }
+}
+
+func TestParseRecordAssertions_NullString(t *testing.T) {
+ assertions := sql.NullString{
+ String: "",
+ Valid: false,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if recordAssertions != nil {
+ t.Errorf("expected nil for null string, got %v", recordAssertions)
+ }
+}
+
+func TestParseRecordAssertions_MixedAssertionTypes(t *testing.T) {
+ // Test that only dnsRecord assertions are parsed, not other types
+ input := `[
+ {"version":"v1","type":"status","compare":"eq","target":200},
+ {"version":"v1","type":"dnsRecord","key":"A","compare":"contains","target":"192.168.1.1"},
+ {"version":"v1","type":"header","compare":"eq","key":"Content-Type","target":"application/json"}
+ ]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion (only dnsRecord), got %d", len(recordAssertions))
+ }
+
+ if recordAssertions[0].Record != "A" {
+ t.Errorf("expected Record to be 'A', got '%s'", recordAssertions[0].Record)
+ }
+}
+
+func TestMonitors_DNSMonitorFields(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.Monitors(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if len(resp.Msg.DnsMonitors) != 1 {
+ t.Fatalf("expected 1 DNS monitor, got %d", len(resp.Msg.DnsMonitors))
+ }
+
+ dnsMonitor := resp.Msg.DnsMonitors[0]
+ if dnsMonitor.Id != "7" {
+ t.Errorf("expected ID '7', got '%s'", dnsMonitor.Id)
+ }
+ if dnsMonitor.Uri != "openstatus.dev" {
+ t.Errorf("expected URI 'openstatus.dev', got '%s'", dnsMonitor.Uri)
+ }
+ if dnsMonitor.Periodicity != "5m" {
+ t.Errorf("expected Periodicity '5m', got '%s'", dnsMonitor.Periodicity)
+ }
+ if dnsMonitor.Timeout != 30000 {
+ t.Errorf("expected Timeout 30000, got %d", dnsMonitor.Timeout)
+ }
+ if dnsMonitor.Retry != 2 {
+ t.Errorf("expected Retry 2, got %d", dnsMonitor.Retry)
+ }
+ if dnsMonitor.DegradedAt == nil || *dnsMonitor.DegradedAt != 3000 {
+ t.Errorf("expected DegradedAt 3000, got %v", dnsMonitor.DegradedAt)
+ }
+}
+
+func TestParseRecordAssertions_EmptyArray(t *testing.T) {
+ assertions := sql.NullString{
+ String: "[]",
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 0 {
+ t.Errorf("expected empty slice for empty JSON array, got %d", len(recordAssertions))
+ }
+}
+
+func TestParseRecordAssertions_UnknownComparator(t *testing.T) {
+ input := `[{"version":"v1","type":"dnsRecord","key":"A","compare":"unknown_comparator","target":"192.168.1.1"}]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions))
+ }
+
+ got := recordAssertions[0]
+ if got.Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_UNSPECIFIED {
+ t.Errorf("expected Comparator to be RECORD_COMPARATOR_UNSPECIFIED for unknown comparator, got %v", got.Comparator)
+ }
+}
+
+func TestParseRecordAssertions_UnknownRecordType(t *testing.T) {
+ input := `[{"version":"v1","type":"dnsRecord","key":"INVALID_RECORD_TYPE","compare":"eq","target":"test"}]`
+ assertions := sql.NullString{
+ String: input,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions))
+ }
+
+ got := recordAssertions[0]
+ // The record type is passed through as-is, even if invalid
+ if got.Record != "INVALID_RECORD_TYPE" {
+ t.Errorf("expected Record to be 'INVALID_RECORD_TYPE', got '%s'", got.Record)
+ }
+}
+
+func TestParseRecordAssertions_MissingRequiredFields(t *testing.T) {
+ // Missing "key" field
+ inputMissingKey := `[{"version":"v1","type":"dnsRecord","compare":"eq","target":"test"}]`
+ assertions := sql.NullString{
+ String: inputMissingKey,
+ Valid: true,
+ }
+
+ recordAssertions := server.ParseRecordAssertions(assertions)
+
+ if len(recordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions))
+ }
+
+ // Missing key results in empty string
+ if recordAssertions[0].Record != "" {
+ t.Errorf("expected empty Record for missing key, got '%s'", recordAssertions[0].Record)
+ }
+
+ // Missing "compare" field
+ inputMissingCompare := `[{"version":"v1","type":"dnsRecord","key":"A","target":"test"}]`
+ assertions2 := sql.NullString{
+ String: inputMissingCompare,
+ Valid: true,
+ }
+
+ recordAssertions2 := server.ParseRecordAssertions(assertions2)
+
+ if len(recordAssertions2) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions2))
+ }
+
+ // Missing compare results in unspecified comparator
+ if recordAssertions2[0].Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_UNSPECIFIED {
+ t.Errorf("expected RECORD_COMPARATOR_UNSPECIFIED for missing compare, got %v", recordAssertions2[0].Comparator)
+ }
+
+ // Missing "target" field
+ inputMissingTarget := `[{"version":"v1","type":"dnsRecord","key":"A","compare":"eq"}]`
+ assertions3 := sql.NullString{
+ String: inputMissingTarget,
+ Valid: true,
+ }
+
+ recordAssertions3 := server.ParseRecordAssertions(assertions3)
+
+ if len(recordAssertions3) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(recordAssertions3))
+ }
+
+ // Missing target results in empty string
+ if recordAssertions3[0].Target != "" {
+ t.Errorf("expected empty Target for missing target, got '%s'", recordAssertions3[0].Target)
+ }
+}
+
+func TestMonitors_DNSMonitorWithRecordAssertions(t *testing.T) {
+ h := server.NewPrivateLocationServer(testDB(), getTBClient(context.Background()))
+
+ req := connect.NewRequest(&private_locationv1.MonitorsRequest{})
+ req.Header().Set("openstatus-token", "my-secret-key")
+
+ resp, err := h.Monitors(context.Background(), req)
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if len(resp.Msg.DnsMonitors) != 1 {
+ t.Fatalf("expected 1 DNS monitor, got %d", len(resp.Msg.DnsMonitors))
+ }
+
+ dnsMonitor := resp.Msg.DnsMonitors[0]
+ if len(dnsMonitor.RecordAssertions) != 1 {
+ t.Fatalf("expected 1 record assertion, got %d", len(dnsMonitor.RecordAssertions))
+ }
+
+ assertion := dnsMonitor.RecordAssertions[0]
+ if assertion.Record != "A" {
+ t.Errorf("expected Record 'A', got '%s'", assertion.Record)
+ }
+ if assertion.Target != "76.76.21.21" {
+ t.Errorf("expected Target '76.76.21.21', got '%s'", assertion.Target)
+ }
+ if assertion.Comparator != private_locationv1.RecordComparator_RECORD_COMPARATOR_CONTAINS {
+ t.Errorf("expected Comparator RECORD_COMPARATOR_CONTAINS, got %v", assertion.Comparator)
+ }
+}
diff --git a/apps/private-location/internal/server/routes.go b/apps/private-location/internal/server/routes.go
index 276068c8b..055df5c1c 100644
--- a/apps/private-location/internal/server/routes.go
+++ b/apps/private-location/internal/server/routes.go
@@ -161,9 +161,17 @@ func (s *Server) RegisterRoutes() http.Handler {
// healthHandler responds with the health status of the server.
func (s *Server) healthHandler(w http.ResponseWriter, r *http.Request) {
+ status := "ok"
+ httpStatus := http.StatusOK
+ // Check database connection
+ if err := s.db.PingContext(r.Context()); err != nil {
+ status = "degraded"
+ httpStatus = http.StatusServiceUnavailable
+ }
+
+ render.Status(r, httpStatus)
render.JSON(w, r, map[string]any{
- "status": "ok",
+ "status": status,
})
- render.Status(r, http.StatusOK)
}
diff --git a/apps/private-location/internal/server/server.go b/apps/private-location/internal/server/server.go
index 3e695efe3..b561f0a24 100644
--- a/apps/private-location/internal/server/server.go
+++ b/apps/private-location/internal/server/server.go
@@ -31,7 +31,15 @@ type Server struct {
// NewServer returns an HTTP server and a cleanup function to shutdown the log provider.
func NewServer() (*http.Server, func(context.Context)) {
- port, _ := strconv.Atoi(os.Getenv("PORT"))
+ portStr := os.Getenv("PORT")
+ if portStr == "" {
+ portStr = "8080"
+ }
+ port, err := strconv.Atoi(portStr)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "invalid PORT value %q: %v\n", portStr, err)
+ os.Exit(1)
+ }
logger, logProvider := setupLogger()
@@ -56,6 +64,7 @@ func NewServer() (*http.Server, func(context.Context)) {
if logProvider != nil {
logProvider.Shutdown(ctx)
}
+ database.Close()
}
return server, cleanup
diff --git a/apps/private-location/internal/server/validation.go b/apps/private-location/internal/server/validation.go
new file mode 100644
index 000000000..6f375a78c
--- /dev/null
+++ b/apps/private-location/internal/server/validation.go
@@ -0,0 +1,64 @@
+package server
+
+import (
+ "errors"
+ "fmt"
+
+ "connectrpc.com/connect"
+ private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
+)
+
+// Validation errors
+var (
+ ErrEmptyMonitorID = errors.New("monitor_id is required")
+ ErrEmptyID = errors.New("id is required")
+ ErrInvalidLatency = errors.New("latency must be non-negative")
+ ErrInvalidTimestamp = errors.New("timestamp must be positive")
+)
+
+// ValidateIngestHTTPRequest validates an HTTP ingest request
+func ValidateIngestHTTPRequest(req *private_locationv1.IngestHTTPRequest) error {
+ if req.MonitorId == "" {
+ return ErrEmptyMonitorID
+ }
+ if req.Latency < 0 {
+ return ErrInvalidLatency
+ }
+ if req.Timestamp <= 0 {
+ return ErrInvalidTimestamp
+ }
+ return nil
+}
+
+// ValidateIngestTCPRequest validates a TCP ingest request
+func ValidateIngestTCPRequest(req *private_locationv1.IngestTCPRequest) error {
+ if req.Id == "" {
+ return ErrEmptyID
+ }
+ if req.Latency < 0 {
+ return ErrInvalidLatency
+ }
+ if req.Timestamp <= 0 {
+ return ErrInvalidTimestamp
+ }
+ return nil
+}
+
+// ValidateIngestDNSRequest validates a DNS ingest request
+func ValidateIngestDNSRequest(req *private_locationv1.IngestDNSRequest) error {
+ if req.Id == "" {
+ return ErrEmptyID
+ }
+ if req.Latency < 0 {
+ return ErrInvalidLatency
+ }
+ if req.Timestamp <= 0 {
+ return ErrInvalidTimestamp
+ }
+ return nil
+}
+
+// NewValidationError creates a Connect error for validation failures
+func NewValidationError(err error) *connect.Error {
+ return connect.NewError(connect.CodeInvalidArgument, fmt.Errorf("validation error: %w", err))
+}
diff --git a/apps/private-location/internal/server/validation_test.go b/apps/private-location/internal/server/validation_test.go
new file mode 100644
index 000000000..7414a8666
--- /dev/null
+++ b/apps/private-location/internal/server/validation_test.go
@@ -0,0 +1,271 @@
+package server_test
+
+import (
+ "testing"
+
+ "connectrpc.com/connect"
+ "github.com/openstatushq/openstatus/apps/private-location/internal/server"
+ private_locationv1 "github.com/openstatushq/openstatus/apps/private-location/proto/private_location/v1"
+)
+
+func TestValidateIngestHTTPRequest(t *testing.T) {
+ tests := []struct {
+ name string
+ req *private_locationv1.IngestHTTPRequest
+ wantErr error
+ }{
+ {
+ name: "valid request",
+ req: &private_locationv1.IngestHTTPRequest{
+ MonitorId: "monitor-123",
+ Latency: 100,
+ Timestamp: 1234567890,
+ },
+ wantErr: nil,
+ },
+ {
+ name: "valid request with zero latency",
+ req: &private_locationv1.IngestHTTPRequest{
+ MonitorId: "monitor-123",
+ Latency: 0,
+ Timestamp: 1234567890,
+ },
+ wantErr: nil,
+ },
+ {
+ name: "empty monitor_id",
+ req: &private_locationv1.IngestHTTPRequest{
+ MonitorId: "",
+ Latency: 100,
+ Timestamp: 1234567890,
+ },
+ wantErr: server.ErrEmptyMonitorID,
+ },
+ {
+ name: "negative latency",
+ req: &private_locationv1.IngestHTTPRequest{
+ MonitorId: "monitor-123",
+ Latency: -1,
+ Timestamp: 1234567890,
+ },
+ wantErr: server.ErrInvalidLatency,
+ },
+ {
+ name: "zero timestamp",
+ req: &private_locationv1.IngestHTTPRequest{
+ MonitorId: "monitor-123",
+ Latency: 100,
+ Timestamp: 0,
+ },
+ wantErr: server.ErrInvalidTimestamp,
+ },
+ {
+ name: "negative timestamp",
+ req: &private_locationv1.IngestHTTPRequest{
+ MonitorId: "monitor-123",
+ Latency: 100,
+ Timestamp: -1,
+ },
+ wantErr: server.ErrInvalidTimestamp,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := server.ValidateIngestHTTPRequest(tt.req)
+ if err != tt.wantErr {
+ t.Errorf("ValidateIngestHTTPRequest() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestValidateIngestTCPRequest(t *testing.T) {
+ tests := []struct {
+ name string
+ req *private_locationv1.IngestTCPRequest
+ wantErr error
+ }{
+ {
+ name: "valid request",
+ req: &private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Latency: 100,
+ Timestamp: 1234567890,
+ },
+ wantErr: nil,
+ },
+ {
+ name: "valid request with zero latency",
+ req: &private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Latency: 0,
+ Timestamp: 1234567890,
+ },
+ wantErr: nil,
+ },
+ {
+ name: "empty id",
+ req: &private_locationv1.IngestTCPRequest{
+ Id: "",
+ Latency: 100,
+ Timestamp: 1234567890,
+ },
+ wantErr: server.ErrEmptyID,
+ },
+ {
+ name: "negative latency",
+ req: &private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Latency: -1,
+ Timestamp: 1234567890,
+ },
+ wantErr: server.ErrInvalidLatency,
+ },
+ {
+ name: "zero timestamp",
+ req: &private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Latency: 100,
+ Timestamp: 0,
+ },
+ wantErr: server.ErrInvalidTimestamp,
+ },
+ {
+ name: "negative timestamp",
+ req: &private_locationv1.IngestTCPRequest{
+ Id: "tcp-123",
+ Latency: 100,
+ Timestamp: -1,
+ },
+ wantErr: server.ErrInvalidTimestamp,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := server.ValidateIngestTCPRequest(tt.req)
+ if err != tt.wantErr {
+ t.Errorf("ValidateIngestTCPRequest() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestValidateIngestDNSRequest(t *testing.T) {
+ tests := []struct {
+ name string
+ req *private_locationv1.IngestDNSRequest
+ wantErr error
+ }{
+ {
+ name: "valid request",
+ req: &private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Latency: 100,
+ Timestamp: 1234567890,
+ },
+ wantErr: nil,
+ },
+ {
+ name: "valid request with zero latency",
+ req: &private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Latency: 0,
+ Timestamp: 1234567890,
+ },
+ wantErr: nil,
+ },
+ {
+ name: "empty id",
+ req: &private_locationv1.IngestDNSRequest{
+ Id: "",
+ Latency: 100,
+ Timestamp: 1234567890,
+ },
+ wantErr: server.ErrEmptyID,
+ },
+ {
+ name: "negative latency",
+ req: &private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Latency: -1,
+ Timestamp: 1234567890,
+ },
+ wantErr: server.ErrInvalidLatency,
+ },
+ {
+ name: "zero timestamp",
+ req: &private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Latency: 100,
+ Timestamp: 0,
+ },
+ wantErr: server.ErrInvalidTimestamp,
+ },
+ {
+ name: "negative timestamp",
+ req: &private_locationv1.IngestDNSRequest{
+ Id: "dns-123",
+ Latency: 100,
+ Timestamp: -1,
+ },
+ wantErr: server.ErrInvalidTimestamp,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := server.ValidateIngestDNSRequest(tt.req)
+ if err != tt.wantErr {
+ t.Errorf("ValidateIngestDNSRequest() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
+func TestNewValidationError(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ wantCode connect.Code
+ wantContains string
+ }{
+ {
+ name: "empty monitor id error",
+ err: server.ErrEmptyMonitorID,
+ wantCode: connect.CodeInvalidArgument,
+ wantContains: "monitor_id is required",
+ },
+ {
+ name: "empty id error",
+ err: server.ErrEmptyID,
+ wantCode: connect.CodeInvalidArgument,
+ wantContains: "id is required",
+ },
+ {
+ name: "invalid latency error",
+ err: server.ErrInvalidLatency,
+ wantCode: connect.CodeInvalidArgument,
+ wantContains: "latency must be non-negative",
+ },
+ {
+ name: "invalid timestamp error",
+ err: server.ErrInvalidTimestamp,
+ wantCode: connect.CodeInvalidArgument,
+ wantContains: "timestamp must be positive",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ connErr := server.NewValidationError(tt.err)
+ if connErr.Code() != tt.wantCode {
+ t.Errorf("NewValidationError() code = %v, want %v", connErr.Code(), tt.wantCode)
+ }
+ if connErr.Message() == "" {
+ t.Error("NewValidationError() message should not be empty")
+ }
+ })
+ }
+}
diff --git a/apps/private-location/internal/tinybird/client.go b/apps/private-location/internal/tinybird/client.go
index f138c36bc..0d289a563 100644
--- a/apps/private-location/internal/tinybird/client.go
+++ b/apps/private-location/internal/tinybird/client.go
@@ -12,6 +12,13 @@ import (
"github.com/rs/zerolog/log"
)
+// Datasource names for Tinybird events
+const (
+ DatasourceHTTP = "ping_response__v8"
+ DatasourceTCP = "tcp_response__v0"
+ DatasourceDNS = "tcp_dns__v0"
+)
+
func getBaseURL() string {
// Use local Tinybird container if available (Docker/self-hosted)
// https://www.tinybird.co/docs/api-reference
diff --git a/apps/private-location/proto/private_location/v1/assertions.pb.go b/apps/private-location/proto/private_location/v1/assertions.pb.go
index 0fd81a8d2..df95ef360 100644
--- a/apps/private-location/proto/private_location/v1/assertions.pb.go
+++ b/apps/private-location/proto/private_location/v1/assertions.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/assertions.proto
@@ -378,7 +378,7 @@ type RecordAssertion struct {
state protoimpl.MessageState `protogen:"open.v1"`
Record string `protobuf:"bytes,1,opt,name=record,proto3" json:"record,omitempty"`
Comparator RecordComparator `protobuf:"varint,2,opt,name=comparator,proto3,enum=private_location.v1.RecordComparator" json:"comparator,omitempty"`
- Targert string `protobuf:"bytes,3,opt,name=targert,proto3" json:"targert,omitempty"`
+ Target string `protobuf:"bytes,3,opt,name=target,proto3" json:"target,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -427,9 +427,9 @@ func (x *RecordAssertion) GetComparator() RecordComparator {
return RecordComparator_RECORD_COMPARATOR_UNSPECIFIED
}
-func (x *RecordAssertion) GetTargert() string {
+func (x *RecordAssertion) GetTarget() string {
if x != nil {
- return x.Targert
+ return x.Target
}
return ""
}
@@ -454,13 +454,13 @@ const file_private_location_v1_assertions_proto_rawDesc = "" +
"\n" +
"comparator\x18\x02 \x01(\x0e2%.private_location.v1.StringComparatorR\n" +
"comparator\x12\x10\n" +
- "\x03key\x18\x03 \x01(\tR\x03key\"\x8a\x01\n" +
+ "\x03key\x18\x03 \x01(\tR\x03key\"\x88\x01\n" +
"\x0fRecordAssertion\x12\x16\n" +
"\x06record\x18\x01 \x01(\tR\x06record\x12E\n" +
"\n" +
"comparator\x18\x02 \x01(\x0e2%.private_location.v1.RecordComparatorR\n" +
- "comparator\x12\x18\n" +
- "\atargert\x18\x03 \x01(\tR\atargert*\x8f\x02\n" +
+ "comparator\x12\x16\n" +
+ "\x06target\x18\x03 \x01(\tR\x06target*\x8f\x02\n" +
"\x10NumberComparator\x12!\n" +
"\x1dNUMBER_COMPARATOR_UNSPECIFIED\x10\x00\x12\x1b\n" +
"\x17NUMBER_COMPARATOR_EQUAL\x10\x01\x12\x1f\n" +
diff --git a/apps/private-location/proto/private_location/v1/dns_monitor.pb.go b/apps/private-location/proto/private_location/v1/dns_monitor.pb.go
index 6a86da108..e96c9bc87 100644
--- a/apps/private-location/proto/private_location/v1/dns_monitor.pb.go
+++ b/apps/private-location/proto/private_location/v1/dns_monitor.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/dns_monitor.proto
diff --git a/apps/private-location/proto/private_location/v1/http_monitor.pb.go b/apps/private-location/proto/private_location/v1/http_monitor.pb.go
index 866cdc4f1..e3527d5be 100644
--- a/apps/private-location/proto/private_location/v1/http_monitor.pb.go
+++ b/apps/private-location/proto/private_location/v1/http_monitor.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/http_monitor.proto
diff --git a/apps/private-location/proto/private_location/v1/private_location.pb.go b/apps/private-location/proto/private_location/v1/private_location.pb.go
index 29804740c..71a8399a1 100644
--- a/apps/private-location/proto/private_location/v1/private_location.pb.go
+++ b/apps/private-location/proto/private_location/v1/private_location.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/private_location.proto
diff --git a/apps/private-location/proto/private_location/v1/tcp_monitor.pb.go b/apps/private-location/proto/private_location/v1/tcp_monitor.pb.go
index d81c9b7d5..3cc2ba3a7 100644
--- a/apps/private-location/proto/private_location/v1/tcp_monitor.pb.go
+++ b/apps/private-location/proto/private_location/v1/tcp_monitor.pb.go
@@ -1,6 +1,6 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
-// protoc-gen-go v1.36.10
+// protoc-gen-go v1.36.11
// protoc (unknown)
// source: private_location/v1/tcp_monitor.proto
diff --git a/packages/proto/private_location/v1/assertions.proto b/packages/proto/private_location/v1/assertions.proto
index 6c7d8c9b6..229d02ccc 100644
--- a/packages/proto/private_location/v1/assertions.proto
+++ b/packages/proto/private_location/v1/assertions.proto
@@ -55,5 +55,5 @@ message HeaderAssertion {
message RecordAssertion {
string record = 1;
RecordComparator comparator = 2;
- string targert = 3;
+ string target = 3;
}