• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Permify / permify / 10549558409

25 Aug 2024 07:29PM UTC coverage: 79.849%. Remained the same
10549558409

push

github

web-flow
Merge pull request #1495 from Permify/dependabot/go_modules/github.com/rs/xid-1.6.0

8020 of 10044 relevant lines covered (79.85%)

114.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

62.61
/internal/storage/postgres/utils/common.go
1
package utils
2

3
import (
4
        "context"
5
        "errors"
6
        "fmt"
7
        "log/slog"
8
        "math"
9
        "strings"
10
        "time"
11

12
        "go.opentelemetry.io/otel/codes"
13
        "golang.org/x/exp/rand"
14

15
        "go.opentelemetry.io/otel/trace"
16

17
        "github.com/Masterminds/squirrel"
18

19
        base "github.com/Permify/permify/pkg/pb/base/v1"
20
)
21

22
const (
23
        BulkEntityFilterTemplate = `
24
WITH filtered_entities AS (
25
    SELECT DISTINCT ON (entity_id) id, entity_id
26
    FROM (
27
        SELECT id, entity_id, tenant_id, entity_type, created_tx_id, expired_tx_id
28
        FROM relation_tuples
29
        WHERE tenant_id = '%s' AND entity_type = '%s' AND %s AND %s
30
        UNION ALL
31
        SELECT id, entity_id, tenant_id, entity_type, created_tx_id, expired_tx_id
32
        FROM attributes
33
        WHERE tenant_id = '%s' AND entity_type = '%s' AND %s AND %s
34
    ) AS entities
35
)
36
SELECT entity_id
37
FROM filtered_entities
38
`
39

40
        TransactionTemplate  = `INSERT INTO transactions (tenant_id) VALUES ($1) RETURNING id`
41
        InsertTenantTemplate = `INSERT INTO tenants (id, name) VALUES ($1, $2) RETURNING created_at`
42
        DeleteTenantTemplate = `DELETE FROM tenants WHERE id = $1 RETURNING name, created_at`
43
)
44

45
// SnapshotQuery adds conditions to a SELECT query for checking transaction visibility based on created and expired transaction IDs.
46
// The query checks if transactions are visible in a snapshot associated with the provided value.
47
func SnapshotQuery(sl squirrel.SelectBuilder, value uint64) squirrel.SelectBuilder {
1✔
48
        // Convert the value to a string once to reduce redundant calls to fmt.Sprintf.
1✔
49
        valStr := fmt.Sprintf("'%v'::xid8", value)
1✔
50

1✔
51
        // Create a subquery for the snapshot associated with the provided value.
1✔
52
        snapshotQuery := fmt.Sprintf("(select snapshot from transactions where id = %s)", valStr)
1✔
53

1✔
54
        // Create an expression to check if a transaction with a specific created_tx_id is visible in the snapshot.
1✔
55
        visibilityExpr := squirrel.Expr(fmt.Sprintf("pg_visible_in_snapshot(created_tx_id, %s) = true", snapshotQuery))
1✔
56
        // Create an expression to check if the created_tx_id is equal to the provided value.
1✔
57
        createdExpr := squirrel.Expr(fmt.Sprintf("created_tx_id = %s", valStr))
1✔
58
        // Use OR condition for the created expressions.
1✔
59
        createdWhere := squirrel.Or{visibilityExpr, createdExpr}
1✔
60

1✔
61
        // Create an expression to check if a transaction with a specific expired_tx_id is not visible in the snapshot.
1✔
62
        expiredVisibilityExpr := squirrel.Expr(fmt.Sprintf("pg_visible_in_snapshot(expired_tx_id, %s) = false", snapshotQuery))
1✔
63
        // Create an expression to check if the expired_tx_id is equal to zero.
1✔
64
        expiredZeroExpr := squirrel.Expr("expired_tx_id = '0'::xid8")
1✔
65
        // Create an expression to check if the expired_tx_id is not equal to the provided value.
1✔
66
        expiredNotExpr := squirrel.Expr(fmt.Sprintf("expired_tx_id <> %s", valStr))
1✔
67
        // Use AND condition for the expired expressions, checking both visibility and non-equality with value.
1✔
68
        expiredWhere := squirrel.And{squirrel.Or{expiredVisibilityExpr, expiredZeroExpr}, expiredNotExpr}
1✔
69

1✔
70
        // Add the created and expired conditions to the SELECT query.
1✔
71
        return sl.Where(createdWhere).Where(expiredWhere)
1✔
72
}
1✔
73

