def finish(self):
     event = ExampleEntity.Finished(
         entity_id=self.id,
         entity_version=self.version,
     )
     self._apply(event)
     publish(event)
Example #2
0
 def log_message(self, message: str) -> "MessageLogged":
     assert isinstance(message, str)
     bucket_id = make_timebucket_id(self.name, decimaltimestamp(),
                                    self.bucket_size)
     event = MessageLogged(originator_id=bucket_id, message=message)
     publish([event])
     return event
Example #3
0
def register_call_dependents(call_id, dependents):
    created_event = CallDependents.Created(entity_id=call_id,
                                           dependents=dependents)
    call_dependents = CallDependents.mutator(event=created_event)
    # print("Number of call dependents:", len(dependents))
    publish(created_event)
    return call_dependents
def register_simulated_price_requirements(call_requirement_id, requirements):
    assert isinstance(requirements, list), type(requirements)
    event = SimulatedPriceRequirements.Created(entity_id=call_requirement_id,
                                               requirements=requirements)
    entity = SimulatedPriceRequirements.mutator(event=event)
    publish(event)
    return entity
Example #5
0
    def __publish_to_subscribers__(self, events: Sequence[TDomainEvent]) -> None:
        """
        Actually dispatches given event to publish-subscribe mechanism.

        :param events: list of domain events
        """
        publish(events)
Example #6
0
    def __publish_to_subscribers__(self, event):
        """
        Actually dispatches given event to publish-subscribe mechanism.

        :param event: domain event or list of events
        """
        publish(event)
def register_new_node(suffix_node_id=None, string_id=None, is_leaf=False, is_root=False):
    """Factory method, registers new node.
    """
    # Make a unique ID.
    node_id = uuid4().hex

    # Instantiate a Created event.
    created_event = SuffixTreeNode.Created(
        entity_id=node_id,
        suffix_node_id=suffix_node_id,
        string_id=string_id,
        is_leaf=is_leaf,
        is_root=is_root,
    )

    # Make the new Node entity.
    new_node = SuffixTreeNode.mutate(event=created_event)

    # Publish the Created event.
    publish(created_event)

    # Also create a new child collection, to
    # avoid any contention around this event.
    register_new_node_child_collection(node_id)

    # Return the new node.
    return new_node
def register_new_node_child_collection(node_id):
    """Factory method, registers new node child collection.
    """
    event = SuffixTreeNodeChildCollection.Created(entity_id=node_id, )
    entity = SuffixTreeNodeChildCollection.mutate(event=event)
    publish(event)
    return entity
def register_new_stringid_collection(node_id):
    """Factory method, registers new collection of string IDs.
    """
    event = StringidCollection.Created(entity_id=node_id, )
    entity = StringidCollection.mutate(event=event)
    publish(event)
    return entity
def register_new_node(suffix_node_id=None, string_id=None, is_leaf=False, is_root=False):
    """Factory method, registers new node.
    """
    # Make a unique ID.
    node_id = uuid4().hex

    # Instantiate a Created event.
    created_event = SuffixTreeNode.Created(
        entity_id=node_id,
        suffix_node_id=suffix_node_id,
        string_id=string_id,
        is_leaf=is_leaf,
        is_root=is_root,
    )

    # Make the new Node entity.
    new_node = SuffixTreeNode.mutate(event=created_event)

    # Publish the Created event.
    publish(created_event)

    # Also create a new child collection, to
    # avoid any contention around this event.
    register_new_node_child_collection(node_id)

    # Return the new node.
    return new_node
Example #11
0
def register_market_calibration(price_process_name, calibration_params):
    created_event = MarketCalibration.Created(entity_id=create_uuid4(),
                                              price_process_name=price_process_name,
                                              calibration_params=calibration_params)
    call_result = MarketCalibration.mutator(event=created_event)
    publish(created_event)
    return call_result
