How to apply ascending ID parameter to thousands of multiple module types - omnet++

Suppose I have a simple module Client defined in Client.ned along with two subclassed simple modules:
simple Client
{
parameters:
volatile int clientId;
}
simple ClientA extends Client
{
}
simple ClientB extends Client
{
}
Now what I wish to do is define a network Network with 1000 ClientA instances and 1000 Client 2 instances as its submodules. I would like each instantiation to have a clientId one bigger than the last, i.e I would like the clientId parameter to ascend with each instantiation. For example, suppose we have the following Network.ned file:
network Network
{
submodules:
clientA[1000]: ClientA {
clientId = index;
};
clientB[1000]: ClientB {
clientId = 1000 + index;
}
}
What I'm looking for is a general approach, where we don't know the number of clients that are to be instantiated beforehand or even the number of client subclasses, just that if there is an instantiated Client of some sort, it should have a clientId parameter one larger than the last instantiation.

Remove volatile from clientId declaration in Client.ned and your solution will work properly.
The main purpose of using volatile is to guarantee returning a "fresh" value of a parameter when it is reading several times. In your network the clientId is constant, so the volatile is not necessary. The side-effect of using volatile is problem with using index, and parentIndex.
Beside the above, one should be aware that using omnetpp.ini is a very convenient method of control the simulation. For example, your NED files may look like:
simple Client {
parameters:
int clientId;
}
simple ClientA extends Client { }
simple ClientB extends Client { }
network Network {
submodules:
clientA[1000]: ClientA;
clientB[1000]: ClientB;
}
And the parameters may be set in omnetpp.ini:
**.clientA[*].clientId = index()
**.clientB[*].clientId = 1000 + index()
EDIT
When the number of clients is not known sizeof() method may be used to determine this number:
**.clientA[*].clientId = index()
**.clientB[*].clientId = sizeof(clientA) + index()

Since OMNeT++'s simulator assigns an ascending ID's to every module and submodule, utilizing getId(), getIndex(), getVectorSize(), and getParentModule() allows me to access this info for each module.

Related

Is there known way to add new syntax features to Protobuf?

Protobuf provides service keyword that defines rpc-interface of one application.
I also want to use concept of entity which means that is part of service (one service contains multiple entities). Each entity type has own unique identifier that gives possibility to address different entities in service.
I would like to use proto like this
message UserReq {
string username = 1;
string password = 2;
}
message RegReq {
uint8 result_code = 1;
}
message RemoteEntityInterface
{
MyEntity entity = 1;
}
message GiveItemResult
{
uint8 result_code = 1;
}
service MyService {
rpc RegisterUser (UserReq) returns (RegReq) {}
rpc Login(UserReq) returns (RemoteEntityInterface) {}
}
entity MyEntity
{
rpc GiveItem (GiveItemReq) returns (GiveItemResult) {}
}
As you can see in example, I used unknown for protobuf keyword entity, this keyword means that MyService can return the interface to some remote object (MyEntity) by using Login remote method.
What are the ways to do this? (maybe write plugin or known way to modify source code of protobuf). Or maybe there are more flexible solutions than protobuf?
I also would like to use multiple parameters per one rpc; adding java-like attributes to rpc; service and entity; and data-model for entity (variables/fields) to add real-time replication support from entity to another service.
I think it is very flexible for services in game-development.
The only official way to extend .proto syntax is to define custom options.
For example, you could have something like:
extend google.protobuf.ServiceOptions {
optional bool is_entity = 123456;
}
service MyEntity
{
option (is_entity) = true;
rpc GiveItem (GiveItemReq) returns (GiveItemResult) {}
}
The default code generator will not do anything special with this option, but you can access it from your own code and from a protoc plugin if you write one.

Omnet++ simple wireless node

Iam trying to create simple wireless node for MANET network which can send messages to other nodes in range. Solutions implemented in INET also contains other layers like IP, transport, application which i dont need.
Iam new to omnet++ so iam struggling a bit. I was thinking of creating whole own node with RadioIn input, but i dont know how to implement only in range communication and i will also need node mobility.
Other solutions would be to use only Radiomedium from INET framework but i dont know how to do it.
Can someone please give me some begginer tips how to achieve my goal? As i said i simply need to create mobile host which can send a defined message to all other hosts in range.
EDIT: I tried to take IdealRadioMedium and create my simple module and connect to it. Here is the NED File.
import inet.physicallayer.common.packetlevel.Radio;
import inet.common.figures.DelegateSignalConfigurator;
import inet.networklayer.configurator.ipv4.IPv4NetworkConfigurator;
import inet.node.inet.INetworkNode;
import inet.node.inet.WirelessHost;
import inet.physicallayer.contract.packetlevel.IRadioMedium;
import inet.visualizer.integrated.IntegratedCanvasVisualizer;
import inet.linklayer.contract.IWirelessNic;
import inet.networklayer.common.InterfaceTable;
simple Txc1
{
gates:
input in;
output out;
}
module Pokusny
{
parameters:
#display("i=device/wifilaptop");
int numRadios = default(1);
#networkNode;
gates:
input radioIn[numRadios] #directIn;
submodules:
mynode: Txc1;
wlan[numRadios]: <default("Ieee80211Nic")> like IWirelessNic {
parameters:
#display("p=216,406,row,60;q=queue");
}
interfaceTable: InterfaceTable {
parameters:
#display("p=53,300;is=s");
}
connections allowunconnected:
for i=0..sizeof(radioIn)-1 {
radioIn[i] --> { #display("m=s"); } --> wlan[i].radioIn;
wlan[i].upperLayerOut --> mynode.in;
wlan[i].upperLayerIn <-- mynode.out;
}
}
network WirelessC
{
parameters:
string hostType = default("WirelessHost");
string mediumType = default("IdealRadioMedium");
#display("bgb=650,500;bgg=100,1,grey95");
#figure[title](type=label; pos=0,-1; anchor=sw; color=darkblue);
#figure[rcvdPkText](type=indicatorText; pos=420,20; anchor=w; font=,20; textFormat="packets received: %g"; initialValue=0);
#statistic[rcvdPk](source=hostB_rcvdPk; record=figure(count); targetFigure=rcvdPkText);
#signal[hostB_rcvdPk];
#delegatesignal[rcvdPk](source=hostB.udpApp[0].rcvdPk; target=hostB_rcvdPk);
submodules:
visualizer: IntegratedCanvasVisualizer {
#display("p=580,125");
}
configurator: IPv4NetworkConfigurator {
#display("p=580,200");
}
radioMedium: <mediumType> like IRadioMedium {
#display("p=580,275");
}
//figureHelper: DelegateSignalConfigurator {
// #display("p=580,350");
//}
hostA: Pokusny {
#display("p=50,325");
}
hostB: Pokusny {
#display("p=450,325");
}
}
Txc1.cc
class Txc1 : public cSimpleModule
{
protected:
// The following redefined virtual function holds the algorithm.
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
};
// The module class needs to be registered with OMNeT++
Define_Module(Txc1);
void Txc1::initialize()
{
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
void Txc1::handleMessage(cMessage *msg)
{
send(msg, "out"); // send out the message
}
And .ini file
network = WirelessC
sim-time-limit = 25s
*.host*.wlan[0].typename = "IdealWirelessNic"
*.host*.wlan[0].mac.useAck = false
*.host*.wlan[0].mac.fullDuplex = false
*.host*.wlan[0].radio.transmitter.communicationRange = 500m
*.host*.wlan[0].radio.receiver.ignoreInterference = true
*.host*.**.bitrate = 1Mbps
When i run the simulation it asks for Interfacetable parameter which i dont know what to type there becuse i havent found it in traversing functioning code ( I had to add it because it throws error that is missing if its not as submodule). Now iam getting
getCointainingNode() node module not found it should have a property name networkNode for module WirelessC.interfaceTable in module .... durint network initialization
EDIT: I added networknode as parameter and now i got Module not found on path '.mobility' defined by par WirelessC.hostA.wlan[0].radio.antenna.Mobilitymodule in module inte::physicallayer:IsotropicAntenna during network initialization
I'd like to point you to the wireless tutorial for INET: https://omnetpp.org/doc/inet/api-current/tutorials/wireless/
It starts with exactly your problem. The only thing left, is to replace the standard UDP host with a host using no protocol at all, maybe even implementing your own. The whole wireless part is explained in the tutorial.
If you want to check the source files for the used modules you need to walk down the chain of dependency since every compound NED module will (at one point) contain simple modules implemented in C++.
E.g. the module which is responsible for distributing the signals is IdealRadioMedium using RadioMedium. Now you need to find the Node implementation directly communicating with this module.
Starting with the WirelessHost used in the tutorial the underlying modules are
StandardHost -> ApplicationLayerNodeBase -> LinkLayerNodeBase with the later being the first one using actually implemented submodules.
The network adapter used is configured in the omnet.ini with *.host*.wlan[0].typename = "IdealWirelessNic". This module relies on Radio.
With all that found out you just need to look for API calls from Radio.cc made to RadioMedium.cc and you found the actual code responsible for sending data.
Understanding that chain of inheritance you can even hook in with your custom module at a level you find fitting. For example just implementing your own LinklayerNodeBase module.
If you are going for wireless communication and mobility, INET will still be the best framework to use.
Check out the INET Wireless Tutorial. It basically covers all the steps that you need to build a small scenario with moving nodes that communicate wirelessly.

How to provide read access to implementers of a protocol while others have write access in Swift

I'd like to provide read access for certain properties to all classes/structs that implement a protocol while client classes of the protocol are allowed read+write access. Is there a way to do this in Swift?
protocol WheelsProtocol {
var count: Int {get set}
}
struct Car: WheelsProtocol {
var count: Int = 0
func checkTirePressure() {
// Here, we will iterate over the count of wheels but we should
// not allow the number of wheels to be changed
}
}
struct CarFactory {
var wheels: WheelsProtocol
init(wheels: WheelsProtocol) {
self.wheels = wheels
}
mutating func configureVehicle() {
self.wheels.count = 4
}
}
What about a protocol for car makers and a different one for cars, something like
protocol MakesCars {
var wheelCount: Int {get set}
}
protocol HasWheels{
var wheelCount: Int { get }
}
struct Car: HasWheels {
let wheelCount: Int
init(wheelCount: Int) {
self.wheelCount = wheelCount
}
func checkTirePressure() {
// Here, we will iterate over the count of wheels but we should
// not allow the number of wheels to be changed
wheelCount = 5 //COMPILER ERROR
}
}
struct CarFactory: MakesCars {
...
}
The key is that you have to define a read-only property in the protocol as a var with { get } but in the object that adopts that protocol you have to put let and set it in an initializer.
There is not a way to limit access to a particular method in the way you're describing. From the documentation on Access Control:
Swift provides three different access levels for entities within your
code. These access levels are relative to the source file in which an
entity is defined, and also relative to the module that source file
belongs to.
Public access enables entities to be used within any source file from
their defining module, and also in a source file from another module
that imports the defining module. You typically use public access when
specifying the public interface to a framework.
Internal access enables entities to be used within any source file
from their defining module, but not in any source file outside of that
module. You typically use internal access when defining an app’s or a
framework’s internal structure.
Private access restricts the use of an entity to its own defining
source file. Use private access to hide the implementation details of
a specific piece of functionality.
To accomplish this, you would need to create a separate module (i.e., a Framework) and limit the writes to the internal scope and make the reads of the public scope.

Passing data to dependencies registered with Execution Context Scope lifetime in Simple Injector

Is there a way to pass data to dependencies registered with either Execution Context Scope or Lifetime Scope in Simple Injector?
One of my dependencies requires a piece of data in order to be constructed in the dependency chain. During HTTP and WCF requests, this data is easy to get to. For HTTP requests, the data is always present in either the query string or as a Request.Form parameter (and thus is available from HttpContext.Current). For WCF requests, the data is always present in the OperationContext.Current.RequestContext.RequestMessage XML, and can be parsed out. I have many command handler implementations that depend on an interface implementation that needs this piece of data, and they work great during HTTP and WCF scoped lifestyles.
Now I would like to be able to execute one or more of these commands using the Task Parallel Library so that it will execute in a separate thread. It is not feasible to move the piece of data out into a configuration file, class, or any other static artifact. It must initially be passed to the application either via HTTP or WCF.
I know how to create a hybrid lifestyle using Simple Injector, and already have one set up as hybrid HTTP / WCF / Execution Context Scope (command interfaces are async, and return Task instead of void). I also know how to create a command handler decorator that will start a new Execution Context Scope when needed. The problem is, I don't know how or where (or if I can) "save" this piece of data so that is is available when the dependency chain needs it to construct one of the dependencies.
Is it possible? If so, how?
Update
Currently, I have an interface called IProvideHostWebUri with two implementations: HttpHostWebUriProvider and WcfHostWebUriProvider. The interface and registration look like this:
public interface IProvideHostWebUri
{
Uri HostWebUri { get; }
}
container.Register<IProvideHostWebUri>(() =>
{
if (HttpContext.Current != null)
return container.GetInstance<HttpHostWebUriProvider>();
if (OperationContext.Current != null)
return container.GetInstance<WcfHostWebUriProvider>();
throw new NotSupportedException(
"The IProvideHostWebUri service is currently only supported for HTTP and WCF requests.");
}, scopedLifestyle); // scopedLifestyle is the hybrid mentioned previously
So ultimately unless I gut this approach, my goal would be to create a third implementation of this interface which would then depend on some kind of context to obtain the Uri (which is just constructed from a string in the other 2 implementations).
#Steven's answer seems to be what I am looking for, but I am not sure how to make the ITenantContext implementation immutable and thread-safe. I don't think it will need to be made disposable, since it just contains a Uri value.
So what you are basically saying is that:
You have an initial request that contains some contextual information captured in the request 'header'.
During this request you want to kick off a background operation (on a different thread).
The contextual information from the initial request should stay available when running in the background thread.
The short answer is that Simple Injector does not contain anything that allows you to do so. The solution is in creating a piece of infrastructure that allows moving this contextual information along.
Say for instance you are processing command handlers (wild guess here ;-)), you can specify a decorator as follows:
public class BackgroundProcessingCommandHandlerDecorator<T> : ICommandHandler<T>
{
private readonly ITenantContext tenantContext;
private readonly Container container;
private readonly Func<ICommandHandler<T>> decorateeFactory;
public BackgroundProcessingCommandHandlerDecorator(ITenantContext tenantContext,
Container container, Func<ICommandHandler<T>> decorateeFactory) {
this.tenantContext = tenantContext;
this.container = container;
this.decorateeFactory = decorateeFactory;
}
public void Handle(T command) {
// Capture the contextual info in a local variable
// NOTE: This object must be immutable and thread-safe.
var tenant = this.tenantContext.CurrentTenant;
// Kick off a new background operation
Task.Factory.StartNew(() => {
using (container.BeginExecutionContextScope()) {
// Load a service that allows setting contextual information
var context = this.container.GetInstance<ITenantContextApplier>();
// Set the context for this thread, before resolving the handler
context.SetCurrentTenant(tenant);
// Resolve the handler
var decoratee = this.decorateeFactory.Invoke();
// And execute it.
decoratee.Handle(command);
}
});
}
}
Note that in the example I make use of an imaginary ITenantContext abstraction, assuming that you need to supply the commands with information about the current tenant, but any other sort of contextual information will obviously do as well.
The decorator is a small piece of infrastructure that allows you to process commands in the background and it is its responsibility to make sure all the required contextual information is moved to the background thread as well.
To be able to do this, the contextual information is captured and used as a closure in the background thread. I created an extra abstraction for this, namely ITenantContextApplier. Do note that the tenant context implementation can implement both the ITenantContext and the ITenantContextApplier interface. If however you define the ITenantContextApplier in your composition root, it will be impossible for the application to change the context, since it does not have a dependency on ITenantContextApplier.
Here's an example:
// Base library
public interface ITenantContext { }
// Business Layer
public class SomeCommandHandler : ICommandHandler<Some> {
public SomeCommandHandler(ITenantContext context) { ... }
}
// Composition Root
public static class CompositionRoot {
// Make the ITenantContextApplier private so nobody can see it.
// Do note that this is optional; there's no harm in making it public.
private interface ITenantContextApplier {
void SetCurrentTenant(Tenant tenant);
}
private class AspNetTenantContext : ITenantContextApplier, ITenantContext {
// Implement both interfaces
}
private class BackgroundProcessingCommandHandlerDecorator<T> { ... }
public static Container Bootstrap(Container container) {
container.RegisterPerWebRequest<ITenantContext, AspNetTenantContext>();
container.Register<ITenantContextApplier>(() =>
container.GetInstance<ITenantContext>() as ITenantContextApplier);
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(BackgroundProcessingCommandHandlerDecorator<>));
}
}
A different approach would be to just make the complete ITenantContext available to the background thread, but to be able to pull this off, you need to make sure that:
The implementation is immutable and thus thread-safe.
The implementation doesn't require disposing, because it will typically be disposed when the original request ends.

Domain Driven Design - complex validation of commands across different aggregates

I've only began with DDD and currently trying to grasp the ways to do different things with it. I'm trying to design it using asynchronous events (no event-sourcing yet) with CQRS. Currently I'm stuck with validation of commands. I've read this question: Validation in a Domain Driven Design , however, none of the answers seem to cover complex validation across different aggregate roots.
Let's say I have these aggregate roots:
Client - contains list of enabled services, each service can have a value-object list of discounts and their validity.
DiscountOrder - an order to enable more discounts on some of the services of given client, contains order items with discount configuration.
BillCycle - each period when bills are generated is described by own billcycle.
Here's the usecase:
Discount order can be submitted. Each new discount period in discount order should not overlap with any of BillCycles. No two discounts of same type can be active at the same time on one service.
Basically, using Hibernate in CRUD style, this would look something similar to (java code, but question is language-agnostic):
public class DiscountProcessor {
...
#Transactional
public void processOrder(long orderId) {
DiscOrder order = orderDao.get(orderId);
BillCycle[] cycles = billCycleDao.getAll();
for (OrderItem item : order.getItems()) {
//Validate billcycle overlapping
for (BillCycle cycle : cycles) {
if (periodsOverlap(cycle.getPeriod(), item.getPeriod())) {
throw new PeriodsOverlapWithBillCycle(...);
}
}
//Validate discount overlapping
for (Discount d : item.getForService().getDiscounts()) {
if (d.getType() == item.getType() && periodsOverlap(d.getPeriod(), item.getPeriod())) {
throw new PeriodsOverlapWithOtherItems(...);
}
}
//Maybe some other validations in future or stuff
...
}
createDiscountsForOrder(order);
}
}
Now here are my thoughts on implementation:
Basically, the order can be in three states: "DRAFT", "VALIDATED" and "INVALID". "DRAFT" state can contain any kind of invalid data, "VALIDATED" state should only contain valid data, "INVALID" should contain invalid data.
Therefore, there should be a method which tries to switch the state of the order, let's call it order.validate(...). The method will perform validations required for shift of state (DRAFT -> VALIDATED or DRAFT -> INVALID) and if successful - change the state and transmit a OrderValidated or OrderInvalidated events.
Now, what I'm struggling with, is the signature of said order.validate(...) method. To validate the order, it requires several other aggregates, namely BillCycle and Client. I can see these solutions:
Put those aggregates directly into the validate method, like
order.validateWith(client, cycles) or order.validate(new
OrderValidationData(client, cycles)). However, this seems a bit
hackish.
Extract the required information from client and cycle
into some kind of intermediate validation data object. Something like
order.validate(new OrderValidationData(client.getDiscountInfos(),
getListOfPeriods(cycles)).
Do validation in a separate service
method which can do whatever it wants with whatever aggregates it
wants (basically similar to CRUD example above). However, this seems
far from DDD, as method order.validate() will become a dummy state
setter, and calling this method will make it possible to bring an
order unintuitively into an corrupted state (status = "valid" but
contains invalid data because nobody bothered to call validation
service).
What is the proper way to do it, and could it be that my whole thought process is wrong?
Thanks in advance.
What about introducing a delegate object to manipulate Order, Client, BillCycle?
class OrderingService {
#Injected private ClientRepository clientRepository;
#Injected private BillingRepository billRepository;
Specification<Order> validSpec() {
return new ValidOrderSpec(clientRepository, billRepository);
}
}
class ValidOrderSpec implements Specification<Order> {
#Override public boolean isSatisfied(Order order) {
Client client = clientRepository.findBy(order.getClientId());
BillCycle[] billCycles = billRepository.findAll();
// validate here
}
}
class Order {
void validate(ValidOrderSpecification<Order> spec) {
if (spec.isSatisfiedBy(this) {
validated();
} else {
invalidated();
}
}
}
The pros and cons of your three solutions, from my perspective:
order.validateWith(client, cycles)
It is easy to test the validation with order.
#file: OrderUnitTest
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build();
subject.validateWith(client, cycles);
assertThat(order.getStatus(), is(VALID));
}
so far so good, but there seems to be some duplicate test code for DiscountOrderProcess.
#file: DiscountProcessor
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build()
DiscountProcessor subject = ...
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
given(orderRepository).findBy(order.getId()).thenReturn(order);
subject.processOrder(order.getId());
assertThat(order.getStatus(), is(VALID));
}
#or in mock style
#Test public void should_change_to_valid_when_xxxx() {
Client client = mock(Client.class)
BillCycle[] cycles = array(mock(BillCycle.class))
Order order = mock(Order.class)
DiscountProcessor subject = ...
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
given(orderRepository).findBy(order.getId()).thenReturn(order);
given(client).....
given(cycle1)....
subject.processOrder(order.getId());
verify(order).validated();
}
order.validate(new OrderValidationData(client.getDiscountInfos(),
getListOfPeriods(cycles))
Same as the above one, you still need to prepare data for both OrderUnitTest and discountOrderProcessUnitTest. But I think this one is better as order is not tightly coupled with Client and BillCycle.
order.validate()
Similar to my idea if you keep validation in the domain layer. Sometimes it is just not any entity's responsibility, consider domain service or specification object.
#file: OrderUnitTest
#Test public void should_change_to_valid_when_xxxx() {
Client client = new ClientFixture()...build()
BillCycle[] cycles = new BillCycleFixture()...build()
Order order = new OrderFixture()...build();
Specification<Order> spec = new ValidOrderSpec(clientRepository, cycleRepository);
given(clientRepository).findBy(client.getId()).thenReturn(client);
given(cycleRepository).findAll().thenReturn(cycles);
subject.validate(spec);
assertThat(order.getStatus(), is(VALID));
}
#file: DiscountProcessor
#Test public void should_change_to_valid_when_xxxx() {
Order order = new OrderFixture()...build()
Specification<Order> spec = mock(ValidOrderSpec.class);
DiscountProcessor subject = ...
given(orderingService).validSpec().thenReturn(spec);
given(spec).isSatisfiedBy(order).thenReturn(true);
given(orderRepository).findBy(order.getId()).thenReturn(order);
subject.processOrder(order.getId());
assertThat(order.getStatus(), is(VALID));
}
Do the 3 possible states reflect your domain or is that just extrapolation ? I'm asking because your sample code doesn't seem to change Order state but throw an exception when it's invalid.
If it's acceptable for the order to stay DRAFT for a short period of time after being submitted, you could have DiscountOrder emit a DiscountOrderSubmitted domain event. A handler catches the event and (delegates to a Domain service that) examines if the submit is legit or not. It would then issue a ChangeOrderState command to make the order either VALIDATED or INVALID.
You could even suppose that the change is legit by default and have processOrder() directly take it to VALIDATED, until proven otherwise by a subsequent INVALID counter-order given by the validation service.
This is not much different from your third solution or Hippoom's one though, except every step of the process is made explicit with its own domain event. I guess that with your current aggregate design you're doomed to have a third party orchestrator (as un-DDD and transaction script-esque as it may sound) that controls the process, since the DiscountOrder aggregate doesn't have native access to all information to tell if a given transformation is valid or not.

Resources