74
// snapshotQuery function generates two strings representing conditions to be applied in a SQL query to filter data based on visibility of transactions.
75
func snapshotQuery(value uint64) (string, string) {
1✔
76
        // Convert the provided value into a string format suitable for our SQL query, formatted as a transaction ID.
1✔
77
        valStr := fmt.Sprintf("'%v'::xid8", value)
1✔
78

1✔
79
        // Create a subquery that fetches the snapshot associated with the transaction ID.
1✔
80
        snapshotQ := fmt.Sprintf("(SELECT snapshot FROM transactions WHERE id = %s)", valStr)
1✔
81

1✔
82
        // Create an expression that checks whether a transaction (represented by 'created_tx_id') is visible in the snapshot.
1✔
83
        visibilityExpr := fmt.Sprintf("pg_visible_in_snapshot(created_tx_id, %s) = true", snapshotQ)
1✔
84
        // Create an expression that checks if the 'created_tx_id' is the same as our transaction ID.
1✔
85
        createdExpr := fmt.Sprintf("created_tx_id = %s", valStr)
1✔
86
        // Combine these expressions to form a condition. A row will satisfy this condition if either of the expressions are true.
1✔
87
        createdWhere := fmt.Sprintf("(%s OR %s)", visibilityExpr, createdExpr)
1✔
88

1✔
89
        // Create an expression that checks whether a transaction (represented by 'expired_tx_id') is not visible in the snapshot.
1✔
90
        expiredVisibilityExpr := fmt.Sprintf("pg_visible_in_snapshot(expired_tx_id, %s) = false", snapshotQ)
1✔
91
        // Create an expression that checks if the 'expired_tx_id' is zero. This handles cases where the transaction hasn't expired.
1✔
92
        expiredZeroExpr := "expired_tx_id = '0'::xid8"
1✔
93
        // Create an expression that checks if the 'expired_tx_id' is not the same as our transaction ID.
1✔
94
        expiredNotExpr := fmt.Sprintf("expired_tx_id <> %s", valStr)
1✔
95
        // Combine these expressions to form a condition. A row will satisfy this condition if the first set of expressions are true (either the transaction hasn't expired, or if it has, it's not visible in the snapshot) and the second expression is also true (the 'expired_tx_id' is not the same as our transaction ID).
1✔
96
        expiredWhere := fmt.Sprintf("(%s AND %s)", fmt.Sprintf("(%s OR %s)", expiredVisibilityExpr, expiredZeroExpr), expiredNotExpr)
1✔
97

1✔
98
        // Return the conditions for both 'created' and 'expired' transactions. These can be used in a WHERE clause of a SQL query to filter results.
1✔
99
        return createdWhere, expiredWhere
1✔
100
}
1✔
101

102
// BulkEntityFilterQuery -
103
func BulkEntityFilterQuery(tenantID, entityType string, snap uint64) string {
1✔
104
        createdWhere, expiredWhere := snapshotQuery(snap)
1✔
105
        return fmt.Sprintf(BulkEntityFilterTemplate, tenantID, entityType, createdWhere, expiredWhere, tenantID, entityType, createdWhere, expiredWhere)
1✔
106
}
1✔
107