Example #12
0
def evaluate_dsl_expr(dsl_expr, simulation_id, interest_rate, present_time,
                      simulated_value_dict, perturbation_dependencies,
                      dependency_results, path_count, perturbation_factor,
                      periodisation, estimated_cost_of_expr, observation_date,
                      is_double_sided_deltas, involved_market_names):

    evaluation_kwds = {
        'simulated_value_dict': simulated_value_dict,
        'simulation_id': simulation_id,
        'interest_rate': interest_rate,
        'perturbation_factor': perturbation_factor,
        'observation_date': observation_date,
        'present_time': present_time,
        'involved_market_names': involved_market_names,
        'path_count': path_count,
        'periodisation': periodisation,
    }

    result_value = None
    perturbed_values = {}

    # Decide perturbation names.
    perturbation_names = perturbation_dependencies
    if is_double_sided_deltas:
        perturbation_names += ['-' + p for p in perturbation_dependencies]

    for perturbation_name in [''] + perturbation_names:

        evaluation_kwds['active_perturbation'] = perturbation_name

        # Initialise namespace with the dependency values.
        dependency_values = {}
        for stub_id in dependency_results.keys():
            dependency_result = dependency_results[stub_id]
            try:
                dependency_value = dependency_result.perturbed_values[
                    perturbation_name]
            except KeyError:
                dependency_value = dependency_result.result_value
            dependency_values[stub_id] = dependency_value

        # Prepare the namespace with the values the expression depends on.
        dsl_locals = DslNamespace(dependency_values)

        # Substitute Name elements, to give something that can be evaluated.
        dsl_expr_resolved = dsl_expr.substitute_names(dsl_locals)

        # Evaluate the expression.
        expr_value = dsl_expr_resolved.evaluate(**evaluation_kwds)
        if not perturbation_name:
            assert result_value is None
            result_value = expr_value
        else:
            perturbed_values[perturbation_name] = expr_value

        # Publish result value computed event.
        publish(ResultValueComputed(estimated_cost_of_expr))

    return result_value, perturbed_values
Example #13
0
 def _change_attribute(self, name, value):
     self._assert_not_discarded()
     event = self.AttributeChanged(name=name,
                                   value=value,
                                   entity_id=self._id,
                                   entity_version=self._version)
     self._apply(event)
     publish(event)
Example #14
0
 def publish_prompt(self):
     prompt = Prompt(self.name, self.pipeline_id)
     try:
         publish(prompt)
     except PromptFailed:
         raise
     except Exception as e:
         raise PromptFailed("{}: {}".format(type(e), str(e)))
Example #15
0
def start_new_log(name, bucket_size):
    if bucket_size not in BUCKET_SIZES:
        raise ValueError("Bucket size not supported: {}. Must be one of: {}"
                         "".format(bucket_size, BUCKET_SIZES.keys()))
    event = Log.Started(entity_id=name, name=name, bucket_size=bucket_size)
    entity = Log.mutate(event=event)
    publish(event)
    return entity
Example #16
0
def register_call_dependencies(call_id, dependencies):
    "Registers things needed by this call."
    created_event = CallDependencies.Created(entity_id=call_id, dependencies=dependencies)
    call_dependencies = CallDependencies.mutator(event=created_event)
    # print("Number of call dependencies:", len(dependencies))

    publish(created_event)
    return call_dependencies
Example #17
0
def register_new_node(suffix_node_id=None):
    """Factory method, registers new node.
    """
    node_id = uuid4()
    event = Node.Created(originator_id=node_id, suffix_node_id=suffix_node_id)
    entity = Node.mutate(event=event)
    publish([event])
    return entity
Example #18
0
def register_call_requirement(call_id, dsl_source, effective_present_time):
    created_event = CallRequirement.Created(
        entity_id=call_id,
        dsl_source=dsl_source,
        effective_present_time=effective_present_time)
    call_requirement = CallRequirement.mutator(event=created_event)
    publish(created_event)
    return call_requirement
Example #19
0
def register_market_calibration(price_process_name, calibration_params):
    created_event = MarketCalibration.Created(
        entity_id=create_uuid4(),
        price_process_name=price_process_name,
        calibration_params=calibration_params)
    call_result = MarketCalibration.mutator(event=created_event)
    publish(created_event)
    return call_result
def register_new_node(suffix_node_id=None):
    """Factory method, registers new node.
    """
    node_id = uuid4().hex
    event = Node.Created(originator_id=node_id, suffix_node_id=suffix_node_id)
    entity = Node.mutate(event=event)
    publish(event)
    return entity
def register_new_node_child_collection(node_id):
    """Factory method, registers new node child collection.
    """
    event = SuffixTreeNodeChildCollection.Created(
        entity_id=node_id,
    )
    entity = SuffixTreeNodeChildCollection.mutate(event=event)
    publish(event)
    return entity
def register_contract_specification(source_code, observation_date=None):
    created_event = ContractSpecification.Created(
        entity_id=create_uuid4(),
        source_code=source_code,
        observation_date=observation_date,
    )
    contract_specification = ContractSpecification.mutator(event=created_event)
    publish(created_event)
    return contract_specification
def register_new_stringid_collection(node_id):
    """Factory method, registers new collection of string IDs.
    """
    event = StringidCollection.Created(
        entity_id=node_id,
    )
    entity = StringidCollection.mutate(event=event)
    publish(event)
    return entity
 def add_child(self, child_node_id, edge_len):
     event = SuffixTreeNodeChildCollection.ChildNodeAdded(
         entity_id=self.id,
         entity_version=self.version,
         child_node_id=child_node_id,
         edge_len=edge_len,
     )
     self._apply(event)
     publish(event)
Example #25
0
def register_call_dependencies(call_id, dependencies):
    "Registers things needed by this call."
    created_event = CallDependencies.Created(entity_id=call_id,
                                             dependencies=dependencies)
    call_dependencies = CallDependencies.mutator(event=created_event)
    # print("Number of call dependencies:", len(dependencies))

    publish(created_event)
    return call_dependencies
Example #26
0
def register_call_requirement(call_id, dsl_source, effective_present_time):
    created_event = CallRequirement.Created(
        entity_id=call_id,
        dsl_source=dsl_source,
        effective_present_time=effective_present_time
    )
    call_requirement = CallRequirement.mutator(event=created_event)
    publish(created_event)
    return call_requirement
Example #27
0
 def remove_item(self, item):
     self._assert_not_discarded()
     event = self.ItemRemoved(
         entity_id=self.id,
         entity_version=self._version,
         item=item,
     )
     self._apply(event)
     publish(event)
Example #28
0
def register_new_example(a, b):
    """
    Factory method for example entities.
    """
    entity_id = uuid.uuid4().hex
    event = Example.Created(entity_id=entity_id, a=a, b=b)
    entity = Example.mutator(event=event)
    publish(event=event)
    return entity
Example #29
0
def register_contract_specification(source_code, observation_date=None):
    created_event = ContractSpecification.Created(
        entity_id=create_uuid4(),
        source_code=source_code,
        observation_date=observation_date,
    )
    contract_specification = ContractSpecification.mutator(event=created_event)
    publish(created_event)
    return contract_specification
Example #30
0
 def publish_prompt(self, head_notification_id=None):
     prompt = PromptToPull(self.name, self.pipeline_id,
                           head_notification_id)
     try:
         publish(prompt)
     except PromptFailed:
         raise
     except Exception as e:
         raise PromptFailed("{}: {}".format(type(e), str(e)))
 def test_evaluation_subscriber(self, evaluate_contract_in_series):
     # Check that when an event is published, the domain service is called.
     contract_valuation_created = ContractValuation.Created(
         entity_id='1',
         market_calibration_id='1',
     )
     self.assertEqual(evaluate_contract_in_series.call_count, 0)
     publish(contract_valuation_created)
     self.assertEqual(evaluate_contract_in_series.call_count, 1)
Example #32
0
 def beat_heart(self, number_of_beats=1):
     self._assert_not_discarded()
     events = []
     while number_of_beats > 0:
         event = self.Heartbeat(entity_id=self._id, entity_version=self._version)
         events.append(event)
         self._apply(event)
         number_of_beats -= 1
     publish(events)
 def add_child(self, child_node_id, edge_len):
     event = SuffixTreeNodeChildCollection.ChildNodeAdded(
         entity_id=self.id,
         entity_version=self.version,
         child_node_id=child_node_id,
         edge_len=edge_len,
     )
     self._apply(event)
     publish(event)
