Skip to content

Commit

Permalink
namesys: select on output
Browse files Browse the repository at this point in the history
License: MIT
Signed-off-by: Łukasz Magiera <magik6k@gmail.com>
  • Loading branch information
magik6k committed Oct 16, 2018
1 parent 734615a commit 2c6295b
Showing 1 changed file with 17 additions and 20 deletions.
37 changes: 17 additions & 20 deletions namesys/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ func resolve(ctx context.Context, r resolver, name string, options opts.ResolveO
return p, err
}

func emitResult(ctx context.Context, outCh chan<- Result, r Result) {
select {
case outCh <- r:
case <-ctx.Done():
}
}

func resolveAsync(ctx context.Context, r resolver, name string, options opts.ResolveOpts) <-chan Result {
resCh := r.resolveOnceAsync(ctx, name, options)
depth := options.Depth
Expand All @@ -49,6 +56,11 @@ func resolveAsync(ctx context.Context, r resolver, name string, options opts.Res
defer close(outCh)
var subCh <-chan Result
var cancelSub context.CancelFunc
defer func() {
if cancelSub != nil {
cancelSub()
}
}()

for {
select {
Expand All @@ -59,20 +71,17 @@ func resolveAsync(ctx context.Context, r resolver, name string, options opts.Res
}

if res.err != nil {
outCh <- Result{Err: res.err}
if cancelSub != nil {
cancelSub()
}
emitResult(ctx, outCh, Result{Err: res.err})
return
}
log.Debugf("resolved %s to %s", name, res.value.String())
if !strings.HasPrefix(res.value.String(), ipnsPrefix) {
outCh <- Result{Path: res.value}
emitResult(ctx, outCh, Result{Path: res.value})
break
}

if depth == 1 {
outCh <- Result{Path: res.value, Err: ErrResolveRecursion}
emitResult(ctx, outCh, Result{Path: res.value, Err: ErrResolveRecursion})
break
}

Expand All @@ -87,6 +96,7 @@ func resolveAsync(ctx context.Context, r resolver, name string, options opts.Res
cancelSub()
}
subCtx, cancelSub = context.WithCancel(ctx)
_ = cancelSub

p := strings.TrimPrefix(res.value.String(), ipnsPrefix)
subCh = resolveAsync(subCtx, r, p, subopts)
Expand All @@ -96,24 +106,11 @@ func resolveAsync(ctx context.Context, r resolver, name string, options opts.Res
break
}

select {
case outCh <- res:
case <-ctx.Done():
if cancelSub != nil {
cancelSub()
}
return
}
emitResult(ctx, outCh, res)
case <-ctx.Done():
if cancelSub != nil {
cancelSub()
}
return
}
if resCh == nil && subCh == nil {
if cancelSub != nil {
cancelSub()
}
return
}
}
Expand Down

0 comments on commit 2c6295b

Please sign in to comment.