-
Notifications
You must be signed in to change notification settings - Fork 11
/
search.go
394 lines (351 loc) · 13.4 KB
/
search.go
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/*
Copyright 2024 Blnk Finance Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blnk
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/sirupsen/logrus"
"github.com/typesense/typesense-go/typesense"
"github.com/typesense/typesense-go/typesense/api"
)
// TypesenseClient wraps the Typesense client and provides methods to interact with it.
type TypesenseClient struct {
Client *typesense.Client
}
// NotificationPayload represents the payload structure for notifications, containing the table and data.
type NotificationPayload struct {
Table string `json:"table"`
Data map[string]interface{} `json:"data"`
}
// NewTypesenseClient initializes and returns a new Typesense client instance.
func NewTypesenseClient(apiKey string, hosts []string) *TypesenseClient {
client := typesense.NewClient(
typesense.WithServer(hosts[0]),
typesense.WithAPIKey(apiKey),
typesense.WithConnectionTimeout(5*time.Second),
typesense.WithCircuitBreakerMaxRequests(50),
typesense.WithCircuitBreakerInterval(2*time.Minute),
typesense.WithCircuitBreakerTimeout(1*time.Minute),
)
return &TypesenseClient{Client: client}
}
// EnsureCollectionsExist ensures that all the necessary collections exist in the Typesense schema.
// If a collection doesn't exist, it will create the collection based on the latest schema.
func (t *TypesenseClient) EnsureCollectionsExist(ctx context.Context) error {
collections := []string{"ledgers", "balances", "transactions", "reconciliations", "identities"}
for _, c := range collections {
latestSchema := getLatestSchema(c)
if _, err := t.CreateCollection(ctx, latestSchema); err != nil {
return fmt.Errorf("failed to create collection %s: %w", c, err)
}
}
return nil
}
// CreateCollection creates a collection in Typesense based on the provided schema.
// If the collection already exists, it will return without error.
func (t *TypesenseClient) CreateCollection(ctx context.Context, schema *api.CollectionSchema) (*api.CollectionResponse, error) {
resp, err := t.Client.Collections().Create(ctx, schema)
if err != nil {
if strings.Contains(err.Error(), "already exists") {
return nil, nil
}
return nil, err
}
return resp, nil
}
// Search performs a search query on a specific collection with the provided search parameters.
func (t *TypesenseClient) Search(ctx context.Context, collection string, searchParams *api.SearchCollectionParams) (*api.SearchResult, error) {
return t.Client.Collection(collection).Documents().Search(ctx, searchParams)
}
// HandleNotification processes incoming notifications and updates Typesense collections based on the table and data.
// It ensures the required fields exist and upserts the data into Typesense.
func (t *TypesenseClient) HandleNotification(table string, data map[string]interface{}) error {
ctx := context.Background()
if err := t.EnsureCollectionsExist(ctx); err != nil {
logrus.Warningf("Failed to ensure collections exist: %v", err)
}
if metaData, ok := data["meta_data"]; ok {
jsonString, err := json.Marshal(metaData)
if err != nil {
return fmt.Errorf("failed to marshal meta_data: %w", err)
}
data["meta_data"] = string(jsonString)
}
latestSchema := getLatestSchema(table)
// Ensure all fields from the latest schema are present in the data.
for _, field := range latestSchema.Fields {
if _, ok := data[field.Name]; !ok {
data[field.Name] = getDefaultValue(field.Type)
}
}
// Handle time fields and convert them to Unix timestamps if necessary.
timeFields := []string{"created_at", "scheduled_for", "inflight_expiry_date", "inflight_expires_at", "completed_at", "started_at"}
for _, field := range timeFields {
if fieldValue, ok := data[field]; ok {
switch v := fieldValue.(type) {
case time.Time:
data[field] = v.Unix()
case int64:
// Time already in Unix format, no action needed
default:
// Set current time if value type is not recognized
data[field] = time.Now().Unix()
}
}
}
// Special handling for balances and ledgers collections
if table == "balances" || table == "ledgers" {
var idField string
if table == "balances" {
idField = "balance_id"
} else {
idField = "ledger_id"
}
if id, ok := data[idField].(string); ok && id != "" {
// Upsert the document in Typesense with the provided ID
data["id"] = id
_, err := t.Client.Collection(table).Documents().Upsert(ctx, data)
if err != nil {
return fmt.Errorf("failed to upsert document in Typesense: %w", err)
}
return nil
}
}
// Special handling for reconciliations and identities collections
if table == "reconciliations" || table == "identities" {
var idField string
if table == "reconciliations" {
idField = "reconciliation_id"
} else {
idField = "identity_id"
}
if id, ok := data[idField].(string); ok && id != "" {
// Upsert the document in Typesense with the provided ID
data["id"] = id
_, err := t.Client.Collection(table).Documents().Upsert(ctx, data)
if err != nil {
return fmt.Errorf("failed to upsert document in Typesense: %w", err)
}
return nil
}
}
// For other collections, perform a regular upsert.
_, err := t.Client.Collection(table).Documents().Upsert(ctx, data)
if err != nil {
return fmt.Errorf("failed to index document in Typesense: %w", err)
}
return nil
}
// MigrateTypeSenseSchema adds new fields from the latest schema to the existing collection schema in Typesense.
// This is useful when the schema has been updated, and new fields need to be added.
func (t *TypesenseClient) MigrateTypeSenseSchema(ctx context.Context, collectionName string) error {
collection := t.Client.Collection(collectionName)
currentSchemaResponse, err := collection.Retrieve(ctx)
if err != nil {
return fmt.Errorf("failed to retrieve current schema: %w", err)
}
currentSchema := &api.CollectionSchema{
Name: currentSchemaResponse.Name,
Fields: currentSchemaResponse.Fields,
}
latestSchema := getLatestSchema(collectionName)
// Compare the current schema with the latest schema and get any new fields.
newFields := compareSchemas(currentSchema, latestSchema)
// Add each new field to the collection.
for _, field := range newFields {
updateSchema := &api.CollectionUpdateSchema{
Fields: []api.Field{field},
}
_, err := collection.Update(ctx, updateSchema)
if err != nil {
return fmt.Errorf("failed to add field %s: %w", field.Name, err)
}
logrus.Infof("Added new field %s to collection %s", field.Name, collectionName)
}
return nil
}
// compareSchemas compares the old schema with the new schema and returns any new fields that are present in the new schema but not in the old one.
func compareSchemas(oldSchema, newSchema *api.CollectionSchema) []api.Field {
var newFields []api.Field
oldFieldMap := make(map[string]bool)
// Create a map of the old fields.
for _, field := range oldSchema.Fields {
oldFieldMap[field.Name] = true
}
// Identify new fields that are in the new schema but not in the old schema.
for _, field := range newSchema.Fields {
if !oldFieldMap[field.Name] {
newFields = append(newFields, field)
}
}
return newFields
}
// getDefaultValue returns the default value for a given field type in Typesense.
func getDefaultValue(fieldType string) interface{} {
switch fieldType {
case "string":
return ""
case "int32", "int64":
return int64(0)
case "float":
return float64(0)
case "bool":
return false
case "string[]":
return []string{}
default:
return nil
}
}
// getLatestSchema returns the latest schema for a given collection name. This function should be updated whenever the schema changes.
func getLatestSchema(collectionName string) *api.CollectionSchema {
switch collectionName {
case "ledgers":
return getLedgerSchema()
case "balances":
return getBalanceSchema()
case "transactions":
return getTransactionSchema()
case "reconciliations":
return getReconciliationSchema()
case "identities":
return getIdentitySchema()
default:
return nil
}
}
// getLedgerSchema returns the schema for the "ledgers" collection.
func getLedgerSchema() *api.CollectionSchema {
facet := true
sortBy := "created_at"
return &api.CollectionSchema{
Name: "ledgers",
Fields: []api.Field{
{Name: "ledger_id", Type: "string", Facet: &facet},
{Name: "name", Type: "string", Facet: &facet},
{Name: "created_at", Type: "int64", Facet: &facet},
{Name: "meta_data", Type: "string", Facet: &facet},
},
DefaultSortingField: &sortBy,
}
}
// getBalanceSchema returns the schema for the "balances" collection.
func getBalanceSchema() *api.CollectionSchema {
facet := true
sortBy := "created_at"
return &api.CollectionSchema{
Name: "balances",
Fields: []api.Field{
{Name: "balance", Type: "int64", Facet: &facet},
{Name: "version", Type: "int64", Facet: &facet},
{Name: "inflight_balance", Type: "int64", Facet: &facet},
{Name: "credit_balance", Type: "int64", Facet: &facet},
{Name: "inflight_credit_balance", Type: "int64", Facet: &facet},
{Name: "debit_balance", Type: "int64", Facet: &facet},
{Name: "inflight_debit_balance", Type: "int64", Facet: &facet},
{Name: "precision", Type: "float", Facet: &facet},
{Name: "ledger_id", Type: "string", Facet: &facet},
{Name: "identity_id", Type: "string", Facet: &facet},
{Name: "balance_id", Type: "string", Facet: &facet},
{Name: "indicator", Type: "string", Facet: &facet},
{Name: "currency", Type: "string", Facet: &facet},
{Name: "created_at", Type: "int64", Facet: &facet},
{Name: "inflight_expires_at", Type: "int64", Facet: &facet},
{Name: "meta_data", Type: "string", Facet: &facet},
},
DefaultSortingField: &sortBy,
}
}
// getTransactionSchema returns the schema for the "transactions" collection.
func getTransactionSchema() *api.CollectionSchema {
facet := true
sortBy := "created_at"
return &api.CollectionSchema{
Name: "transactions",
Fields: []api.Field{
{Name: "precise_amount", Type: "int64", Facet: &facet},
{Name: "amount", Type: "float", Facet: &facet},
{Name: "rate", Type: "float", Facet: &facet},
{Name: "precision", Type: "float", Facet: &facet},
{Name: "transaction_id", Type: "string", Facet: &facet},
{Name: "parent_transaction", Type: "string", Facet: &facet},
{Name: "source", Type: "string", Facet: &facet},
{Name: "destination", Type: "string", Facet: &facet},
{Name: "reference", Type: "string", Facet: &facet},
{Name: "currency", Type: "string", Facet: &facet},
{Name: "description", Type: "string", Facet: &facet},
{Name: "status", Type: "string", Facet: &facet},
{Name: "hash", Type: "string", Facet: &facet},
{Name: "allow_overdraft", Type: "bool", Facet: &facet},
{Name: "inflight", Type: "bool", Facet: &facet},
{Name: "sources", Type: "string[]", Facet: &facet},
{Name: "destinations", Type: "string[]", Facet: &facet},
{Name: "created_at", Type: "int64", Facet: &facet},
{Name: "scheduled_for", Type: "int64", Facet: &facet},
{Name: "inflight_expiry_date", Type: "int64", Facet: &facet},
{Name: "meta_data", Type: "string", Facet: &facet},
},
DefaultSortingField: &sortBy,
}
}
// getReconciliationSchema returns the schema for the "reconciliations" collection.
func getReconciliationSchema() *api.CollectionSchema {
facet := true
sortBy := "started_at"
return &api.CollectionSchema{
Name: "reconciliations",
Fields: []api.Field{
{Name: "reconciliation_id", Type: "string", Facet: &facet},
{Name: "upload_id", Type: "string", Facet: &facet},
{Name: "status", Type: "string", Facet: &facet},
{Name: "matched_transactions", Type: "int32", Facet: &facet},
{Name: "unmatched_transactions", Type: "int32", Facet: &facet},
{Name: "started_at", Type: "int64", Facet: &facet},
{Name: "completed_at", Type: "int64", Facet: &facet},
},
DefaultSortingField: &sortBy,
}
}
// getIdentitySchema returns the schema for the "identities" collection.
func getIdentitySchema() *api.CollectionSchema {
facet := true
sortBy := "created_at"
return &api.CollectionSchema{
Name: "identities",
Fields: []api.Field{
{Name: "identity_id", Type: "string", Facet: &facet},
{Name: "identity_type", Type: "string", Facet: &facet},
{Name: "organization_name", Type: "string", Facet: &facet},
{Name: "category", Type: "string", Facet: &facet},
{Name: "first_name", Type: "string", Facet: &facet},
{Name: "last_name", Type: "string", Facet: &facet},
{Name: "other_names", Type: "string", Facet: &facet},
{Name: "gender", Type: "string", Facet: &facet},
{Name: "email_address", Type: "string", Facet: &facet},
{Name: "phone_number", Type: "string", Facet: &facet},
{Name: "nationality", Type: "string", Facet: &facet},
{Name: "street", Type: "string", Facet: &facet},
{Name: "country", Type: "string", Facet: &facet},
{Name: "state", Type: "string", Facet: &facet},
{Name: "post_code", Type: "string", Facet: &facet},
{Name: "city", Type: "string", Facet: &facet},
{Name: "dob", Type: "int64", Facet: &facet},
{Name: "created_at", Type: "int64", Facet: &facet},
{Name: "meta_data", Type: "string", Facet: &facet},
},
DefaultSortingField: &sortBy,
}
}