Commit 211bccc9 authored by tavit ohanian's avatar tavit ohanian

Merge branch 'port-2021-05-03' into 'master'

Port 2021 05 03

See merge request dms3/public/go-dms3-delay!1
parents 72378897 1d0b747d
Pipeline #268 passed with stages
in 25 seconds
blank_issues_enabled: false
contact_links:
- name: Getting Help on IPFS
url: https://ipfs.io/help
about: All information about how and where to get help on IPFS.
- name: IPFS Official Forum
url: https://discuss.ipfs.io
about: Please post general questions, support requests, and discussions here.
---
name: Open an issue
about: Only for actionable issues relevant to this repository.
title: ''
labels: need/triage
assignees: ''
---
<!--
Hello! To ensure this issue is correctly addressed as soon as possible by the IPFS team, please try to make sure:
- This issue is relevant to this repository's topic or codebase.
- A clear description is provided. It should includes as much relevant information as possible and clear scope for the issue to be actionable.
FOR GENERAL DISCUSSION, HELP OR QUESTIONS, please see the options at https://ipfs.io/help or head directly to https://discuss.ipfs.io.
(you can delete this section after reading)
-->
# Configuration for welcome - https://github.com/behaviorbot/welcome
# Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome
# Comment to be posted to on first time issues
newIssueWelcomeComment: >
Thank you for submitting your first issue to this repository! A maintainer
will be here shortly to triage and review.
In the meantime, please double-check that you have provided all the
necessary information to make this process easy! Any information that can
help save additional round trips is useful! We currently aim to give
initial feedback within **two business days**. If this does not happen, feel
free to leave a comment.
Please keep an eye on how this issue will be labeled, as labels give an
overview of priorities, assignments and additional actions requested by the
maintainers:
- "Priority" labels will show how urgent this is for the team.
- "Status" labels will show if this is ready to be worked on, blocked, or in progress.
- "Need" labels will indicate if additional input or analysis is required.
Finally, remember to use https://discuss.ipfs.io if you just need general
support.
# Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome
# Comment to be posted to on PRs from first time contributors in your repository
newPRWelcomeComment: >
Thank you for submitting this PR!
A maintainer will be here shortly to review it.
We are super grateful, but we are also overloaded! Help us by making sure
that:
* The context for this PR is clear, with relevant discussion, decisions
and stakeholders linked/mentioned.
* Your contribution itself is clear (code comments, self-review for the
rest) and in its best form. Follow the [code contribution
guidelines](https://github.com/ipfs/community/blob/master/CONTRIBUTING.md#code-contribution-guidelines)
if they apply.
Getting other community members to do a review would be great help too on
complex PRs (you can ask in the chats/forums). If you are unsure about
something, just leave us a comment.
Next steps:
* A maintainer will triage and assign priority to this PR, commenting on
any missing things and potentially assigning a reviewer for high
priority items.
* The PR gets reviews, discussed and approvals as needed.
* The PR is merged by maintainers when it has been approved and comments addressed.
We currently aim to provide initial feedback/triaging within **two business
days**. Please keep an eye on any labelling actions, as these will indicate
priorities and status of your contribution.
We are very grateful for your contribution!
# Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge
# Comment to be posted to on pull requests merged by a first time user
# Currently disabled
#firstPRMergeComment: ""
stages:
- build
- test
variables:
BUILD_DIR: "/tmp/$CI_CONCURRENT_PROJECT_ID"
before_script:
- mkdir -p $BUILD_DIR/src
- cd $BUILD_DIR/src
- if [ -d $CI_PROJECT_DIR ]
- then
- echo "soft link $CI_PROJECT_DIR exists"
- else
- echo "creating soft link $CI_PROJECT_DIR"
- ln -s $CI_PROJECT_DIR
- fi
- cd $CI_PROJECT_DIR
build:
stage: build
tags:
- testing
script:
- echo $CI_JOB_STAGE
- go build
test:
stage: test
tags:
- testing
script:
- echo $CI_JOB_STAGE
- go test -cover
coverage: '/coverage: \d+.\d+% of statements/'
0.1.0: QmUe1WCHkQaz4UeNKiHDUBV2T6i9prc3DniqyHPXyfGaUq
os:
- linux
language: go
go:
- 1.11.x
env:
global:
- GOTFLAGS="-race"
matrix:
- BUILD_DEPTYPE=gx
- BUILD_DEPTYPE=gomod
# disable travis install
install:
- true
script:
- bash <(curl -s https://raw.githubusercontent.com/ipfs/ci-helpers/master/travis-ci/run-standard-tests.sh)
cache:
directories:
- $GOPATH/src/gx
- $GOPATH/pkg/mod
- $HOME/.cache/go-build
notifications:
email: false
MIT License
Copyright (c) 2018 IPFS
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
all: deps
gx:
go get github.com/whyrusleeping/gx
go get github.com/whyrusleeping/gx-go
deps: gx
gx --verbose install --global
gx-go rewrite
test: deps
gx test -v -race -coverprofile=coverage.txt -covermode=atomic .
rw:
gx-go rewrite
rwundo:
gx-go rewrite --undo
publish: rwundo
gx publish
.PHONY: all gx deps test rw rwundo publish
# go-dms3-delay
# go-ipfs-delay
[![](https://img.shields.io/badge/made%20by-Protocol%20Labs-blue.svg?style=flat-square)](http://ipn.io)
[![](https://img.shields.io/badge/project-IPFS-blue.svg?style=flat-square)](http://ipfs.io/)
[![standard-readme compliant](https://img.shields.io/badge/standard--readme-OK-green.svg?style=flat-square)](https://github.com/RichardLitt/standard-readme)
[![GoDoc](https://godoc.org/github.com/ipfs/go-ipfs-delay?status.svg)](https://godoc.org/github.com/ipfs/go-ipfs-delay)
[![Build Status](https://travis-ci.org/ipfs/go-ipfs-delay.svg?branch=master)](https://travis-ci.org/ipfs/go-ipfs-delay)
> go-ipfs-delay makes it easy to add (threadsafe) configurable delays to other objects.
## Table of Contents
- [Install](#install)
- [Usage](#usage)
- [Contribute](#contribute)
- [License](#license)
## Install
`go-ipfs-delay` works like a regular Go module:
```
> go get github.com/ipfs/go-ipfs-delay
```
## Usage
```
import "github.com/ipfs/go-ipfs-delay"
```
Check the [GoDoc documentation](https://godoc.org/github.com/ipfs/go-ipfs-delay)
## Contribute
PRs accepted.
Small note: If editing the README, please conform to the [standard-readme](https://github.com/RichardLitt/standard-readme) specification.
## License
MIT © Protocol Labs, Inc.
package delay
import (
"math/rand"
"sync"
"time"
)
// D (Delay) makes it easy to add (threadsafe) configurable delays to other
// objects.
type D interface {
Set(time.Duration) time.Duration
Wait()
NextWaitTime() time.Duration
Get() time.Duration
}
type delay struct {
l sync.RWMutex
t time.Duration
generator Generator
}
func (d *delay) Set(t time.Duration) time.Duration {
d.l.Lock()
defer d.l.Unlock()
prev := d.t
d.t = t
return prev
}
func (d *delay) Wait() {
d.l.RLock()
defer d.l.RUnlock()
time.Sleep(d.generator.NextWaitTime(d.t))
}
func (d *delay) NextWaitTime() time.Duration {
d.l.Lock()
defer d.l.Unlock()
return d.generator.NextWaitTime(d.t)
}
func (d *delay) Get() time.Duration {
d.l.Lock()
defer d.l.Unlock()
return d.t
}
// Delay generates a generic delay form a t, a sleeper, and a generator
func Delay(t time.Duration, generator Generator) D {
return &delay{
t: t,
generator: generator,
}
}
// Fixed returns a delay with fixed latency
func Fixed(t time.Duration) D {
return Delay(t, FixedGenerator())
}
// VariableUniform is a delay following a uniform distribution
// Notice that to implement the D interface Set can only change the minimum delay
// the delta is set only at initialization
func VariableUniform(t, d time.Duration, rng *rand.Rand) D {
return Delay(t, VariableUniformGenerator(d, rng))
}
// VariableNormal is a delay following a normal distribution
// Notice that to implement the D interface Set can only change the mean delay
// the standard deviation is set only at initialization
func VariableNormal(t, std time.Duration, rng *rand.Rand) D {
return Delay(t, VariableNormalGenerator(std, rng))
}
package delay
import (
"testing"
"time"
)
func TestDelaySetAndGet(t *testing.T) {
initialValue := 1000 * time.Millisecond
modifiedValue := 2000 * time.Millisecond
deviation := 1000 * time.Millisecond
fixed := Fixed(initialValue)
variableNormal := VariableNormal(initialValue, deviation, nil)
variableUniform := VariableUniform(initialValue, deviation, nil)
if fixed.Get().Seconds() != 1 {
t.Fatal("Fixed delay not initialized correctly")
}
if variableNormal.Get().Seconds() != 1 {
t.Fatal("Normalized variable delay not initialized correctly")
}
if variableUniform.Get().Seconds() != 1 {
t.Fatal("Uniform variable delay not initialized correctly")
}
fixed.Set(modifiedValue)
if fixed.Get().Seconds() != 2 {
t.Fatal("Fixed delay not set correctly")
}
variableNormal.Set(modifiedValue)
if variableNormal.Get().Seconds() != 2 {
t.Fatal("Normalized variable delay not set correctly")
}
variableUniform.Set(modifiedValue)
if variableUniform.Get().Seconds() != 2 {
t.Fatal("Uniform variable delay not initialized correctly")
}
}
type fixedAdd struct {
toAdd time.Duration
}
func (fa *fixedAdd) NextWaitTime(t time.Duration) time.Duration {
return t + fa.toAdd
}
func TestDelaySleep(t *testing.T) {
initialValue := 1000 * time.Millisecond
toAdd := 500 * time.Millisecond
generator := &fixedAdd{toAdd: toAdd}
delay := Delay(initialValue, generator)
if delay.NextWaitTime() != initialValue+toAdd {
t.Fatal("NextWaitTime should call the generator")
}
}
package delay
import (
"math/rand"
"time"
)
// Generator provides an interface for generating wait times
type Generator interface {
NextWaitTime(time.Duration) time.Duration
}
var sharedRNG = rand.New(rand.NewSource(time.Now().UnixNano()))
// VariableNormalGenerator makes delays that following a normal distribution
func VariableNormalGenerator(std time.Duration, rng *rand.Rand) Generator {
if rng == nil {
rng = sharedRNG
}
return &variableNormal{
std: std,
rng: rng,
}
}
type variableNormal struct {
std time.Duration
rng *rand.Rand
}
func (d *variableNormal) NextWaitTime(t time.Duration) time.Duration {
return time.Duration(d.rng.NormFloat64()*float64(d.std)) + t
}
// VariableUniformGenerator generates delays following a uniform distribution
func VariableUniformGenerator(d time.Duration, rng *rand.Rand) Generator {
if rng == nil {
rng = sharedRNG
}
return &variableUniform{
d: d,
rng: rng,
}
}
type variableUniform struct {
d time.Duration // max delta
rng *rand.Rand
}
func (d *variableUniform) NextWaitTime(t time.Duration) time.Duration {
return time.Duration(d.rng.Float64()*float64(d.d)) + t
}
type fixed struct{}
// FixedGenerator returns a delay with fixed latency
func FixedGenerator() Generator {
return &fixed{}
}
func (d *fixed) NextWaitTime(t time.Duration) time.Duration {
return t
}
package delay
import (
"math"
"math/rand"
"testing"
"time"
)
const testSeed = 99
func TestGeneratorNextWaitTime(t *testing.T) {
initialValue := 1000 * time.Millisecond
deviation := 1000 * time.Millisecond
firstRandomNormal := rand.New(rand.NewSource(testSeed)).NormFloat64()
firstRandom := rand.New(rand.NewSource(testSeed)).Float64()
fixedGenerator := FixedGenerator()
variableNormalGenerator := VariableNormalGenerator(deviation, rand.New(rand.NewSource(testSeed)))
variableUniformGenerator := VariableUniformGenerator(deviation, rand.New(rand.NewSource(testSeed)))
if fixedGenerator.NextWaitTime(initialValue).Seconds() != 1 {
t.Fatal("Fixed generator output incorrect wait time")
}
if math.Abs(variableNormalGenerator.NextWaitTime(initialValue).Seconds()-(firstRandomNormal*deviation.Seconds()+initialValue.Seconds())) > 0.00001 {
t.Fatal("Normalized variable delay generator output incorrect wait time")
}
if math.Abs(variableUniformGenerator.NextWaitTime(initialValue).Seconds()-(firstRandom*deviation.Seconds()+initialValue.Seconds())) > 0.00001 {
t.Fatal("Uniform variable delay output incorrect wait time")
}
}
{
"author": "hsanjuan",
"bugs": {
"url": "https://github.com/ipfs/go-ipfs-delay"
},
"gx": {
"dvcsimport": "github.com/ipfs/go-ipfs-delay"
},
"gxVersion": "0.12.1",
"language": "go",
"license": "",
"name": "go-ipfs-delay",
"releaseCmd": "git commit -a -m \"gx publish $VERSION\"",
"version": "0.1.0"
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment