TouchVCSProviderUser refreshes an active VCS provider user, or inserts/reactivates one when doing so would not exceed the active user limit.
(ctx context.Context, workspace string, user *VCSProviderUserMessage, activeWindow time.Duration, limit int)
| 47 | // TouchVCSProviderUser refreshes an active VCS provider user, or inserts/reactivates |
| 48 | // one when doing so would not exceed the active user limit. |
| 49 | func (s *Store) TouchVCSProviderUser(ctx context.Context, workspace string, user *VCSProviderUserMessage, activeWindow time.Duration, limit int) (bool, error) { |
| 50 | payload := user.Payload |
| 51 | if payload == nil { |
| 52 | payload = &storepb.VCSProviderUserPayload{} |
| 53 | } |
| 54 | payloadBytes, err := protojson.Marshal(payload) |
| 55 | if err != nil { |
| 56 | return false, errors.Wrapf(err, "failed to marshal VCS provider user payload") |
| 57 | } |
| 58 | |
| 59 | vcsType := user.VCSType.String() |
| 60 | var refreshed bool |
| 61 | if err := s.GetDB().QueryRowContext(ctx, ` |
| 62 | UPDATE vcs_provider_user |
| 63 | SET last_seen_at = now(), payload = $4 |
| 64 | WHERE workspace = $1 AND vcs_type = $2 AND user_id = $3 |
| 65 | AND last_seen_at >= now() - make_interval(secs => $5) |
| 66 | RETURNING true |
| 67 | `, workspace, vcsType, user.UserID, payloadBytes, activeWindow.Seconds()).Scan(&refreshed); err != nil { |
| 68 | if err != sql.ErrNoRows { |
| 69 | return false, errors.Wrapf(err, "failed to update active VCS provider user") |
| 70 | } |
| 71 | } else { |
| 72 | return true, nil |
| 73 | } |
| 74 | |
| 75 | tx, err := s.GetDB().BeginTx(ctx, nil) |
| 76 | if err != nil { |
| 77 | return false, errors.Wrapf(err, "failed to begin transaction") |
| 78 | } |
| 79 | defer tx.Rollback() |
| 80 | |
| 81 | if err := AcquireAdvisoryXactLockWithStringKey(ctx, tx, AdvisoryLockKeyVCSProviderUser, workspace); err != nil { |
| 82 | return false, errors.Wrapf(err, "failed to acquire VCS provider user lock") |
| 83 | } |
| 84 | |
| 85 | var active bool |
| 86 | if err := tx.QueryRowContext(ctx, ` |
| 87 | SELECT last_seen_at >= now() - make_interval(secs => $4) |
| 88 | FROM vcs_provider_user |
| 89 | WHERE workspace = $1 AND vcs_type = $2 AND user_id = $3 |
| 90 | `, workspace, vcsType, user.UserID, activeWindow.Seconds()).Scan(&active); err != nil && err != sql.ErrNoRows { |
| 91 | return false, errors.Wrapf(err, "failed to get VCS provider user") |
| 92 | } |
| 93 | |
| 94 | if active { |
| 95 | if _, err := tx.ExecContext(ctx, ` |
| 96 | UPDATE vcs_provider_user |
| 97 | SET last_seen_at = now(), payload = $4 |
| 98 | WHERE workspace = $1 AND vcs_type = $2 AND user_id = $3 |
| 99 | `, workspace, vcsType, user.UserID, payloadBytes); err != nil { |
| 100 | return false, errors.Wrapf(err, "failed to update VCS provider user") |
| 101 | } |
| 102 | if err := tx.Commit(); err != nil { |
| 103 | return false, errors.Wrapf(err, "failed to commit transaction") |
| 104 | } |
| 105 | return true, nil |
| 106 | } |