Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

from fiftyone_devicedetection_onpremise.devicedetection_onpremise import \
DeviceDetectionOnPremise
from fiftyone_devicedetection_onpremise.constants import RESULTS_CLOSED
from fiftyone_devicedetection_onpremise.swig_data import SwigData
from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder

Expand Down Expand Up @@ -82,9 +83,15 @@ def test_a_reused_instance_gives_the_new_request_results(self):
first = flowdata.device
self.assertTrue(first.ismobile.value())
with self.process(DESKTOP) as flowdata:
self.assertIs(first, flowdata.device)
self.assertIsNot(first, flowdata.device)
self.assertFalse(flowdata.device.ismobile.value())
self.assertEqual({}, flowdata.errors)
# The reference kept from the first request raises, as it did
# before the data was pooled, rather than reading this
# request's results.
with self.assertRaises(Exception) as caught:
first.get("ismobile")
self.assertEqual(RESULTS_CLOSED, str(caught.exception))


if __name__ == "__main__":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

from fiftyone_ipintelligence_onpremise.ipintelligence_onpremise import \
IpIntelligenceOnPremise
from fiftyone_ipintelligence_onpremise.constants import RESULTS_CLOSED
from fiftyone_ipintelligence_onpremise.swig_data import SwigData
from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder

Expand Down Expand Up @@ -79,7 +80,13 @@ def test_a_reused_instance_has_no_address_from_the_last_request(self):
first = flowdata.ip
self.assertTrue(first.get("ip").has_value())
with self.process(TestConstants.IPV6_ADDRESS) as flowdata:
self.assertIs(first, flowdata.ip)
self.assertIsNot(first, flowdata.ip)
# The reference kept from the first request raises, as it did
# before the data was pooled, rather than reading this
# request's results.
with self.assertRaises(Exception) as caught:
first.get("ip")
self.assertEqual(RESULTS_CLOSED, str(caught.exception))
self.assertFalse(flowdata.ip.get("ip").has_value())
self.assertEqual(TestConstants.IPV6_ADDRESS,
flowdata.ip.get("ipv6").value())
Expand Down
2 changes: 1 addition & 1 deletion pipeline/fiftyone_pipeline_core/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def index():

## Element data is reused

Some flow elements reuse their element data from one request to the next. When a flow data is closed, by calling `close()` or at the end of a `with` block, its element data goes back to a pool, and a later request may change its values. So read the values you need before the flow data is closed, and don't keep a reference to element data, such as `flowdata.device`, after that. Keeping one isn't supported, and reads aren't checked for it. A value you've already read is unchanged.
Some flow elements reuse their element data from one request to the next. When a flow data is closed, by calling `close()` or at the end of a `with` block, its element data goes back to a pool, and a later request gets a copy of it. So read the values you need before the flow data is closed. A reference to element data, such as `flowdata.device`, that you keep after that raises an exception when you read a property from it, and never gives you another request's values. A value you've already read is unchanged.

## Requirements

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,11 @@ class ElementData(object):
directly or by FlowData.close.

A FlowElement may take its instances from an ElementDataPool, and
closing the FlowData gives them back for a later request to reuse. So
keeping a reference to ElementData after its FlowData is closed is not
supported, because another request may then change its values. Reads
are not checked for this.
closing the FlowData gives them back for a later request to reuse. An
instance given back is closed for reading, and a later request gets a
copy of it rather than the instance itself. So a reference kept after
the FlowData is closed raises when it is read, and never reads another
request's values.

"""

Expand Down Expand Up @@ -214,6 +215,11 @@ def __init__(self, flow_element):
# default, so data whose constructor does not call this one has it too.
_finished = False

# Set once the instance has been given back to an ElementDataPool, when
# its FlowData has closed. A read then raises. The pool hands a later
# request a copy, so this instance is never opened again.
_closed_for_reading = False

def __setattr__(self, name, value):

"""!
Expand Down Expand Up @@ -258,6 +264,22 @@ def _clear(self):

self._finished = False

def _check_readable(self, key):

"""!
Raise if the instance has gone back to its FlowElement's pool, so a
reference kept after its FlowData closed reads nothing.

@type key: str
@param key: what is being read, for the message
@raise Exception: when the FlowData has been closed
"""

if self._closed_for_reading:
flow_element = self.__dict__.get("flow_element")
raise Exception(Messages.ELEMENT_DATA_CLOSED.format(
key, getattr(flow_element, "datakey", "")))