Example #34
0
 def append_message(self, message):
     assert isinstance(message, six.string_types)
     bucket_id = make_timebucket_id(self.name, time(), self.bucket_size)
     event = MessageLogged(
         originator_id=bucket_id,
         message=message,
     )
     publish(event)
     return event
def evaluate_dsl_expr(dsl_expr, simulation_id, interest_rate, present_time, simulated_value_dict,
                      perturbation_dependencies, dependency_results, path_count, perturbation_factor, periodisation,
                      estimated_cost_of_expr, observation_date, is_double_sided_deltas, involved_market_names):

    evaluation_kwds = {
        'simulated_value_dict': simulated_value_dict,
        'simulation_id': simulation_id,
        'interest_rate': interest_rate,
        'perturbation_factor': perturbation_factor,
        'observation_date': observation_date,
        'present_time': present_time,
        'involved_market_names': involved_market_names,
        'path_count': path_count,
        'periodisation': periodisation,
    }

    result_value = None
    perturbed_values = {}

    # Decide perturbation names.
    perturbation_names = perturbation_dependencies
    if is_double_sided_deltas:
        perturbation_names += ['-' + p for p in perturbation_dependencies]


    for perturbation_name in [''] + perturbation_names:

        evaluation_kwds['active_perturbation'] = perturbation_name

        # Initialise namespace with the dependency values.
        dependency_values = {}
        for stub_id in dependency_results.keys():
            dependency_result = dependency_results[stub_id]
            try:
                dependency_value = dependency_result.perturbed_values[perturbation_name]
            except KeyError:
                dependency_value = dependency_result.result_value
            dependency_values[stub_id] = dependency_value

        # Prepare the namespace with the values the expression depends on.
        dsl_locals = DslNamespace(dependency_values)

        # Substitute Name elements, to give something that can be evaluated.
        dsl_expr_resolved = dsl_expr.substitute_names(dsl_locals)

        # Evaluate the expression.
        expr_value = dsl_expr_resolved.evaluate(**evaluation_kwds)
        if not perturbation_name:
            assert result_value is None
            result_value = expr_value
        else:
            perturbed_values[perturbation_name] = expr_value

        # Publish result value computed event.
        publish(ResultValueComputed(estimated_cost_of_expr))

    return result_value, perturbed_values
 def publish_prompt(self, end_position=None):
     if end_position is not None:
         assert isinstance(end_position, six.integer_types), end_position
     prompt = Prompt(self.name, self.pipeline_id, end_position=end_position)
     try:
         publish(prompt)
     except PromptFailed:
         raise
     except Exception as e:
         raise PromptFailed("{}: {}".format(type(e), str(e)))
 def shorten(self, label, dest_node_id):
     self._assert_not_discarded()
     event = SuffixTreeEdge.Shortened(
         entity_id=self._id,
         entity_version=self._version,
         label=label,
         dest_node_id=dest_node_id,
     )
     self._apply(event)
     publish(event)
Example #38
0
    def test_published_events_are_appended_to_event_store(self):
        # Check the event store's append method has NOT been called.
        self.assertEqual(0, self.event_store.append.call_count)

        # Publish a (mock) domain event.
        domain_event = mock.Mock(spec=DomainEvent)
        publish(domain_event)

        # Check the append method HAS been called once with the domain event.
        self.event_store.append.assert_called_once_with(domain_event)
 def switch_child(self, old_node_id, new_node_id, new_edge_len):
     event = SuffixTreeNodeChildCollection.ChildNodeSwitched(
         entity_id=self.id,
         entity_version=self.version,
         old_node_id=old_node_id,
         new_node_id=new_node_id,
         new_edge_len=new_edge_len,
     )
     self._apply(event)
     publish(event)
 def shorten(self, label, dest_node_id):
     self._assert_not_discarded()
     event = SuffixTreeEdge.Shortened(
         entity_id=self._id,
         entity_version=self._version,
         label=label,
         dest_node_id=dest_node_id,
     )
     self._apply(event)
     publish(event)
    def test_published_events_are_appended_to_event_store(self):
        # Check the event store's append method has NOT been called.
        self.assertEqual(0, self.event_store.append.call_count)

        # Publish a (mock) domain event.
        domain_event = mock.Mock(spec=DomainEvent)
        publish(domain_event)

        # Check the append method HAS been called once with the domain event.
        self.event_store.append.assert_called_once_with(domain_event)
 def switch_child(self, old_node_id, new_node_id, new_edge_len):
     event = SuffixTreeNodeChildCollection.ChildNodeSwitched(
         entity_id=self.id,
         entity_version=self.version,
         old_node_id=old_node_id,
         new_node_id=new_node_id,
         new_edge_len=new_edge_len,
     )
     self._apply(event)
     publish(event)
