github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/core/connection/smartconnect.go (about) 1 /* 2 * Copyright (C) 2022 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package connection 19 20 import ( 21 "fmt" 22 "time" 23 24 "github.com/mysteriumnetwork/node/core/discovery/proposal" 25 ) 26 27 type proposalRepository interface { 28 Proposals(filter *proposal.Filter) ([]proposal.PricedServiceProposal, error) 29 } 30 31 // FilteredProposals create an function to keep getting proposals from the discovery based on the provided filters. 32 func FilteredProposals(f *proposal.Filter, sortBy string, repo proposalRepository) func() (*proposal.PricedServiceProposal, error) { 33 usedProposals := make(map[string]time.Time) 34 35 return func() (*proposal.PricedServiceProposal, error) { 36 proposals, err := repo.Proposals(f) 37 if err != nil { 38 return nil, err 39 } 40 41 proposals, err = proposal.Sort(proposals, sortBy) 42 if err != nil { 43 return nil, fmt.Errorf("failed to sort proposals: %w", err) 44 } 45 46 for _, p := range proposals { // Trying to find providers that we didn't try to connect during 5 minutes. 47 if t, ok := usedProposals[p.ProviderID]; !ok || time.Since(t) > 5*time.Minute { 48 usedProposals[p.ProviderID] = time.Now() 49 return &p, nil 50 } 51 } 52 53 for _, p := range proposals { // If we failed to find new provider, trying the old ones. 54 usedProposals[p.ProviderID] = time.Now() 55 return &p, nil 56 } 57 58 return nil, fmt.Errorf("no providers available for the filter") 59 } 60 }