Dynamic business rules engine for ruby on rails - ruby-on-rails

I have an application which will require a "dynamic business rules" engine. Some of the business rules changes very frequently. Some of then applies for a limited set of business accounts. For example: my customer have a process where they qualify stores, based on their size, number of the sales person, number of products, location, etc. But he manages different account, and each account give different "weights" to each attribute.
How do I implement this engine using Ruby? I know Java has drools, but I find drools annoying and complex. And I prefer not having to use JRuby...
Regards,
Rubem

If you're sure a rule engine is what you need, you will need to find one you can use in Ruby. A quick Google search brought up Rools (http://rools.rubyforge.org/) and Ruby Rules (http://xircles.codehaus.org/projects/ruby-rules). I'm not sure of the status of either project though. Using JRuby with Drools might be your best bet but then again, I'm a Java developer and a big Drools advocate. :)
Without knowing all the details, it's a little hard to say how that should be implemented. It also depends on how you want the rules to be updated. One approach is to write a collection of rules similar to this: "if a store exists with more than 50 sales people and the store hasn't had its weight updated to reflect that, then update the store's weight." However, in some way you could compare that to hardcoding.
A better approach might be to create Weight objects with criteria that need to be met for the weight to apply. Then you could write one rule that matches on both Weights and Stores: "if a Store exists that matches a Weight's criteria and the Store doesn't already have that Weight assigned to it, then add the Weigh to the Store." Then the business folks could just create and update Weights, possibly in a web front-ended database, instead of maintaining rules.

Related

Zanzibar doubts about Tuple + Check Api. (authzed/spicedb)

We currently have a home grown authz system in production that uses opa/rego policy engine as core for decision making(close to what netflix done). We been looking at Zanzibar rebac model to replace our opa/policy based decision engine, and AuthZed got our attention. Further looking at AuthZed, we like the idea of defining a schema of "resource + subject" types and their relations (like OOP model). We like the simplicity of using a social-graph between resource & subject to answer questions. But the more we dig-in and think about real usage patterns, we get more questions and missing clarity in some aspects. I put down those thoughts below, hope it's not confusing...
[Doubts/Questions]
[tuple-data] resource data/metadata must be continuously added into the authz-system in the form of tuple data.
e.g. doc{org,owner} must be added as tuple to populate the relation in the decision-graph. assume, i'm a CMS system, am i expected to insert(or update) the authz-engine(tuple) for for every single doc created in my cms system for lifetime?.
resource-owning applications are kept in hook(responsible) for continuous keep-it-current updates.
how about old/stale relation-data(tuples) - authz-engine don't know they are stale or not...app's burnded to tidy it?.
[check-api] - autzh check is answered by graph walking mechanism - [resource--to-->subject] traverse path.
these is no dynamic mixture/nature in decision making - like rego-rule-script to decide based on json payload.
how to do dynamic decision based on json payload?
You're correct about the application being responsible for the authorization data it "owns". If you intend to have a unique role/relationship for each document in your system, then you do need to write/delete those relationships as the referenced resources (or the roles on them, more likely) change, but if you are using an RBAC-like design for your schema, you'd have to apply these role changes anyway; you'd just apply them to SpiceDB, instead of to your database. Likewise, if you have a relationship between say, a document and its parent organization, you do have to write/delete those as well, but that should only occur when the document is created or deleted.
In practice, unless you intend to keep the relationships in both your database and in SpiceDB (which some users do), you'll generally only have to write them to one or the other. If you do intend to apply them to both, you can either just perform the updates to both at the same time, or use an outbox-like pattern to synchronize behind the scenes.
Having to be proactive in your applications about storing data in a centralized system is necessary for data consistency. The alternative is federated systems that reach into other services. Federated systems come with the trade-offs of being eventually consistent and can also suffer from priority inversion. I presented on the centralized vs federate trade-offs in a bit of depth and other design aspects of authorization systems in my presentation on the cloud native authorization landscape.
Caveats are a new feature in SpiceDB that enable dynamic policy to be enforced on the relationship graph. Caveats are defined using Google's Common Expression Language, which a language used for policy in other cloud-native projects like Kubernetes. You can also use caveats to make relationships that eventually expire, if you want to take some of book-keeping out of your app code.

