File size: 10,313 Bytes
83a59ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package services

import (
	"context"
	"fmt"
	"sync"
	"time"

	"github.com/NdoleStudio/httpsms/pkg/entities"
	"github.com/NdoleStudio/httpsms/pkg/repositories"
	"github.com/NdoleStudio/httpsms/pkg/telemetry"
	"github.com/NdoleStudio/stacktrace"
	"github.com/dgraph-io/ristretto/v2"
	"github.com/google/uuid"
)

// contactMapCacheTTL bounds cross-instance staleness because invalidation is process-local.
const (
	contactMapCacheTTL               = 5 * time.Minute
	contactGenerationCleanupInterval = time.Hour
)

// ContactCacheEntry stores a contact together with its user's cache generation.
type ContactCacheEntry struct {
	contact    *entities.Contact
	generation uint64
}

type contactGeneration struct {
	value      uint64
	lastAccess time.Time
}

// ContactService owns contact CRUD and phone-number contact lookups.
type ContactService struct {
	service
	logger                telemetry.Logger
	tracer                telemetry.Tracer
	repository            repositories.ContactRepository
	cache                 *ristretto.Cache[string, ContactCacheEntry]
	generationMu          sync.Mutex
	generations           map[entities.UserID]contactGeneration
	nextGeneration        uint64
	lastGenerationCleanup time.Time
}

// NewContactService creates a new ContactService.
func NewContactService(
	logger telemetry.Logger,
	tracer telemetry.Tracer,
	repository repositories.ContactRepository,
	contactCache *ristretto.Cache[string, ContactCacheEntry],
) (s *ContactService) {
	return &ContactService{
		logger:      logger.WithService(fmt.Sprintf("%T", s)),
		tracer:      tracer,
		repository:  repository,
		cache:       contactCache,
		generations: make(map[entities.UserID]contactGeneration),
	}
}

func (service *ContactService) cacheKey(userID entities.UserID, phoneNumber string) string {
	return fmt.Sprintf("%s|%s", userID, phoneNumber)
}

func (service *ContactService) generation(userID entities.UserID) uint64 {
	now := time.Now()
	service.generationMu.Lock()
	defer service.generationMu.Unlock()

	service.expireGenerationsLocked(now)
	if generation, ok := service.generations[userID]; ok {
		generation.lastAccess = now
		service.generations[userID] = generation
		return generation.value
	}

	service.nextGeneration++
	service.generations[userID] = contactGeneration{
		value:      service.nextGeneration,
		lastAccess: now,
	}
	return service.nextGeneration
}

func (service *ContactService) advanceGeneration(userID entities.UserID) {
	now := time.Now()
	service.generationMu.Lock()
	defer service.generationMu.Unlock()

	service.expireGenerationsLocked(now)
	service.nextGeneration++
	service.generations[userID] = contactGeneration{
		value:      service.nextGeneration,
		lastAccess: now,
	}
}

func (service *ContactService) expireGenerations(now time.Time) {
	service.generationMu.Lock()
	defer service.generationMu.Unlock()
	service.expireGenerationsLocked(now)
}

func (service *ContactService) expireGenerationsLocked(now time.Time) {
	if !service.lastGenerationCleanup.IsZero() &&
		now.Sub(service.lastGenerationCleanup) < contactGenerationCleanupInterval {
		return
	}
	for userID, generation := range service.generations {
		if now.Sub(generation.lastAccess) >= contactMapCacheTTL {
			delete(service.generations, userID)
		}
	}
	service.lastGenerationCleanup = now
}

// CreateMany persists one or many contacts in a single batch.
func (service *ContactService) CreateMany(ctx context.Context, userID entities.UserID, contacts []*entities.Contact) error {
	ctx, span := service.tracer.Start(ctx)
	defer span.End()

	if err := service.repository.Store(ctx, contacts); err != nil {
		return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot store [%d] contacts for user [%s]", len(contacts), userID))
	}

	phoneNumbers := make([]string, 0)
	for _, contact := range contacts {
		phoneNumbers = append(phoneNumbers, contact.PhoneNumbers...)
	}
	service.invalidate(userID, phoneNumbers)
	return nil
}

// Get returns a single contact scoped to the user.
func (service *ContactService) Get(ctx context.Context, userID entities.UserID, contactID uuid.UUID) (*entities.Contact, error) {
	ctx, span := service.tracer.Start(ctx)
	defer span.End()

	contact, err := service.repository.Load(ctx, userID, contactID)
	if err != nil {
		return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, stacktrace.GetCode(err), "cannot load contact [%s] for user [%s]", contactID, userID))
	}
	return contact, nil
}

// Index lists contacts for a user with the provided search/pagination params.
func (service *ContactService) Index(ctx context.Context, userID entities.UserID, params repositories.IndexParams) (*[]entities.Contact, error) {
	ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
	defer span.End()

	contacts, err := service.repository.Index(ctx, userID, params)
	if err != nil {
		return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot index contacts for user [%s]", userID))
	}

	ctxLogger.Info(fmt.Sprintf("fetched [%d] contacts with params [%+#v]", len(*contacts), params))
	return contacts, nil
}

