restore_session.go RawHistoryFolder
1package usecase
2
3import (
4 "context"
5 "errors"
6 "fmt"
7
8 "github.com/bnema/dumber/internal/domain/entity"
9 "github.com/bnema/dumber/internal/domain/repository"
10 "github.com/bnema/dumber/internal/logging"
11)
12
13// ErrSessionNotFound is returned when a session state cannot be found.
14var ErrSessionNotFound = errors.New("session not found")
15
16// ErrVersionMismatch is returned when the session state version is incompatible.
17var ErrVersionMismatch = errors.New("session state version mismatch")
18
19// RestoreSessionUseCase handles restoring session state from a snapshot.
20type RestoreSessionUseCase struct {
21 stateRepo repository.SessionStateRepository
22 sessionRepo repository.SessionRepository
23}
24
25// NewRestoreSessionUseCase creates a new RestoreSessionUseCase.
26func NewRestoreSessionUseCase(
27 stateRepo repository.SessionStateRepository,
28 sessionRepo repository.SessionRepository,
29) *RestoreSessionUseCase {
30 return &RestoreSessionUseCase{
31 stateRepo: stateRepo,
32 sessionRepo: sessionRepo,
33 }
34}
35
36// RestoreInput contains the parameters for restoring a session.
37type RestoreInput struct {
38 SessionID entity.SessionID
39}
40
41// RestoreOutput contains the restored session state.
42type RestoreOutput struct {
43 State *entity.SessionState
44}
45
46// Execute loads and validates a session state for restoration.
47func (uc *RestoreSessionUseCase) Execute(ctx context.Context, input RestoreInput) (*RestoreOutput, error) {
48 log := logging.FromContext(ctx)
49
50 if input.SessionID == "" {
51 return nil, fmt.Errorf("session id required")
52 }
53
54 log.Info().
55 Str("session_id", string(input.SessionID)).
56 Msg("restoring session state")
57
58 state, err := uc.stateRepo.GetSnapshot(ctx, input.SessionID)
59 if err != nil {
60 return nil, fmt.Errorf("get session snapshot: %w", err)
61 }
62 if state == nil {
63 return nil, ErrSessionNotFound
64 }
65
66 // Validate version compatibility
67 if state.Version > entity.SessionStateVersion {
68 log.Warn().
69 Int("state_version", state.Version).
70 Int("current_version", entity.SessionStateVersion).
71 Msg("session state version is newer than current version")
72 return nil, ErrVersionMismatch
73 }
74
75 log.Info().
76 Str("session_id", string(input.SessionID)).
77 Int("tab_count", len(state.Tabs)).
78 Int("pane_count", state.CountPanes()).
79 Msg("session state loaded for restoration")
80
81 return &RestoreOutput{State: state}, nil
82}
83
84// DeleteSnapshot removes a session's snapshot (for cleanup after failed restore or user deletion).
85func (uc *RestoreSessionUseCase) DeleteSnapshot(ctx context.Context, sessionID entity.SessionID) error {
86 return uc.stateRepo.DeleteSnapshot(ctx, sessionID)
87}