How to handle database scalability with Ruby on Rails

I am creating a management system and I want to know how "Ruby on Rails" can support me in the mission of ensuring that each customer has their information, records and tables independent from other customers.
Is it better to put everything in a database and put a customer identifier to pull information through this parameter in queries or create a database for each customer automatically?
I admit that the second option attracts me more ... And I know that putting everything in one database will be detrimental to performance, because I assume that customers and their data will increase exponentially!
I want to know which option is more viable in the long run. And if the best option is to create separate databases, how can I do this with Ruby on Rails ??
There are pro and cons for both solutions which really depend on your use case.
Separating each customer in its own database has definitely advantages for scaling, running in different data centres or even onsite. However, this comes with higher complexity. For instance you can't query across customers anymore, you would need to run queries for each customers and aggregate the results. This approach is called multi tenancy (or shardening). There is a good gem called Apartment available (https://github.com/influitive/apartment).
Keeping everything in one database might be simpler to start of as it's less complex but it really depends on your use case.
Edit
Adding some more information based on the questions.
There are several reasons to use a one db per client architecture.
You have clearly separated tenants. In case it might make sense to go with the one db approach.
Scale. Having separated databases for each tenant makes scaling of course easier.
If 2) is the main reason you want to go for a one db per client approach I would strongly advise you against it. You add so much more complexity to your app which you might not need for years to come (if ever).
If scaling is your main concern I recommend reading Designing Data Intensive Applications by Martin Kleppmann. But basically, don't worry about scale for the first few years and focus on your product.

How to store and use algorithms?

I have a Rails app that displays transportation prices of companies (think e.g. momondo.com).
Those companies are 'created' using the same data model for all of them. Every company has its unique way to calculate a price.
I have to implement different algorithms for every single one. In some cases an 'algorithm' could just be a lookup in a table, in other cases it's a math formula.
So, what kind of data model is the most appropriate here?
Thanks in advance
Whether it's a SQL query or a math formula, it would still be ruby code. So I'd suggest putting them in classes (you can afterwards decide if you declare these classes dynamically or not) with, in combination, a strategy pattern
I have an application that sounds a lot like yours (different domain). I ended up creating a Rule class that has a rule attribute that is a jsonb type. Then I created a rules engine (none of the Ruby rules engines fit my needs). So, I just select the appropriate rule (in my case, using a combination of organization and name since my organizations can have multiple rules) and then pass this to my rules engine for evaluation.
Currently, in my application, rules are defined in YAML files, but I'll be creating a front end so that organizations can use the UI to define their various rules.
I realize that's very high level, but hopefully it gives you a directional sense of how another person approached the problem.

Neo4j how to avoid supernodes

