File size: 7,920 Bytes
fea99b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package entutils

import (
	"fmt"
	"time"

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/entsql"
	"entgo.io/ent/schema/field"
	"entgo.io/ent/schema/index"
	"entgo.io/ent/schema/mixin"
	"github.com/oklog/ulid/v2"

	"github.com/openmeterio/openmeter/pkg/clock"
	"github.com/openmeterio/openmeter/pkg/convert"
	"github.com/openmeterio/openmeter/pkg/models"
)

// UniqueResourceMixin adds common fields
type UniqueResourceMixin struct {
	mixin.Schema
}

func (UniqueResourceMixin) Fields() []ent.Field {
	fields := ResourceMixin{}.Fields()
	fields = append(fields, KeyMixin{}.Fields()...)

	return fields
}

func (UniqueResourceMixin) Indexes() []ent.Index {
	indexes := ResourceMixin{}.Indexes()

	// Key mixin indexes are not used, as now that we know we have namespaces, we can use a better index

	// Soft deleted items should not create a conflict with a new item with the same key.
	// The proper index would be:
	//
	// 	CREATE UNIQE INDEX x ON y (namespace, key) WHERE deleted_at IS NULL
	//
	// ENT only supports WHERE clauses on indexes via manually creating migrations, so
	// we could approximate that behavior using this index.
	//
	// Caveats: If two resources with the same key are deleted in the same microsecond then the
	// deletion will fail. (e.g. by doing a create, delete, create, delete in the same microsecond)
	indexes = append(indexes, index.Fields("namespace", "key", "deleted_at").Unique())

	return indexes
}

// ResourceMixin adds common fields
type ResourceMixin struct {
	mixin.Schema
	MetadataDeprecatedReason string
}

func (m ResourceMixin) Fields() []ent.Field {
	var fields []ent.Field
	fields = append(fields, IDMixin{}.Fields()...)
	fields = append(fields, NamespaceMixin{}.Fields()...)
	fields = append(fields, MetadataMixin{DeprecatedReason: m.MetadataDeprecatedReason}.Fields()...)
	fields = append(fields, TimeMixin{}.Fields()...)
	fields = append(fields,
		field.String("name"),
		field.String("description").Optional().Nillable(),
	)

	return fields
}

func (ResourceMixin) Indexes() []ent.Index {
	var indexes []ent.Index
	indexes = append(indexes, IDMixin{}.Indexes()...)
	indexes = append(indexes, NamespaceMixin{}.Indexes()...)
	indexes = append(indexes, MetadataMixin{}.Indexes()...)
	indexes = append(indexes, TimeMixin{}.Indexes()...)
	indexes = append(indexes, index.Fields("namespace", "id").Unique())

	return indexes
}

// IDMixin adds the ID field to the schema
type IDMixin struct {
	mixin.Schema
}

// Fields of the IDMixin.
func (IDMixin) Fields() []ent.Field {
	return []ent.Field{
		field.String("id").
			DefaultFunc(func() string {
				return ulid.Make().String()
			}).
			Unique().
			Immutable().
			SchemaType(map[string]string{
				dialect.Postgres: "char(26)",
			}),
	}
}

func (IDMixin) Indexes() []ent.Index {
	return []ent.Index{
		index.Fields("id").Unique(),
	}
}

type IDMixinGetter interface {
	GetID() string
}

type IDMixinCreator[T any] interface {
	SetID(id string) T
}

// KeyMixin adds the key field to the schema
type KeyMixin struct {
	mixin.Schema
}

// Fields of the KeyMixin.
func (KeyMixin) Fields() []ent.Field {
	return []ent.Field{
		field.String("key").
			NotEmpty().
			Immutable(),
	}
}

// NamespaceMixin can be used for namespaced entities
type NamespaceMixin struct {
	mixin.Schema
}

// Fields of the IDMixin.
func (NamespaceMixin) Fields() []ent.Field {
	return []ent.Field{
		field.String("namespace").
			NotEmpty().
			Immutable(),
	}
}

func (NamespaceMixin) Indexes() []ent.Index {
	return []ent.Index{
		index.Fields("namespace"),
	}
}

type NamespaceMixinGetter interface {
	GetNamespace() string
}

type NamespaceMixinCreator[T any] interface {
	SetNamespace(namespace string) T
}

// MetadataMixin adds metadata to the schema
type MetadataMixin struct {
	mixin.Schema
	DeprecatedReason string
}

// Fields of the IDMixin.
func (m MetadataMixin) Fields() []ent.Field {
	metadata := field.JSON("metadata", map[string]string{}).
		Optional().
		SchemaType(map[string]string{
			dialect.Postgres: "jsonb",
		})
	if m.DeprecatedReason != "" {
		metadata.Deprecated(m.DeprecatedReason)
	}

	return []ent.Field{metadata}
}

