-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindexer_service.go
More file actions
1563 lines (1356 loc) · 51.3 KB
/
indexer_service.go
File metadata and controls
1563 lines (1356 loc) · 51.3 KB
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright The Linux Foundation and each contributor to LFX.
// SPDX-License-Identifier: MIT
// Package services provides domain services for the LFX indexer application.
package services
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/linuxfoundation/lfx-v2-indexer-service/internal/domain/contracts"
"github.com/linuxfoundation/lfx-v2-indexer-service/internal/enrichers"
"github.com/linuxfoundation/lfx-v2-indexer-service/pkg/constants"
"github.com/linuxfoundation/lfx-v2-indexer-service/pkg/logging"
"github.com/linuxfoundation/lfx-v2-indexer-service/pkg/types"
)
// IndexerService handles transaction processing and health checking
type IndexerService struct {
// Core dependencies
storageRepo contracts.StorageRepository
messagingRepo contracts.MessagingRepository
logger *slog.Logger
// Enrichment registry for extensible object-specific enrichment
enricherRegistry *enrichers.Registry
// Configuration
timeout time.Duration
// Health check caching
mu sync.RWMutex
cacheDuration time.Duration
lastReadiness *cachedResult
lastLiveness *cachedResult
lastHealth *cachedResult
}
// HealthStatus represents the overall health status of the service
type HealthStatus struct {
Status string `json:"status"` // "healthy", "degraded", "unhealthy"
Timestamp time.Time `json:"timestamp"`
Duration time.Duration `json:"duration"`
Checks map[string]Check `json:"checks"`
ErrorCount int `json:"error_count,omitempty"`
}
// Check represents the health status of an individual component
type Check struct {
Status string `json:"status"`
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
// cachedResult holds a cached health status with timestamp
type cachedResult struct {
status *HealthStatus
timestamp time.Time
}
// NewIndexerService creates a new indexer service
func NewIndexerService(
storageRepo contracts.StorageRepository,
messagingRepo contracts.MessagingRepository,
logger *slog.Logger,
) *IndexerService {
// Initialize enricher registry with project enricher
registry := enrichers.NewRegistry()
for _, enricher := range []enrichers.Enricher{
enrichers.NewProjectEnricher(),
enrichers.NewProjectSettingsEnricher(),
enrichers.NewCommitteeEnricher(),
enrichers.NewCommitteeSettingsEnricher(),
enrichers.NewCommitteeMemberEnricher(),
enrichers.NewMeetingEnricher(),
enrichers.NewMeetingSettingsEnricher(),
enrichers.NewMeetingRegistrantEnricher(),
enrichers.NewMeetingRSVPEnricher(),
enrichers.NewMeetingAttachmentEnricher(),
enrichers.NewPastMeetingEnricher(),
enrichers.NewPastMeetingAttachmentEnricher(),
enrichers.NewPastMeetingParticipantEnricher(),
enrichers.NewPastMeetingRecordingEnricher(),
enrichers.NewPastMeetingTranscriptEnricher(),
enrichers.NewPastMeetingSummaryEnricher(),
enrichers.NewGroupsIOServiceEnricher(),
enrichers.NewGroupsIOServiceSettingsEnricher(),
enrichers.NewGroupsIOMailingListEnricher(),
enrichers.NewGroupsIOMailingListSettingsEnricher(),
enrichers.NewGroupsIOMemberEnricher(),
// V1 Meeting enrichers
enrichers.NewV1MeetingEnricher(),
enrichers.NewV1PastMeetingEnricher(),
enrichers.NewV1MeetingRegistrantEnricher(),
enrichers.NewV1MeetingRSVPEnricher(),
enrichers.NewV1PastMeetingParticipantEnricher(),
enrichers.NewV1PastMeetingRecordingEnricher(),
enrichers.NewV1PastMeetingTranscriptEnricher(),
enrichers.NewV1PastMeetingSummaryEnricher(),
} {
registry.Register(enricher)
}
return &IndexerService{
storageRepo: storageRepo,
messagingRepo: messagingRepo,
logger: logging.WithComponent(logger, constants.Component),
enricherRegistry: registry,
timeout: constants.HealthCheckTimeout,
cacheDuration: constants.CacheDuration,
}
}
// =================
// TRANSACTION ACTION HELPERS
// =================
// isCreateAction returns true if this is a create action (both V1 and V2)
func (s *IndexerService) isCreateAction(transaction *contracts.LFXTransaction) bool {
return transaction.Action == constants.ActionCreate || transaction.Action == constants.ActionCreated
}
// isUpdateAction returns true if this is an update action (both V1 and V2)
func (s *IndexerService) isUpdateAction(transaction *contracts.LFXTransaction) bool {
return transaction.Action == constants.ActionUpdate || transaction.Action == constants.ActionUpdated
}
// isDeleteAction returns true if this is a delete action (both V1 and V2)
func (s *IndexerService) isDeleteAction(transaction *contracts.LFXTransaction) bool {
return transaction.Action == constants.ActionDelete || transaction.Action == constants.ActionDeleted
}
// =================
// TRANSACTION CREATION METHODS
// =================
// CreateTransactionFromMessage creates a transaction from message data
func (s *IndexerService) CreateTransactionFromMessage(messageData map[string]any, objectType string, isV1 bool) (*contracts.LFXTransaction, error) {
logger := s.logger
// Extract action as string first, then convert to MessageAction
actionStr, ok := messageData["action"].(string)
if !ok || actionStr == "" {
logging.LogError(logger, "Failed to create transaction: missing action",
fmt.Errorf("missing or invalid action in message data"),
"object_type", objectType,
"is_v1", isV1)
return nil, fmt.Errorf("missing or invalid action in message data")
}
action := constants.MessageAction(actionStr)
logger.Debug("Creating transaction from message",
"action", action,
"object_type", objectType,
"is_v1", isV1)
// Create transaction directly without constructors
transaction := &contracts.LFXTransaction{
Action: action,
ObjectType: objectType,
Data: messageData["data"],
Headers: make(map[string]string),
Timestamp: time.Now(),
IsV1: isV1,
}
// Set V1 data if this is a V1 transaction
if isV1 {
s.setV1Data(transaction, messageData)
}
// Parse indexing_config if present (for resource indexing)
if indexingConfigData, ok := messageData["indexing_config"].(map[string]any); ok {
// Get transaction data for template expansion
var transactionData map[string]any
if dataMap, ok := messageData["data"].(map[string]any); ok {
transactionData = dataMap
} else {
transactionData = make(map[string]any)
}
indexingConfig, err := s.parseIndexingConfig(indexingConfigData, transactionData)
if err != nil {
return nil, fmt.Errorf("failed to parse indexing_config: %w", err)
}
transaction.IndexingConfig = indexingConfig
}
// Convert headers
headerCount := 0
if headers, ok := messageData["headers"].(map[string]interface{}); ok {
for k, v := range headers {
if str, ok := v.(string); ok {
transaction.Headers[k] = str
headerCount++
}
}
}
if tags, ok := messageData["tags"].([]any); ok {
// Only add tags that are strings. Ignore other types instead of failing.
for _, tag := range tags {
if tagStr, ok := tag.(string); ok {
transaction.Tags = append(transaction.Tags, tagStr)
}
}
}
logger.Info("Transaction created successfully",
"transaction_id", s.generateTransactionID(transaction),
"action", action,
"object_type", objectType,
"is_v1", isV1,
"tags", transaction.Tags,
"header_count", headerCount)
return transaction, nil
}
// setV1Data sets V1-specific data on the transaction
func (s *IndexerService) setV1Data(transaction *contracts.LFXTransaction, messageData map[string]any) {
if v1Data, ok := messageData["v1_data"].(map[string]any); ok {
transaction.V1Data = v1Data
s.logger.Debug("V1 data set on transaction",
"object_type", transaction.ObjectType,
"v1_data_fields", len(v1Data))
} else {
s.logger.Debug("No V1 data found in message",
"object_type", transaction.ObjectType)
}
}
// ValidateTransactionData validates transaction data
func (s *IndexerService) ValidateTransactionData(transaction *contracts.LFXTransaction) error {
logger := s.logger
transactionID := s.generateTransactionID(transaction)
logger.Debug("Validating transaction data",
"transaction_id", transactionID,
"action", transaction.Action,
"object_type", transaction.ObjectType)
if transaction.Data == nil {
err := fmt.Errorf("data field is required")
logging.LogError(logger, "Transaction data validation failed: missing data", err,
"transaction_id", transactionID,
"validation_step", "data_presence",
"action", transaction.Action,
"object_type", transaction.ObjectType)
return err
}
// Try to decode the data
if err := s.decodeTransactionData(transaction); err != nil {
logging.LogError(logger, "Transaction data validation failed: failed to decode data", err,
"transaction_id", transactionID,
"validation_step", "data_decode",
"action", transaction.Action,
"object_type", transaction.ObjectType)
return err
}
switch {
case s.isCreateAction(transaction) || s.isUpdateAction(transaction):
if _, ok := transaction.Data.(map[string]any); !ok {
err := fmt.Errorf("data must be an object for %s actions", transaction.Action)
logging.LogError(logger, "Transaction data validation failed: invalid data type", err,
"transaction_id", transactionID,
"validation_step", "data_type",
"action", transaction.Action,
"object_type", transaction.ObjectType,
"transaction_data", transaction.Data,
"expected_type", "object")
return err
}
logger.Debug("Transaction data validation passed",
"transaction_id", transactionID,
"data_type", "object")
case s.isDeleteAction(transaction):
if _, ok := transaction.Data.(string); !ok {
err := fmt.Errorf("data must be a string (object ID) for %s actions", transaction.Action)
logging.LogError(logger, "Transaction data validation failed: invalid data type", err,
"transaction_id", transactionID,
"validation_step", "data_type",
"action", transaction.Action,
"object_type", transaction.ObjectType,
"expected_type", "string")
return err
}
logger.Debug("Transaction data validation passed",
"transaction_id", transactionID,
"data_type", "string")
}
logger.Debug("Transaction data validation completed successfully",
"transaction_id", transactionID)
return nil
}
// decodeTransactionData decodes the transaction data
func (s *IndexerService) decodeTransactionData(transaction *contracts.LFXTransaction) error {
logger := s.logger
transactionID := s.generateTransactionID(transaction)
// Decode the data if it is base64 encoded
if data, ok := transaction.Data.(string); ok {
decodedData, err := base64.StdEncoding.DecodeString(data)
if err == nil {
// If there is no error, then we can unmarshal the data.
// Otherwise, it means the data wasn't base64 encoded and therefore
// we can just use the data as is.
switch {
case s.isCreateAction(transaction) || s.isUpdateAction(transaction):
var data map[string]any
if err := json.Unmarshal(decodedData, &data); err != nil {
logging.LogError(logger, "Failed to unmarshal JSON", err,
"validation_step", "json_unmarshal",
"transaction_data", transaction.Data,
"transaction_id", transactionID)
return err
}
transaction.Data = data
case s.isDeleteAction(transaction):
transaction.Data = string(decodedData)
}
}
}
return nil
}
// ValidateTransactionHeaders validates transaction headers
func (s *IndexerService) ValidateTransactionHeaders(transaction *contracts.LFXTransaction) error {
logger := s.logger
transactionID := s.generateTransactionID(transaction)
logger.Debug("Validating transaction headers",
"transaction_id", transactionID,
"is_v1", transaction.IsV1,
"header_count", len(transaction.Headers))
if transaction.Headers == nil {
err := fmt.Errorf("headers field is required")
logging.LogError(logger, "Transaction header validation failed: missing headers", err,
"transaction_id", transactionID,
"validation_step", "headers_presence",
"is_v1", transaction.IsV1)
return err
}
// Dispatch to version-specific validation
var err error
if transaction.IsV1 {
err = s.validateV1Headers(transaction, transactionID)
} else {
err = s.validateV2Headers(transaction, transactionID)
}
if err != nil {
return err
}
logger.Debug("Transaction header validation completed successfully",
"transaction_id", transactionID,
"is_v1", transaction.IsV1)
return nil
}
// validateV1Headers validates headers for V1 transactions
func (s *IndexerService) validateV1Headers(transaction *contracts.LFXTransaction, transactionID string) error {
logger := s.logger
// V1 transactions don't require authorization headers
// They use X-Username and X-Email headers instead
logger.Debug("Validating V1 headers",
"transaction_id", transactionID,
"has_x_username", transaction.Headers[constants.HeaderXUsername] != "",
"has_x_email", transaction.Headers[constants.HeaderXEmail] != "")
// Log if V1 headers are present (for debugging)
if username := transaction.Headers[constants.HeaderXUsername]; username != "" {
logger.Debug("V1 username header found",
"transaction_id", transactionID,
"username", username)
}
return nil
}
// validateV2Headers validates headers for V2 transactions
func (s *IndexerService) validateV2Headers(transaction *contracts.LFXTransaction, transactionID string) error {
logger := s.logger
// V2 transactions require authorization header
if auth, exists := transaction.Headers[constants.AuthorizationHeader]; !exists || auth == "" {
err := fmt.Errorf("authorization header is required for V2 transactions")
logging.LogError(logger, "V2 header validation failed: missing authorization", err,
"transaction_id", transactionID,
"validation_step", "authorization_header",
"has_auth_header", exists)
return err
}
logger.Debug("V2 authorization header validated",
"transaction_id", transactionID)
return nil
}
// ValidateObjectType validates object type using the enricher registry
func (s *IndexerService) ValidateObjectType(transaction *contracts.LFXTransaction) error {
logger := s.logger
transactionID := s.generateTransactionID(transaction)
logger.Debug("Validating object type",
"transaction_id", transactionID,
"object_type", transaction.ObjectType)
// Check if we have an enricher registered for this object type
enricher, exists := s.enricherRegistry.GetEnricher(transaction.ObjectType)
if !exists {
err := fmt.Errorf("no enricher found for object type: %s", transaction.ObjectType)
logging.LogError(logger, "Object type validation failed: no enricher found", err,
"transaction_id", transactionID,
"validation_step", "enricher_lookup",
"object_type", transaction.ObjectType)
return err
}
logger.Debug("Object type validation passed",
"transaction_id", transactionID,
"object_type", transaction.ObjectType,
"enricher_type", fmt.Sprintf("%T", enricher))
return nil
}
// ValidateTransactionAction validates the transaction action based on transaction version
func (s *IndexerService) ValidateTransactionAction(transaction *contracts.LFXTransaction) error {
logger := s.logger
transactionID := s.generateTransactionID(transaction)
logger.Debug("Validating transaction action",
"transaction_id", transactionID,
"action", transaction.Action,
"is_v1", transaction.IsV1)
// Dispatch to version-specific validation
var err error
if transaction.IsV1 {
err = s.validateV1Action(transaction, transactionID)
} else {
err = s.validateV2Action(transaction, transactionID)
}
if err != nil {
return err
}
logger.Debug("Transaction action validation completed successfully",
"transaction_id", transactionID,
"action", transaction.Action,
"is_v1", transaction.IsV1)
return nil
}
// validateV1Action validates actions for V1 transactions
func (s *IndexerService) validateV1Action(transaction *contracts.LFXTransaction, transactionID string) error {
logger := s.logger
// V1 transactions are sent by the v1-sync-helper service
// These use present-tense actions to match the original V1 API format
// Subject pattern: lfx.v1.index.{object_type}
logger.Debug("Validating V1 action",
"transaction_id", transactionID,
"action", transaction.Action)
switch transaction.Action {
case constants.ActionCreate, constants.ActionUpdate, constants.ActionDelete:
logger.Debug("V1 action validation passed",
"transaction_id", transactionID,
"action", transaction.Action)
return nil
default:
err := fmt.Errorf("invalid V1 transaction action: %s", transaction.Action)
logging.LogError(logger, "V1 action validation failed", err,
"transaction_id", transactionID,
"validation_step", "action_check",
"action", transaction.Action,
"valid_actions", []constants.MessageAction{constants.ActionCreate, constants.ActionUpdate, constants.ActionDelete})
return err
}
}
// validateV2Action validates actions for V2 transactions
func (s *IndexerService) validateV2Action(transaction *contracts.LFXTransaction, transactionID string) error {
logger := s.logger
// V2 transactions are sent by regular LFX services
// These use past-tense actions to indicate completed operations
// Subject pattern: lfx.index.{object_type}
logger.Debug("Validating V2 action",
"transaction_id", transactionID,
"action", transaction.Action)
switch transaction.Action {
case constants.ActionCreated, constants.ActionUpdated, constants.ActionDeleted:
logger.Debug("V2 action validation passed",
"transaction_id", transactionID,
"action", transaction.Action)
return nil
default:
err := fmt.Errorf("invalid V2 transaction action: %s", transaction.Action)
logging.LogError(logger, "V2 action validation failed", err,
"transaction_id", transactionID,
"validation_step", "action_check",
"action", transaction.Action,
"valid_actions", []constants.MessageAction{constants.ActionCreated, constants.ActionUpdated, constants.ActionDeleted})
return err
}
}
// GetCanonicalAction returns the canonical (past-tense) action for indexing
func (s *IndexerService) GetCanonicalAction(transaction *contracts.LFXTransaction) constants.MessageAction {
switch transaction.Action {
case constants.ActionCreate, constants.ActionCreated:
return constants.ActionCreated
case constants.ActionUpdate, constants.ActionUpdated:
return constants.ActionUpdated
case constants.ActionDelete, constants.ActionDeleted:
return constants.ActionDeleted
default:
return transaction.Action
}
}
// ExtractObjectID extracts object ID from transaction
func (s *IndexerService) ExtractObjectID(transaction *contracts.LFXTransaction) (string, error) {
if s.isDeleteAction(transaction) {
return transaction.ParsedObjectID, nil
}
if transaction.ParsedData == nil {
return "", fmt.Errorf("parsed data is nil")
}
if id, ok := transaction.ParsedData["id"].(string); ok && id != "" {
return id, nil
}
return "", fmt.Errorf("missing or invalid 'id' field in data")
}
// =================
// TRANSACTION PROCESSING METHODS
// =================
// EnrichTransaction enriches a transaction with additional data and validation
func (s *IndexerService) EnrichTransaction(ctx context.Context, transaction *contracts.LFXTransaction) error {
logger := logging.FromContext(ctx, s.logger)
transactionID := s.generateTransactionID(transaction)
logger.Info("Starting transaction enrichment",
"transaction_id", transactionID,
"action", transaction.Action,
"object_type", transaction.ObjectType,
"is_v1", transaction.IsV1)
// Validate transaction action
if err := s.ValidateTransactionAction(transaction); err != nil {
logging.LogError(logger, "Transaction enrichment failed: action validation", err,
"transaction_id", transactionID,
"step", "validate_action")
return fmt.Errorf("%s: %w", constants.ErrInvalidAction, err)
}
logger.Debug("Action validation completed", "transaction_id", transactionID)
if transaction.IndexingConfig == nil {
// Validate object type using enricher registry
if err := s.ValidateObjectType(transaction); err != nil {
logging.LogError(logger, "Transaction enrichment failed: object type validation", err,
"transaction_id", transactionID,
"step", "validate_object_type")
return fmt.Errorf("%s: %w", constants.ErrInvalidObjectType, err)
}
logger.Debug("Object type validation completed", "transaction_id", transactionID)
}
// Validate transaction data
if err := s.ValidateTransactionData(transaction); err != nil {
logging.LogError(logger, "Transaction enrichment failed: data validation", err,
"transaction_id", transactionID,
"step", "validate_data")
return fmt.Errorf("invalid transaction data: %w", err)
}
logger.Debug("Data validation completed", "transaction_id", transactionID)
// Validate transaction headers
if err := s.ValidateTransactionHeaders(transaction); err != nil {
logging.LogError(logger, "Transaction enrichment failed: header validation", err,
"transaction_id", transactionID,
"step", "validate_headers")
return fmt.Errorf("invalid transaction headers: %w", err)
}
logger.Debug("Header validation completed", "transaction_id", transactionID)
// Parse data based on action
if err := s.parseTransactionData(transaction); err != nil {
logging.LogError(logger, "Transaction enrichment failed: data parsing", err,
"transaction_id", transactionID,
"step", "parse_data")
return fmt.Errorf("%s: %w", constants.ErrParseTransaction, err)
}
logger.Debug("Data parsing completed", "transaction_id", transactionID)
// Parse principals based on transaction version
principals, err := s.parsePrincipals(ctx, transaction)
if err != nil {
logging.LogError(logger, "Transaction enrichment failed: principal parsing", err,
"transaction_id", transactionID,
"step", "parse_principals")
return fmt.Errorf("failed to parse principals: %w", err)
}
transaction.ParsedPrincipals = principals
logger.Debug("Principal parsing completed",
"transaction_id", transactionID,
"principal_count", len(principals))
logger.Info("Transaction enrichment completed successfully",
"transaction_id", transactionID,
"principal_count", len(principals))
return nil
}
// GenerateTransactionBody creates a transaction body for indexing
func (s *IndexerService) GenerateTransactionBody(ctx context.Context, transaction *contracts.LFXTransaction) (*contracts.TransactionBody, error) {
logger := logging.FromContext(ctx, s.logger)
transactionID := s.generateTransactionID(transaction)
logger.Debug("Generating transaction body",
"transaction_id", transactionID,
"object_type", transaction.ObjectType,
"action", transaction.Action)
body := &contracts.TransactionBody{
ObjectType: transaction.ObjectType,
V1Data: transaction.V1Data,
Tags: transaction.Tags,
}
// Set latest flag
latest := true
body.Latest = &latest
// Set fields based on action
canonicalAction := s.GetCanonicalAction(transaction)
logger.Debug("Using canonical action",
"transaction_id", transactionID,
"original_action", transaction.Action,
"canonical_action", canonicalAction)
switch canonicalAction {
case constants.ActionCreated:
body.CreatedAt = &transaction.Timestamp
body.UpdatedAt = body.CreatedAt // For search sorting
s.setPrincipalFields(body, transaction.ParsedPrincipals, constants.ActionCreated)
logger.Debug("Created action body prepared",
"transaction_id", transactionID,
"principal_count", len(transaction.ParsedPrincipals))
case constants.ActionUpdated:
body.UpdatedAt = &transaction.Timestamp
s.setPrincipalFields(body, transaction.ParsedPrincipals, constants.ActionUpdated)
logger.Debug("Updated action body prepared",
"transaction_id", transactionID,
"principal_count", len(transaction.ParsedPrincipals))
case constants.ActionDeleted:
body.DeletedAt = &transaction.Timestamp
s.setPrincipalFields(body, transaction.ParsedPrincipals, constants.ActionDeleted)
body.ObjectID = transaction.ParsedObjectID
body.ObjectRef = transaction.ObjectType + ":" + transaction.ParsedObjectID
logger.Debug("Deleted action body prepared",
"transaction_id", transactionID,
"object_id", body.ObjectID,
"object_ref", body.ObjectRef,
"principal_count", len(transaction.ParsedPrincipals))
// Early return for delete transactions (no enrichment needed)
logger.Debug("Transaction body generation completed (delete action)", "transaction_id", transactionID)
return body, nil
default:
err := fmt.Errorf("unsupported action: %s", canonicalAction)
logging.LogError(logger, "Unsupported canonical action", err,
"transaction_id", transactionID,
"canonical_action", canonicalAction,
"original_action", transaction.Action)
return nil, err
}
// Enrich data for create/update actions
if err := s.enrichTransactionData(body, transaction); err != nil {
logging.LogError(logger, "Failed to enrich transaction data during body generation", err,
"transaction_id", transactionID)
return nil, fmt.Errorf("failed to enrich transaction data: %w", err)
}
logger.Debug("Transaction data enrichment completed", "transaction_id", transactionID)
// Set object reference
body.ObjectRef = transaction.ObjectType + ":" + body.ObjectID
logger.Debug("Transaction body generation completed",
"transaction_id", transactionID,
"object_ref", body.ObjectRef)
return body, nil
}
// ProcessTransaction processes a complete transaction
func (s *IndexerService) ProcessTransaction(ctx context.Context, transaction *contracts.LFXTransaction, index string) (*contracts.ProcessingResult, error) {
logger := logging.FromContext(ctx, s.logger)
transactionID := s.generateTransactionID(transaction)
result := &contracts.ProcessingResult{
ProcessedAt: time.Now(),
MessageID: s.generateMessageID(transaction),
}
logger.Info("Processing transaction",
"transaction_id", transactionID,
"action", transaction.Action,
"object_type", transaction.ObjectType,
"is_v1", transaction.IsV1,
"index", index)
// Enrich the transaction
if err := s.EnrichTransaction(ctx, transaction); err != nil {
logging.LogError(logger, "Failed to enrich transaction", err,
"transaction_id", transactionID,
"step", "enrichment")
result.Error = err
result.Success = false
return result, err
}
logger.Debug("Transaction enrichment completed", "transaction_id", transactionID)
// Generate transaction body
body, err := s.GenerateTransactionBody(ctx, transaction)
if err != nil {
logging.LogError(logger, "Failed to generate transaction body", err,
"transaction_id", transactionID,
"step", "body_generation")
result.Error = err
result.Success = false
return result, err
}
logger.Debug("Transaction body generated",
"transaction_id", transactionID,
"object_id", body.ObjectID,
"object_ref", body.ObjectRef)
// Convert body to JSON for indexing
bodyBytes, err := json.Marshal(body)
if err != nil {
err = fmt.Errorf("failed to marshal body: %w", err)
logging.LogError(logger, "Failed to marshal transaction body", err,
"transaction_id", transactionID,
"step", "json_marshaling")
result.Error = err
result.Success = false
return result, err
}
logger.Debug("Transaction body marshaled",
"transaction_id", transactionID,
"body_size_bytes", len(bodyBytes))
// Index the transaction using storage repository
err = s.storageRepo.Index(ctx, index, body.ObjectRef, bytes.NewReader(bodyBytes))
if err != nil {
logging.LogError(logger, "Failed to index transaction", err,
"transaction_id", transactionID,
"step", "indexing",
"index", index,
"object_ref", body.ObjectRef)
result.Error = err
result.Success = false
result.IndexSuccess = false
return result, err
}
logger.Debug("Transaction indexed successfully",
"transaction_id", transactionID,
"object_ref", body.ObjectRef)
// Success
result.Success = true
result.IndexSuccess = true
result.DocumentID = body.ObjectRef
logger.Info("Transaction processing completed successfully",
"transaction_id", transactionID,
"object_ref", body.ObjectRef)
// Publish post-indexing event. Non-blocking — failure is logged but does not
// affect the result of the indexing operation itself.
s.publishIndexingEvent(ctx, body, s.GetCanonicalAction(transaction))
return result, nil
}
// publishIndexingEvent publishes a domain event to NATS after a successful OpenSearch write.
// Failures are non-blocking: the error is logged and the caller continues normally.
// Subject format: lfx.{object_type}.{action} (e.g., "lfx.project.created").
func (s *IndexerService) publishIndexingEvent(ctx context.Context, body *contracts.TransactionBody, canonicalAction constants.MessageAction) {
logger := logging.FromContext(ctx, s.logger)
event := &contracts.IndexingEvent{
DocumentID: body.ObjectRef,
ObjectID: body.ObjectID,
ObjectType: body.ObjectType,
Action: canonicalAction,
Body: body,
Timestamp: time.Now().UTC(),
}
eventBytes, err := json.Marshal(event)
if err != nil {
logging.LogError(logger, "Failed to marshal indexing event — skipping publish", err,
"document_id", body.ObjectRef,
"action", canonicalAction,
"object_type", body.ObjectType)
return
}
subject := constants.BuildEventSubject(body.ObjectType, canonicalAction)
if err := s.messagingRepo.Publish(ctx, subject, eventBytes); err != nil {
logging.LogError(logger, "Failed to publish indexing event — index write already succeeded", err,
"subject", subject,
"document_id", body.ObjectRef,
"action", canonicalAction,
"object_type", body.ObjectType)
return
}
logger.Info("Indexing event published",
"subject", subject,
"document_id", body.ObjectRef,
"action", canonicalAction,
"object_type", body.ObjectType)
}
// =================
// HEALTH CHECK METHODS
// =================
// CheckReadiness performs readiness checks with simplified caching
func (s *IndexerService) CheckReadiness(ctx context.Context) *HealthStatus {
logger := s.logger
// Simple inline cache check
s.mu.RLock()
if s.lastReadiness != nil && time.Since(s.lastReadiness.timestamp) < s.cacheDuration {
cached := s.lastReadiness.status
s.mu.RUnlock()
logger.Debug("Health readiness check served from cache")
return cached
}
s.mu.RUnlock()
logger.Debug("Health readiness check started")
// Perform actual health check
status := s.performHealthCheck(ctx)
// Simple inline cache update
s.mu.Lock()
s.lastReadiness = &cachedResult{status: status, timestamp: time.Now()}
s.mu.Unlock()
logger.Info("Health readiness check completed",
"status", status.Status,
"error_count", status.ErrorCount,
"duration", status.Duration)
return status
}
// CheckLiveness performs liveness checks with simplified caching
func (s *IndexerService) CheckLiveness(ctx context.Context) *HealthStatus {
s.logger.DebugContext(ctx, "Liveness check initiated")
// Simple inline cache check
s.mu.RLock()
if s.lastLiveness != nil && time.Since(s.lastLiveness.timestamp) < s.cacheDuration {
cached := s.lastLiveness.status
s.mu.RUnlock()
s.logger.DebugContext(ctx, "Liveness check completed using cache", "status", cached.Status)
return cached
}
s.mu.RUnlock()
// Liveness is simpler - just check if the service itself is responsive
status := &HealthStatus{
Status: constants.StatusHealthy,
Timestamp: time.Now(),
Duration: 0,
Checks: map[string]Check{
constants.ComponentService: {
Status: constants.StatusHealthy,
Timestamp: time.Now(),
Duration: 0,
},
},
}
// Simple inline cache update
s.mu.Lock()
s.lastLiveness = &cachedResult{status: status, timestamp: time.Now()}
s.mu.Unlock()
return status
}
// CheckHealth performs comprehensive health checks with simplified caching
func (s *IndexerService) CheckHealth(ctx context.Context) *HealthStatus {
// Simple inline cache check
s.mu.RLock()
if s.lastHealth != nil && time.Since(s.lastHealth.timestamp) < s.cacheDuration {
cached := s.lastHealth.status
s.mu.RUnlock()
return cached
}
s.mu.RUnlock()
// Health check can be more lenient than readiness
status := s.performHealthCheck(ctx)
// For general health, we might accept degraded state as "healthy"
if status.Status == constants.StatusDegraded {
status.Status = constants.StatusHealthy // Accept degraded for general health
}
// Simple inline cache update
s.mu.Lock()
s.lastHealth = &cachedResult{status: status, timestamp: time.Now()}
s.mu.Unlock()
return status
}
// =================
// HELPER METHODS
// =================
// performHealthCheck does the actual health checking logic
func (s *IndexerService) performHealthCheck(ctx context.Context) *HealthStatus {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
status := &HealthStatus{
Timestamp: time.Now(),
Checks: make(map[string]Check),
}
var wg sync.WaitGroup
var mu sync.Mutex
// Check storage (OpenSearch)
wg.Add(1)
go func() {
defer wg.Done()
start := time.Now()
err := s.storageRepo.HealthCheck(ctx)
check := Check{
Duration: time.Since(start),
Timestamp: start,
}
if err != nil {
check.Status = constants.StatusUnhealthy
check.Error = err.Error()
mu.Lock()
status.ErrorCount++
mu.Unlock()
} else {
check.Status = constants.StatusHealthy
}
mu.Lock()
status.Checks[constants.ComponentOpenSearch] = check
mu.Unlock()
}()
// Check messaging (NATS + Auth)
wg.Add(1)
go func() {