Example #43
0
def register_simulated_price(market_simulation_id, market_name, fixing_date,
                             delivery_date, price_value):
    simulated_price_id = make_simulated_price_id(market_simulation_id,
                                                 market_name, fixing_date,
                                                 delivery_date)
    created_event = SimulatedPrice.Created(entity_id=simulated_price_id,
                                           value=price_value)
    simulated_price = SimulatedPrice.mutator(event=created_event)
    publish(created_event)
    return simulated_price
Example #44
0
def create_new_example(foo='', a='', b=''):
    """
    Factory method for example entities.

    :rtype: Example
    """
    entity_id = uuid.uuid4()
    event = Example.Created(originator_id=entity_id, foo=foo, a=a, b=b)
    entity = Example._mutate(initial=None, event=event)
    publish(event=event)
    return entity
def register_new_allocation_source(a, b):
    """
    Factory method for Allocation Source entities.

    :rtype: AllocationSource
    """
    entity_id = uuid.uuid4().hex
    event = AllocationSource.Created(entity_id=entity_id, a=a, b=b)
    entity = AllocationSource.mutate(event=event)
    publish(event=event)
    return entity
Example #46
0
 def append_message(self, message, level='INFO'):
     assert isinstance(message, six.string_types)
     domain_event_id = create_domain_event_id()
     entity_bucket_id = make_bucket_id(self.name, timestamp_from_uuid(domain_event_id), self.bucket_size)
     event = MessageLogged(
         entity_id=entity_bucket_id,
         message=message,
         level=level,
     )
     publish(event)
     return event
def create_new_example(foo='', a='', b=''):
    """
    Factory method for example entities.

    :rtype: Example
    """
    entity_id = uuid.uuid4()
    event = Example.Created(originator_id=entity_id, foo=foo, a=a, b=b)
    entity = Example._mutate(initial=None, event=event)
    publish(event=event)
    return entity
def register_new_edge(edge_id, label, source_node_id, dest_node_id):
    """Factory method, registers new edge.
    """
    event = SuffixTreeEdge.Created(
        entity_id=edge_id,
        label=label,
        source_node_id=source_node_id,
        dest_node_id=dest_node_id,
    )
    entity = SuffixTreeEdge.mutate(event=event)
    publish(event)
    return entity
Example #49
0
def start_new_log(name, bucket_size):
    if bucket_size not in BUCKET_SIZES:
        raise ValueError("Bucket size not supported: {}. Must be one of: {}"
                         "".format(bucket_size, BUCKET_SIZES.keys()))
    event = Log.Started(
        entity_id=name,
        name=name,
        bucket_size=bucket_size
    )
    entity = Log.mutate(event=event)
    publish(event)
    return entity
Example #50
0
def register_call_requirement(call_id, dsl_source, present_time, contract_specification_id, cost):
    assert isinstance(present_time, (datetime.date, type(None))), present_time
    created_event = CallRequirement.Created(
        entity_id=call_id,
        dsl_source=dsl_source,
        present_time=present_time,
        contract_specification_id=contract_specification_id,
        cost=cost,
    )
    call_requirement = CallRequirement.mutator(event=created_event)
    publish(created_event)
    return call_requirement
 def save(self):
     """
     Publishes pending events for others in application.
     """
     batch_of_events = []
     try:
         while True:
             batch_of_events.append(self._pending_events.popleft())
     except IndexError:
         pass
     if batch_of_events:
         publish(batch_of_events)