108
// GenerateGCQuery generates a Squirrel DELETE query builder for garbage collection.
109
// It constructs a query to delete expired records from the specified table
110
// based on the provided value, which represents a transaction ID.
111
func GenerateGCQuery(table string, value uint64) squirrel.DeleteBuilder {
1✔
112
        // Convert the provided value into a string format suitable for our SQL query, formatted as a transaction ID.
1✔
113
        valStr := fmt.Sprintf("'%v'::xid8", value)
1✔
114

1✔
115
        // Create a Squirrel DELETE builder for the specified table.
1✔
116
        deleteBuilder := squirrel.Delete(table)
1✔
117

1✔
118
        // Create an expression to check if 'expired_tx_id' is not equal to '0' (not expired).
1✔
119
        expiredZeroExpr := squirrel.Expr("expired_tx_id <> '0'::xid8")
1✔
120

1✔
121
        // Create an expression to check if 'expired_tx_id' is less than the provided value (before the cutoff).
1✔
122
        beforeExpr := squirrel.Expr(fmt.Sprintf("expired_tx_id < %s", valStr))
1✔
123

1✔
124
        // Add the WHERE clauses to the DELETE query builder to filter and delete expired data.
1✔
125
        return deleteBuilder.Where(expiredZeroExpr).Where(beforeExpr)
1✔
126
}
1✔
127

128
// HandleError records an error in the given span, logs the error, and returns a standardized error.
129
// This function is used for consistent error handling across different parts of the application.
130
func HandleError(ctx context.Context, span trace.Span, err error, errorCode base.ErrorCode) error {
×
131
        // Check if the error is context-related
×
132
        if IsContextRelatedError(ctx, err) {
×
133
                slog.DebugContext(ctx, "A context-related error occurred",
×
134
                        slog.String("error", err.Error()))
×
135
                return errors.New(base.ErrorCode_ERROR_CODE_CANCELLED.String())
×
136
        }
×
137

138
        // Check if the error is serialization-related
139
        if IsSerializationRelatedError(err) {
×
140
                slog.DebugContext(ctx, "A serialization-related error occurred",
×
141
                        slog.String("error", err.Error()))
×
142
                return errors.New(base.ErrorCode_ERROR_CODE_SERIALIZATION.String())
×
143
        }
×
144

145
        // For all other types of errors, log them at the error level and record them in the span
146
        slog.ErrorContext(ctx, "An operational error occurred",
×
147
                slog.Any("error", err))
×
148
        span.RecordError(err)
×
149
        span.SetStatus(codes.Error, err.Error())
×
150

×
151
        // Return a new error with the standard error code provided
×
152
        return errors.New(errorCode.String())
×
153
}
154

155
// IsContextRelatedError checks if the error is due to context cancellation, deadline exceedance, or closed connection
156
func IsContextRelatedError(ctx context.Context, err error) bool {
×
157
        if errors.Is(ctx.Err(), context.Canceled) || errors.Is(ctx.Err(), context.DeadlineExceeded) {
×
158
                return true
×
159
        }
×
160
        if errors.Is(err, context.Canceled) ||
×
161
                errors.Is(err, context.DeadlineExceeded) ||
×
162
                strings.Contains(err.Error(), "conn closed") {
×
163
                return true
×
164
        }
×
165
        return false
×
166
}
167

168
// IsSerializationRelatedError checks if the error is a serialization failure, typically in database transactions.
169
func IsSerializationRelatedError(err error) bool {
×
170
        if strings.Contains(err.Error(), "could not serialize") ||
×
171
                strings.Contains(err.Error(), "duplicate key value") {
×
172
                return true
×
173
        }
×
174
        return false
×
175
}
176

177
// WaitWithBackoff implements an exponential backoff strategy with jitter for retries.
178
// It waits for a calculated duration or until the context is cancelled, whichever comes first.
179
func WaitWithBackoff(ctx context.Context, tenantID string, retries int) {
×
180
        backoff := time.Duration(math.Min(float64(20*time.Millisecond)*math.Pow(2, float64(retries)), float64(1*time.Second)))
×
181
        jitter := time.Duration(rand.Float64() * float64(backoff) * 0.5)
×
182
        nextBackoff := backoff + jitter
×
183
        slog.WarnContext(ctx, "waiting before retry", slog.String("tenant_id", tenantID), slog.Int64("backoff_duration", nextBackoff.Milliseconds()))
×
184
        select {
×
185
        case <-time.After(nextBackoff):
×
186
        case <-ctx.Done():
×
187
        }
188
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc