vovanchello
vovanchello

Reputation: 319

How to generate Golang code from bytecode of some kind close to pseudocode programming languages in the domain of Event-Sourcing

I have many services, and each service has an entity that has the same interface:

type Entity interface{
  ApplyEvent(evt Event)
}

type Event interface{
  ID() ID
  Version() int
  Body() any
}

Each service owns only its own entities, however, because of this, I cannot access another entity unless I duplicate the code or import entities from the repository for another service.

Moreover, the ApplyEvent method simply changes the fields of the entity. For example

type Person struct{
  Name string
  Age int
}


func (p *Person) ApplyEvent(e Event){
  evt:= e.Body().(NameChangedEvent)
  p.Name = evt.NewName
}

In other words, the logic is always very simple and does not require concurrency execution.

I had the idea to try to study the use of some statically typed object-oriented languages adapted to this domain, or, if there are none, to twist the existing ones. Something like Solidity for smart contracts.

 pragma ...;


// Creating a aggregate
aggregate Person {

    name string;
    age int;
    
    function applyNameChanged(evt NameChangedEvent) public {
        name = evt.name
    };
}

// creating a event
event NameChangedEvent{
  name string;
}

This code is then compiled and Golang code is generated from its byte code.

Then tell me in which direction it is worth moving in this approach. Are there any ready-made solutions for this?

Upvotes: -3

Views: 35

Answers (1)

MJepbarov
MJepbarov

Reputation: 137

You can generate Go code for Event Sourcing using a simple DSL or code templates. One easy way is to create a config file (JSON, YAML) that defines your entities and events, then use Go's text/template package to generate the ApplyEvent methods automatically. You can run this with go generate during the build process. If you want more control, try to create a custom parser using tools like ANTLR or Pigeon, this will reduce code duplication and will keep services clean and maintainable.

I can try to show examples if you want.

Upvotes: 0

Related Questions