def start_contract_valuation(contract_specification_id, market_simulation_id, periodisation, is_double_sided_deltas):
    contract_valuation_id = create_contract_valuation_id()
    contract_valuation_created = ContractValuation.Created(
        entity_id=contract_valuation_id,
        market_simulation_id=market_simulation_id,
        contract_specification_id=contract_specification_id,
        periodisation=periodisation,
        is_double_sided_deltas=is_double_sided_deltas,
    )
    contract_valuation = ContractValuation.mutator(event=contract_valuation_created)
    publish(contract_valuation_created)
    return contract_valuation
def register_new_edge(edge_id, first_char_index, last_char_index, source_node_id, dest_node_id):
    """Factory method, registers new edge.
    """
    event = Edge.Created(
        originator_id=edge_id,
        first_char_index=first_char_index,
        last_char_index=last_char_index,
        source_node_id=source_node_id,
        dest_node_id=dest_node_id,
    )
    entity = Edge.mutate(event=event)
    publish(event)
    return entity
Example #54
0
def register_market_simulation(market_calibration_id, market_names, fixing_dates, observation_date, path_count,
                               interest_rate):
    created_event = MarketSimulation.Created(entity_id=create_uuid4(),
                                             market_calibration_id=market_calibration_id,
                                             market_names=market_names,
                                             fixing_dates=fixing_dates,
                                             observation_date=observation_date,
                                             path_count=path_count,
                                             interest_rate=interest_rate,
                                             )
    call_result = MarketSimulation.mutator(event=created_event)
    publish(created_event)
    return call_result
def register_new_instance(atmo_id, name, username):
    """
    Factory method for Instance entities.

    :rtype: Instance
    """
    # Instead of generating a random entity_id, maybe we should generate a UUID from the atmo_id passed in?
    # entity_id = uuid.UUID(int=atmo_id, version=4).hex
    entity_id = uuid.uuid4().hex
    event = Instance.Created(entity_id=entity_id, atmo_id=atmo_id, name=name, username=username)
    entity = Instance.mutate(event=event)
    publish(event=event)
    return entity
def start_new_timebucketedlog(name, bucket_size=None):
    if bucket_size is None:
        bucket_size = 'year'
    if bucket_size not in BUCKET_SIZES:
        raise ValueError("Bucket size '{}' not supported, must be one of: {}"
                         "".format(bucket_size, BUCKET_SIZES.keys()))
    event = Timebucketedlog.Started(
        originator_id=name,
        name=name,
        bucket_size=bucket_size
    )
    entity = Timebucketedlog._mutate(initial=None, event=event)
    publish(event)
    return entity
 def test_simulation_subscriber(self, generate_simulated_prices):
     # Check that when an event is published, the domain service is called.
     market_simulation_created = MarketSimulation.Created(
         entity_id='1',
         market_calibration_id='1',
         market_names=[],
         fixing_dates=[],
         observation_date=datetime.date(2011, 1, 1,),
         path_count=2,
         interest_rate=2.5,
     )
     self.assertEqual(generate_simulated_prices.call_count, 0)
     publish(market_simulation_created)
     self.assertEqual(generate_simulated_prices.call_count, 1)
Example #58
0
def take_snapshot(entity, at_event_id):
    # Make the 'stored entity ID' for the entity, it is used as the Snapshot 'entity ID'.
    id_prefix = id_prefix_from_entity(entity)
    stored_entity_id = make_stored_entity_id(id_prefix, entity.id)

    # Create the snapshot event.
    snapshot = Snapshot(
        entity_id=stored_entity_id,
        domain_event_id=at_event_id,
        topic=topic_from_domain_class(entity.__class__),
        attrs=entity.__dict__.copy(),
    )
    publish(snapshot)

    # Return the event.
    return snapshot
Example #59
0
 def __setitem__(self, index, item):
     """
     Sets item in array, at given index.
     
     Won't overrun the end of the array, because
     the position is fixed to be less than base_size.
     """
     size = self.repo.array_size
     if size and index >= size:
         raise ArrayIndexError("Index is {}, but size is {}".format(index, size))
     event = ItemAssigned(
         originator_id=self.id,
         index=index,
         item=item,
     )
     publish(event)