def get(self, key):

"""!
Expand All @@ -269,9 +291,12 @@ def get(self, key):

@rtype: mixed
@return: Returns specified property from the data
@raise Exception: when the FlowData has been closed and the data
has gone back to its FlowElement's pool

"""

self._check_readable(key)
return self.get_internal(key.lower())

def __getattr__(self, key):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,12 @@ def as_dictionary(self):

@rtype: dict
@return: Returns a dictionary of items in an ElementData
@raise Exception: when the FlowData has been closed and the data
has gone back to its FlowElement's pool

"""

self._check_readable("as_dictionary")
return self.contents

def get_internal(self, key):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,10 @@ class ElementDataPool(object):

An instance from the pool has no values and is open for writing, as
take() calls its _clear method, which a class with values of its own
overrides to drop them. An instance a cache may hold never goes back,
overrides to drop them. An instance given back is closed for reading,
and take() returns a copy of it, so a reference a caller kept after
closing its FlowData raises when read and never sees a later request's
values. An instance a cache may hold never goes back,
because the cache shares it with other requests, and the instances of a
FlowData that is not closed are left to the garbage collector.

Expand Down Expand Up @@ -76,7 +79,13 @@ def take(self):
with self._lock:
if not self._instances:
return None
element_data = self._instances.pop()
given_back = self._instances.pop()
# A copy, made without calling the class, whose __getattr__ reads
# properties. The instance given back stays closed for reading, so
# a reference to it kept after its FlowData closed still raises.
element_data = object.__new__(type(given_back))
element_data.__dict__.update(given_back.__dict__)
element_data._closed_for_reading = False
element_data._clear()
return element_data

Expand All @@ -96,6 +105,9 @@ def give_back(self, element_data):
# the cache did not keep. The specification asks for no less.
if getattr(element_data.flow_element, "cache", None) is not None:
return
# Closed for reading whether or not the pool keeps it, so a read
# after close raises the same way every time.
element_data._closed_for_reading = True
with self._lock:
if len(self._instances) < self.maximum_instances:
self._instances.append(element_data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,14 @@ class Messages():
"FlowElement that writes it has finished processing. ElementData is "
"written only while the FlowElement that provides it processes.")

# A read of ElementData whose FlowData has been closed, once the data
# has gone back to its FlowElement's pool. This takes the key read and
# the element's data key as format arguments.
ELEMENT_DATA_CLOSED = (
"'{}' cannot be read from the '{}' ElementData, because its "
"FlowData has been closed. Read the values needed before closing "
"the FlowData.")

# The usage sharing element is not the last Flow Element. This takes the
# element's class name, its position counting from 1 and the number of
# Flow Elements as format arguments.
Expand Down
67 changes: 65 additions & 2 deletions pipeline/fiftyone_pipeline_core/tests/test_element_data_pools.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ def test_a_reused_instance_has_no_values_from_the_last_request(self):
first = flowdata.get("pooled")
with process(pipeline, "second", 2) as flowdata:
second = flowdata.get("pooled")
self.assertIs(first, second)
self.assertIsNot(first, second)
self.assertIsNone(second.get("first"))
self.assertEqual(2, second.get("second"))
self.assertEqual("second", second.last_name)
Expand All @@ -220,7 +220,7 @@ def test_a_core_element_reuses_its_instance_with_new_values(self):
first = flowdata.sequence
session = first.get("session-id")
with process(pipeline) as flowdata:
self.assertIs(first, flowdata.sequence)
self.assertIsNot(first, flowdata.sequence)
self.assertNotEqual(session, flowdata.sequence.get("session-id"))
self.assertEqual(1, flowdata.sequence.get("sequence"))

Expand Down Expand Up @@ -256,6 +256,69 @@ def test_a_flow_data_not_closed_leaves_its_instances_to_the_gc(self):
self.assertEqual([], [ref for ref in made if ref() is not None])


# Each core element that takes its ElementData from a pool, with a property
# its data holds once processed.
CORE_POOLED = [("sequence", "sequence"), ("jsonbundler", "json"),
("javascriptbuilder", "javascript"),
("set-headers", "responseheaderdictionary")]

CLOSED = "has been closed"


class ReadAfterCloseTests(unittest.TestCase):

"""A reference to pooled ElementData kept after its FlowData closed
raises when read, and never reads a later request's values, which the
later FlowData reads as its own."""

def test_a_kept_reference_raises_once_its_flow_data_has_closed(self):
pipeline = build(PooledElement())
with process(pipeline, "first", 1) as flowdata:
kept = flowdata.pooled
with self.assertRaises(Exception) as caught:
kept.get("first")
self.assertIn(CLOSED, str(caught.exception))

def test_a_kept_reference_never_reads_the_next_request(self):
pipeline = build(PooledElement())
with process(pipeline, "first", 1) as flowdata:
kept = flowdata.pooled
with process(pipeline, "second", 2) as flowdata:
for read in (lambda: kept.get("second"),
lambda: kept.get("first"), lambda: kept["second"],
lambda: kept.second, kept.as_dictionary):
with self.assertRaises(Exception) as caught:
read()
self.assertIn(CLOSED, str(caught.exception))
self.assertEqual(2, flowdata.pooled.get("second"))
self.assertIsNone(flowdata.pooled.get("first"))

def test_each_core_element_refuses_a_read_after_close(self):
pipeline = PipelineBuilder().build()
with process(pipeline, "first", 1) as flowdata:
kept = {key: flowdata.get(key) for key, _ in CORE_POOLED}
with process(pipeline, "second", 2) as flowdata:
for key, name in CORE_POOLED:
with self.subTest(key):
with self.assertRaises(Exception) as caught:
kept[key].get(name)
self.assertIn(CLOSED, str(caught.exception))
self.assertIsNot(kept[key], flowdata.get(key))
self.assertIsNotNone(flowdata.get(key).get(name))

def test_data_a_full_pool_leaves_behind_still_refuses_reads(self):
pipeline = build(PooledElement(bound=1))
one = process(pipeline, "one", 1)
two = process(pipeline, "two", 2)
kept = (one.pooled, two.pooled)
one.close()
two.close()
for data in kept:
with self.assertRaises(Exception) as caught:
data.get("one")
self.assertIn(CLOSED, str(caught.exception))


class PoolLookupTests(unittest.TestCase):

def test_an_element_names_the_pool_it_keeps(self):
Expand Down
15 changes: 11 additions & 4 deletions pipeline/fiftyone_pipeline_core/tests/test_web_client_side.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,8 +316,9 @@ def test_the_json_served_is_the_json_builders_json(self):
"""The JavaScript Builder specification says the endpoint the
script calls back MUST return JSON in the same form as the JSON
within the script, which is the JSON Builder's. The flow data the
endpoint processes is kept, so the body can be compared with its
JSON."""
endpoint processes keeps its JSON as it closes, because its
ElementData can't be read once it has closed, so the body can be
compared with that JSON."""