// AnnotationsMixin adds annotations to the schema
type AnnotationsMixin struct {
	mixin.Schema
	DeprecatedReason string
}

// Fields of the IDMixin.
func (m AnnotationsMixin) Fields() []ent.Field {
	annotations := field.JSON("annotations", models.Annotations{}).
		Optional().
		SchemaType(map[string]string{
			dialect.Postgres: "jsonb",
		})
	if m.DeprecatedReason != "" {
		annotations.Deprecated(m.DeprecatedReason)
	}

	return []ent.Field{annotations}
}

func (AnnotationsMixin) Indexes() []ent.Index {
	return []ent.Index{
		index.Fields("annotations").
			Annotations(
				entsql.IndexTypes(map[string]string{
					dialect.Postgres: "GIN",
				}),
			),
	}
}

type AnnotationsMixinGetter interface {
	GetAnnotations() models.Annotations
}

type AnnotationsMixinSetter[T any] interface {
	SetAnnotations(annotations models.Annotations) T
}

// TimeMixin adds the created_at and updated_at fields to the schema
type TimeMixin struct {
	mixin.Schema
}

// Fields of the TimeMixin.
func (TimeMixin) Fields() []ent.Field {
	return []ent.Field{
		field.Time("created_at").
			Default(truncatedNow).
			Immutable(),
		field.Time("updated_at").
			Default(truncatedNow).
			UpdateDefault(truncatedNow),
		field.Time("deleted_at").
			Optional().
			Nillable(),
	}
}

type TimeMixinGetter interface {
	GetCreatedAt() time.Time
	GetUpdatedAt() time.Time
	GetDeletedAt() *time.Time
}

type TimeMixinCreator[T any] interface {
	SetCreatedAt(createdAt time.Time) T
	SetUpdatedAt(updatedAt time.Time) T
	SetNillableDeletedAt(deletedAt *time.Time) T
}

type TimeMixinUpdater[T any] interface {
	SetUpdatedAt(updatedAt time.Time) T
	SetNillableDeletedAt(deletedAt *time.Time) T
}

func MapTimeMixinFromDB[T TimeMixinGetter](dbEntity T) models.ManagedModel {
	return models.ManagedModel{
		CreatedAt: dbEntity.GetCreatedAt().In(time.UTC),
		UpdatedAt: dbEntity.GetUpdatedAt().In(time.UTC),
		DeletedAt: convert.TimePtrIn(dbEntity.GetDeletedAt(), time.UTC),
	}
}

// truncatedNow returns the current time truncated to microsecond precision. This is useful, as:
// - ent when creating resources will return the in memory calculated data including the timestamp in host precision
// - PostgreSQL has microsecond precision
// - Linux has nanosecond precision
// - MacOS seem to have at most microsecond precision in go
//
// This means that any test that relies on CreatedAt or UpdatedAt comparisons will pass on macos, but will fail on CI.
func truncatedNow() time.Time {
	// PostgreSQL has microsecond precision, so let's truncate to that which makes
	// it easier to test and compare times.
	return clock.Now().Truncate(time.Microsecond)
}

type CadencedMixin struct {
	mixin.Schema
}

func (CadencedMixin) Fields() []ent.Field {
	return []ent.Field{
		field.Time("active_from").Immutable(),
		field.Time("active_to").Optional().Nillable(),
	}
}

// CustomerAddressMixin adds address fields to a customer, used by billing to snapshot addresses for invoices
type CustomerAddressMixin struct {
	ent.Schema
	FieldPrefix string
}

func (c CustomerAddressMixin) Fields() []ent.Field {
	return []ent.Field{
		// PII fields
		field.String(fmt.Sprintf("%s_address_country", c.FieldPrefix)).GoType(models.CountryCode("")).MinLen(2).MaxLen(2).Optional().Nillable(),
		field.String(fmt.Sprintf("%s_address_postal_code", c.FieldPrefix)).Optional().Nillable(),
		field.String(fmt.Sprintf("%s_address_state", c.FieldPrefix)).Optional().Nillable(),
		field.String(fmt.Sprintf("%s_address_city", c.FieldPrefix)).Optional().Nillable(),
		field.String(fmt.Sprintf("%s_address_line1", c.FieldPrefix)).Optional().Nillable(),
		field.String(fmt.Sprintf("%s_address_line2", c.FieldPrefix)).Optional().Nillable(),
		field.String(fmt.Sprintf("%s_address_phone_number", c.FieldPrefix)).Optional().Nillable(),
	}
}