Use query instead of iteration to get saved received offer (#881)

This commit is contained in:
Jonathan Zernik 2021-02-22 21:40:44 -08:00 committed by GitHub
parent d9b5613480
commit b7658932a9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 7 deletions

View file

@ -792,6 +792,35 @@ class SqueakDb:
offer_with_peer = self._parse_received_offer_with_peer(row)
return offer_with_peer
def get_received_offer_for_squeak_and_peer(
self,
squeak_hash: bytes,
peer_address: PeerAddress,
) -> Optional[ReceivedOfferWithPeer]:
""" Get offer with peer for a given peer address and squeak hash . """
s = (
select([self.received_offers, self.peers])
.select_from(
self.received_offers.outerjoin(
self.peers,
self.peers.c.host == self.received_offers.c.peer_host,
self.peers.c.port == self.received_offers.c.peer_port,
)
)
.where(self.received_offers.c.squeak_hash == squeak_hash.hex())
.where(self.received_offers.c.peer_host == peer_address.host)
.where(self.received_offers.c.peer_port == peer_address.port)
.where(self.received_offer_is_not_paid)
.where(self.received_offer_is_not_expired)
)
with self.get_connection() as connection:
result = connection.execute(s)
row = result.fetchone()
if row is None:
return None
offer_with_peer = self._parse_received_offer_with_peer(row)
return offer_with_peer
def delete_expired_received_offers(self):
""" Delete all expired offers. """
s = self.received_offers.delete().where(

View file

@ -1,6 +1,7 @@
import logging
import threading
from typing import List
from typing import Optional
from squeak.core import CheckSqueak
from squeak.core import CSqueak
@ -338,6 +339,16 @@ class SqueakController:
def get_received_offers_with_peer(self, squeak_hash: bytes) -> List[ReceivedOfferWithPeer]:
return self.squeak_db.get_received_offers_with_peer(squeak_hash)
def get_received_offer_for_squeak_and_peer(
self,
squeak_hash: bytes,
peer_addresss: PeerAddress,
) -> Optional[ReceivedOfferWithPeer]:
return self.squeak_db.get_received_offer_for_squeak_and_peer(
squeak_hash,
peer_addresss,
)
def get_buy_offer_with_peer(self, received_offer_id: int) -> ReceivedOfferWithPeer:
received_offer_with_peer = self.squeak_db.get_offer_with_peer(
received_offer_id)

View file

@ -121,13 +121,10 @@ class PeerConnection:
self._upload_squeak(squeak_hash)
def _get_saved_offer(self, squeak_hash: bytes) -> Optional[ReceivedOfferWithPeer]:
offers = self.squeak_controller.get_received_offers_with_peer(
squeak_hash)
for offer_with_peer in offers:
if offer_with_peer.received_offer.peer_address.host == self.peer_address.host \
and offer_with_peer.received_offer.peer_address.port == self.peer_address.port:
return offer_with_peer
return None
return self.squeak_controller.get_received_offer_for_squeak_and_peer(
squeak_hash,
self.peer_address,
)
def _download_squeak(self, squeak_hash: bytes):
squeak = self.peer_client.download_squeak(squeak_hash)