pipeline = PipelineBuilder({
"javascript_builder_settings": {"endpoint": "/json"},
Expand All @@ -327,7 +328,13 @@ def test_the_json_served_is_the_json_builders_json(self):

def create_and_keep():
flowdata = create_flowdata()
processed.append(flowdata)
close = flowdata.close

def keep_and_close():
processed.append(flowdata.jsonbundler.json)
close()

flowdata.close = keep_and_close
return flowdata

app = Flask(__name__)
Expand All @@ -342,7 +349,7 @@ def json_endpoint():

self.assertEqual(200, response.status_code)
self.assertEqual(1, len(processed))
self.assertEqual(processed[0].jsonbundler.json, response.get_json())
self.assertEqual(processed[0], response.get_json())
self.assertEqual(42, response.get_json()["switchable"]["answer"])

def test_a_post_with_a_matching_etag_is_refused(self):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ def get(self, key):
restricted properties, saying so, or where the data has no value
for it, with the message the missing property service gives
"""


self._check_readable(key)
if hasattr(self.flow_element, "restricted_property_keys"):

if key.lower() not in self.flow_element.restricted_property_keys:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,13 @@ def test_an_engine_without_a_cache_reuses_its_instance(self):
with process(pipeline, "first") as flowdata:
first = flowdata.pooled
with process(pipeline, "second") as flowdata:
self.assertIs(first, flowdata.pooled)
self.assertIsNot(first, flowdata.pooled)
self.assertEqual("second", flowdata.pooled.get("name"))
# The reference kept from the first request refuses reads
# rather than reading the second request's values.
with self.assertRaises(Exception) as caught:
first.get("name")
self.assertIn("has been closed", str(caught.exception))


if __name__ == "__main__":
Expand Down
Loading