Skip to content

Commit

Permalink
remove background context (#377)
Browse files Browse the repository at this point in the history
  • Loading branch information
tonicmuroq authored Apr 3, 2021
1 parent 4a39c3c commit 656c942
Showing 1 changed file with 20 additions and 13 deletions.
33 changes: 20 additions & 13 deletions store/redis/ephemeral.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (r *Rediaron) StartEphemeral(ctx context.Context, path string, heartbeat ti
return nil, nil, ErrAlreadyExists
}

ctx, cancel := context.WithCancel(context.Background())
cctx, cancel := context.WithCancel(context.Background())
expiry := make(chan struct{})

var wg sync.WaitGroup
Expand All @@ -33,23 +33,15 @@ func (r *Rediaron) StartEphemeral(ctx context.Context, path string, heartbeat ti
tick := time.NewTicker(heartbeat / 3)
defer tick.Stop()

revoke := func() {
if _, err := r.cli.Del(context.Background(), path).Result(); err != nil {
log.Errorf("[StartEphemeral] revoke with %s failed: %v", path, err)
}
}

for {
select {
case <-tick.C:
if _, err := r.cli.Expire(context.Background(), path, heartbeat).Result(); err != nil {
log.Errorf("[StartEphemeral] keepalive with %s failed: %v", path, err)
revoke()
if err := r.refreshEphemeral(path, heartbeat); err != nil {
r.revokeEphemeral(path)
return
}

case <-ctx.Done():
revoke()
case <-cctx.Done():
r.revokeEphemeral(path)
return
}
}
Expand All @@ -60,3 +52,18 @@ func (r *Rediaron) StartEphemeral(ctx context.Context, path string, heartbeat ti
wg.Wait()
}, nil
}

func (r *Rediaron) revokeEphemeral(path string) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if _, err := r.cli.Del(ctx, path).Result(); err != nil {
log.Errorf("[refreshEphemeral] revoke with %s failed: %v", path, err)
}
}

func (r *Rediaron) refreshEphemeral(path string, ttl time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
_, err := r.cli.Expire(ctx, path, ttl).Result()
return err
}

0 comments on commit 656c942

Please sign in to comment.