// Count returns the total number of contacts for a user matching the same
// search filter as Index, ignoring pagination. It lets callers report an
// accurate total independent of the current page's skip/limit.
func (service *ContactService) Count(ctx context.Context, userID entities.UserID, params repositories.IndexParams) (int64, error) {
	ctx, span := service.tracer.Start(ctx)
	defer span.End()

	total, err := service.repository.Count(ctx, userID, params)
	if err != nil {
		return 0, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot count contacts for user [%s]", userID))
	}
	return total, nil
}

// Update persists changes to a contact and invalidates its old and new numbers.
func (service *ContactService) Update(ctx context.Context, contact *entities.Contact, previousPhoneNumbers []string) error {
	ctx, span := service.tracer.Start(ctx)
	defer span.End()

	if err := service.repository.Update(ctx, contact); err != nil {
		return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot update contact [%s] for user [%s]", contact.ID, contact.UserID))
	}

	phoneNumbers := make([]string, 0, len(previousPhoneNumbers)+len(contact.PhoneNumbers))
	phoneNumbers = append(phoneNumbers, previousPhoneNumbers...)
	phoneNumbers = append(phoneNumbers, contact.PhoneNumbers...)
	service.invalidate(contact.UserID, phoneNumbers)
	return nil
}

// Delete removes a contact scoped to the user and invalidates its phone numbers.
func (service *ContactService) Delete(ctx context.Context, userID entities.UserID, contactID uuid.UUID) error {
	ctx, span := service.tracer.Start(ctx)
	defer span.End()

	contact, err := service.repository.Load(ctx, userID, contactID)
	if err != nil {
		return service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, stacktrace.GetCode(err), "cannot load contact [%s] for user [%s] before delete", contactID, userID))
	}

	if err := service.repository.Delete(ctx, userID, contactID); err != nil {
		return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete contact [%s] for user [%s]", contactID, userID))
	}

	service.invalidate(userID, contact.PhoneNumbers)
	return nil
}

// DeleteAllForUser removes every contact owned by a user and clears cached contacts.
func (service *ContactService) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {
	ctx, span := service.tracer.Start(ctx)
	defer span.End()

	if err := service.repository.DeleteAllForUser(ctx, userID); err != nil {
		return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete all contacts for user [%s]", userID))
	}

	service.invalidate(userID, nil)
	return nil
}

// GetContactMap resolves only the requested phone numbers. Each contact is
// cached independently by user and phone number.
func (service *ContactService) GetContactMap(ctx context.Context, userID entities.UserID, phoneNumbers []string) (map[string]*entities.Contact, error) {
	ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
	defer span.End()

	generation := service.generation(userID)
	result := make(map[string]*entities.Contact, len(phoneNumbers))
	missing := make([]string, 0, len(phoneNumbers))
	missingSet := make(map[string]struct{}, len(phoneNumbers))
	requested := make(map[string]struct{}, len(phoneNumbers))
	for _, phoneNumber := range phoneNumbers {
		if _, seen := requested[phoneNumber]; seen {
			continue
		}
		requested[phoneNumber] = struct{}{}
		key := service.cacheKey(userID, phoneNumber)
		if entry, found := service.cache.Get(key); found {
			if entry.generation == generation {
				if entry.contact != nil {
					result[phoneNumber] = entry.contact
				}
				continue
			}
			service.cache.Del(key)
		}
		missing = append(missing, phoneNumber)
		missingSet[phoneNumber] = struct{}{}
	}

	if len(missing) == 0 {
		return result, nil
	}

	ctxLogger.Info(fmt.Sprintf("fetching [%d] missing contacts by phone numbers for user [%s]", len(missing), userID))
	contacts, err := service.repository.FetchByPhoneNumbers(ctx, userID, missing)
	if err != nil {
		return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot fetch contacts by phone numbers for user [%s]", userID))
	}

	for index := range *contacts {
		contact := (*contacts)[index]
		for _, phoneNumber := range contact.PhoneNumbers {
			if _, requested := missingSet[phoneNumber]; requested {
				result[phoneNumber] = &contact
			}
		}
	}

	if service.generation(userID) == generation {
		for _, phoneNumber := range missing {
			contact := result[phoneNumber]
			entry := ContactCacheEntry{contact: contact, generation: generation}
			if accepted := service.cache.SetWithTTL(service.cacheKey(userID, phoneNumber), entry, 1, contactMapCacheTTL); !accepted {
				ctxLogger.Error(stacktrace.NewErrorf("cannot cache contact lookup for user [%s] and phone number [%s]", userID, phoneNumber))
			}
		}
	}

	return result, nil
}

func (service *ContactService) invalidate(userID entities.UserID, phoneNumbers []string) {
	service.advanceGeneration(userID)
	service.cache.Wait()
	for _, phoneNumber := range phoneNumbers {
		service.cache.Del(service.cacheKey(userID, phoneNumber))
	}
}