Skip to content

Commit 3e7dc51

Browse files
Created txn redis for functions related to transactions for Redis
1 parent d4bbabf commit 3e7dc51

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

internal/session/txnredis.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package session
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
8+
"github.com/google/uuid"
9+
10+
"github.com/PythonHacker24/linux-acl-management-backend/internal/types"
11+
)
12+
13+
/* save a pending transaction in Redis as transactionID -> JSON in session:sessionID:txnpending */
14+
func (m *Manager) SavePendingTransaction(session *Session, tx *types.Transaction) error {
15+
ctx := context.Background()
16+
17+
/* get the session ID */
18+
sessionID := session.ID
19+
20+
/* create the Redis key for pending transactions */
21+
key := fmt.Sprintf("session:%s:txnpending", sessionID)
22+
23+
/* marshal transaction to JSON */
24+
txBytes, err := json.Marshal(tx)
25+
if err != nil {
26+
return fmt.Errorf("failed to marshal transaction: %w", err)
27+
}
28+
29+
/* use HSET to store transactionID -> JSON */
30+
return m.redis.HSet(ctx, key, tx.ID.String(), txBytes).Err()
31+
}
32+
33+
/* remove a pending transaction by ID from Redis HASH session:<sessionID>:txnpending */
34+
func (m *Manager) RemovePendingTransaction(session *Session, txnID uuid.UUID) error {
35+
ctx := context.Background()
36+
37+
sessionID := session.ID
38+
key := fmt.Sprintf("session:%s:txnpending", sessionID)
39+
40+
/* remove the transaction ID field from the hash */
41+
return m.redis.HDel(ctx, key, txnID.String()).Err()
42+
}
43+
44+
/* returns latest results of processed transactions */
45+
func (m *Manager) getTransactionResultsRedis(session *Session, limit int) ([]types.Transaction, error) {
46+
ctx := context.Background()
47+
48+
/* get the session ID */
49+
sessionID := session.ID
50+
51+
/* create a key for Redis operation */
52+
key := fmt.Sprintf("session:%s:txresults", sessionID)
53+
54+
/* returns transactions in chronological order */
55+
values, err := m.redis.LRange(ctx, key, int64(-limit), -1).Result()
56+
if err != nil {
57+
return nil, fmt.Errorf("failed to get transaction results: %w", err)
58+
}
59+
60+
/* converts each JSON string back into a TransactionResult */
61+
results := make([]types.Transaction, 0, len(values))
62+
for _, val := range values {
63+
var result types.Transaction
64+
if err := json.Unmarshal([]byte(val), &result); err != nil {
65+
m.errCh <- fmt.Errorf("failed to unmarshal transaction result: %w; value: %s", err, val)
66+
continue
67+
}
68+
results = append(results, result)
69+
}
70+
71+
return results, nil
72+
}

0 commit comments

Comments
 (0)