In my Neo4j project I have Role and Permission entities which represent user roles and permissions. Each User in the system has relationships to appropriate sets of roles and permissions.
I think Role and Permission are some kind of supernodes that can become a major headache from a performance point of view in future.
What is the best practice for this case ? How to reimplement Role and Permission in order to avoid possible issues with supernodes ?
Do you plan to make some aggregate/mass queries based on Roles (i.e. count number of people of certain role, list them)?
If not, and you just want to check if a specific user has certain Role, than in my humble opinion it should not cause difficult to maintain, important performance issues ( as you will traverse certain relationships of the graph, ignoring vast majority of multiple relations of your "supernodes" ). I would keep with simple design ( "premature optimization is the root of all evil" ;) ), and once problems are noticed (internally, relationships are stored in a linkedlist-like structure, so finding a proper one may take time on supernode, even if you restrict searching to a certain relation type), splitting Role nodes using meta-node approach should do the job (it's described in Learning Neo4j)
If yes, you have a problem. That's probably a field in which RDBMS are better... Using meta nodes probably won't help, as you will still to have process all of them to list/count all users... So caching that data in a separate store may be simply the best idea ...
I'm going to assume that you're just using Neo4j as a permissions lookup data source (like hasPermission(current_user, 'permission_string')) and not tied into any queries to other entities. That can be fine, especially if you have a hierarchical access schema. If that's not true then this might not apply and it would be good to have a clearer idea of what your entities look like.
Since you're likely using permissions throughout your application it might and if they're going to grow in size and scope it could make sense for performance to use some form of caching like an in-memory store or in Redis, for example.
It might even make sense to generate a denormalized cache of every permission state for every user. So you would evaluate your rules which might be based on hierarchical roles/permissions and come out with a list of "User X has permission Y". Then whenever you change a user or a permission you'd regenerate the cache for that entity, and if you changed a role you would regenerate the cache for all of the associated users and permissions.
Also I don't know if I would apply this advice to just Neo4j. If you're talking about a simple key/value lookup then a lot of general purpose databases would be overkill in performance critical situations.

Building core shop framework in Rails. Suitable or not?

I work at an in-house IT department for company running 10 or so only shops of varying complexity. The shops code has been written over the last 8 years, each shop a new branch growing father and father away from the stem (I guess that makes it a bush?)
The need for more and more complex discounts, campaigns and user monitoring are growing rapidly - and changing rapidly as well (you never know what they come up with). So we have decided to write a new system from scratch and bring the different shops back together having them run on the same core code. We have considered .NET, but due to the fact that the design requirements change so fast we have more or less decided to give Rails a try. But we have some uncertainties/questions about rails.
Is Rails (stack) suitable to run to build a shop framework and who should this be organized?
We are running around 10 shops of which some are very much alike only differing in style, where others stands out in functionality, flow and content. But behind the business logic is all the same. The shops functionality is to a great extend the same as well. As an example the checkout page of one shop might display great details about VAT, discounts, P&P, etc. where as another might only show the necessary minimum.
Which approach would you take? Would you build and maintain a runable template shop with a functional superset of the shops. As new functionality is developed then merge the code with the other shops? Sounds a bit cumbersome.
In the example with the checkout page the views would differ from shop to shop, but the controllers and the models would remain the same, as long as you externalize configurations, like payment method types, and so on.
From this perspective it would make more sense just to create a repository of the views and configurations for each shop and then maintain model and controller code in a separate repository.
Would be possible to arrange the views according to shop, keeping all resources in one repositoary /views/shopname/Product. Would this make sense?
What do you think? how would you do this? Will working with rails in this way bring to much trouble?
Our campaign/discount system is growing steadily complex, both GUI and business logic. (in this view Rails seems interesting with its fast turnaround). Our discounts are property based and these properties are stored in a database row.
Making changes in the requirements to the workings of a discount is a real headache. So we are slowly replacing this property based system with a system that for each discount attaches a class (PHP) and a configuration so that each discount type has its own class and each utilization of such discount could specify some values for this class to operate on given current context (basically: what is in the basket)
In rails what approach would you take?
In rails you can easily extend your model (discount) with yet another property, migrate and you are ready (maybe a bit simplified). Could you write a base discount class that relied on a few basic properties and then write modules that hook into (extends) this class in case you need more advanced functionality?
Specifically what would this be in Rails terms a helper?
Some of this post might be a bit unclear. Please do ask questions. Also I'm in the process of learning Rails so please excuse me if don't use the right terms or if I've missed some of the main ideas of Rails.
Thanks
Michael
Is Rails (stack) suitable to run to
build a shop framework and how should
this be organized?
Sure, it can be suitable see:
http://www.shopify.com/
http://www.liquidmarkup.org/
I would not recommend it as a first project though.
Dont forget Spree Commerce as a viable solution that may or not suid your needs. On the other hand, if you want to roll your own solution, also check ActiveMerchant for payment gateway integration.

Resources