Giter Site home page Giter Site logo

nools's People

Contributors

bryant1410 avatar devside avatar doug-martin avatar dustinsmith1024 avatar geoff-lee-lendesk avatar gitter-badger avatar kidrane avatar larryprice avatar paullryan avatar scdf avatar tommy20061222 avatar vikeen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nools's Issues

Compiling nools from different sources

Nools should allow compiling flows and rules from different sources. Currently the rules compiler is reading the flow definition file from the file system, this should be changed to be read from a stream, this way people have the flexibility to store the rules wherever they please, in the file system, building them through an interface and storing them in memory, read them from a different location, etc...

The mechanism of having the rules stored only in file systems is neither flexible nor secure, rules might be a critical factor in evaluating business operations

Recompiling the same nools file throws an error

Use case: I'm using nools in NodeJS. The rules are in a ".nools" file and can be changed at any time. I need to be able to recompile the same file without specifying a new name.

I saw in lib/index.js that you're using the flows object to keep track of compiled files and you're checking in the FlowContainer's constructor is flows[name] already exists (this is where the error is thrown).

Ideally, we would have a way to remove items from this 'flows' object which btw will grow big if your application is compiling lots of '.nools' files. I know I can recompile fine if I use another name in the options parameter, but I don't think it's the appropriate way of doing things.

Fact matching more than once for a rule

define Thing {
  constructor: function(value) {
    this.value = value;
  }
}

rule "some rule" {
   when {
     $1: Thing $1.value == "something";
     $2: Thing;
   }
}

The fact matched by $1 will also be matched by $2, that doesn't feel right in my opinion. Matching typically happens left-to-right, therefore $1 should have priority over $2.

Unable to load shared library ... node-proxy.node

I can't seem to require('nools') without getting this error:

Error: Unable to load shared library /private/tmp/node_modules/nools/node_modules/comb/node_modules/node-proxy/lib/node-proxy.node
    at Object..node (module.js:472:11)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)
    at Module.require (module.js:354:17)
    at require (module.js:370:17)
    at Object.<anonymous> (/private/tmp/node_modules/nools/node_modules/comb/lib/base/proxy.js:1:75)
    at Module._compile (module.js:441:26)
    at Object..js (module.js:459:10)
    at Module.load (module.js:348:31)
    at Function._load (module.js:308:12)

I'm using Mac OS 10.6.

Option to not cache flows or export the flow cache in index.js

I use nools to create a large number of flows dynamically from a set of flow definitions. Each flow definition is stored by a unique name which i use to create the flow object.

These flow objects are then managed by a LRU cache which disposes the flow object when required.

However in certain scenarios the LRU cache is destroyed and dispose is not called. In this case I have no more references available of all my previously created flows and when i try to recreate them I get an error saying they already exist.

I can bypass this by asking nools if the flow exists before recreating it.

However what do I do in the scenario when I never recreate a flow again. Wouldn't there be a memory leak caused due the reference maintained on the flows cache in index.js ?

An example to show more clearly what i mean

  • I create cache 1
  • I create Flow A and store in cache 1
  • I create Flow B and store in cache 1
  • I delete cache 1
  • I create cache 2
  • I create Flow A and find it already exists so i use it and store it in cache 2
  • I create Flow C and store it in cache 2

In this case if i never try to create Flow B again it will forever remain in the flows object and never be removed from memory.

I think there should be an option to disable storing a created flow in the flows cache in index.js or else this should be exported so that it can be cleared manually when needed.

Agenda Groups

A really useful feature would be have agenda groups support in the default rules language. This would allow groupings of rules that need to run together because of a logic reason that could be configured semantically. Currently the only way to achieve this is through a heavy use of priority/salience.

It would look like:

rule "A group a1 rule" {
  agenda-group: "a1",
  when { ...

rule "A group a2 rule" {
  agenda-group: "a2",
  when { ...

rule "Another group a1 rule" {
  agenda-group: "a1",
  when { ...

Then there would be a nools.groupArray which would be empty by default and you would add groups to this array in the order of desired execution such as nools.groupArray = ['a1', 'a2']. This ordering would result in a rules run of first attempting "A group a1 rule" and "Another group a1 rule" then attempting "A group a2 rule". Effectively running each agenda group as a separate rete tree that get's instantiated as the one prior is finished.

Question: Why don't rules with the same constraint don't all match?

I have a rule file below based on one of your examples. Originally I started out playing with salience (took me a short while to figure out the syntax in the DSL to set the salience since their weren't an examples). Anyway, in the example below the "count3" rule does not fire ever. I can if I start setting salience, but, even then it seems nonsensical at times. The "count2" rule that modifies the Counter seems to win always. I would assume that all the rules would fire. Thanks.

define Counter {
count: 0,
constructor: function(count){
this.count = count;
}
}

rule "counted too high" {
when {
ctr: Counter ctr.count == 100;
}
then{
console.log("Look ma! I counted to " + ctr.count);
halt();
}
}

rule "not count" {
when {
not(ctr: Counter);
}
then{
console.log("Imma gonna count!");
assert(new Counter(1));
}
}

rule count1 {
when{
ctr: Counter {count: count}
}
then{
console.log("Count 1");
}
}

rule count2 {

when{
    ctr: Counter {count: count}
}
then{
    modify(ctr, function(){this.count = count + 1;});
    console.log("Count 2");
}

}

rule count3 {

when{
    ctr: Counter {count: count}
}
then{
        console.log("Count 3");    
}

}

Facts defined in compile options not available via getDefined()

I think I should be able to do this:

custom-facts.js

module.exports = {
  CustomClass: function() {...}
}

custom-flow.js

var facts = require('custom-facts');

var flow = nools.compile('rules.nools', {
  defined: facts
});

custom = flow.getDefined('CustomClass');

But it seems that, event though the rules compile correctly, the classes are not available via getDefined(). It would be nice to have this work. I'd like to define my classes in coffeescript (in an separate file) and provide them to the rest of the app as if they were part of the rules file.

Or am I approaching this wrong?

Constraint with $t[$t.step] fails compilation

Contraint:

$t: Thing ($t.step && isUndefined($t[$t.step]))

fails with this error:

Error: Invalid expression '($t.step && isUndefined($t[$t.step]))'
    at Object.exports.parseConstraint (/home/steven/bin/.nmgm/nools/node_modules/nools/lib/parser/index.js:10:19)
    at constraintsToJs (/home/steven/bin/.nmgm/nools/node_modules/nools/lib/compile/transpile.js:82:61)
    at /home/steven/bin/.nmgm/nools/node_modules/nools/lib/compile/transpile.js:136:24
    at Array.map (native)
    at wrapper.map (/home/steven/bin/.nmgm/nools/node_modules/nools/node_modules/array-extended/index.js:222:28)
    at wrapper.extendedMethod [as map] (/home/steven/bin/.nmgm/nools/node_modules/nools/node_modules/extended/node_modules/extender/extender.js:400:40)
    at /home/steven/bin/.nmgm/nools/node_modules/nools/lib/compile/transpile.js:135:45
    at Array.map (native)
    at wrapper.map (/home/steven/bin/.nmgm/nools/node_modules/nools/node_modules/array-extended/index.js:222:28)
    at wrapper.extendedMethod [as map] (/home/steven/bin/.nmgm/nools/node_modules/nools/node_modules/extended/node_modules/extender/extender.js:400:40)

If I replace isUndefined($t[$t.step]) with isUndefined($t) compilation works.

window error on server

I tried to use Nools with the helloWorld.js example from the examples, but I could not install it with npm install, so I decided to use it directly. I downloaded the nools.js and pleced it to the same folder with the helloWorld.js. Of course I modified the require sentence to this.

var nools = require("./nools.js");

Then I tries to run (node helloWorld.js ), but got reference error to 'window' in nools.js.

I guess the npm install problem is related to my system, but according to the manual nools can be used with the way I mentioned before.

$ node helloWorld.js

/node.js/nools.js:13
}).call(window);
^
ReferenceError: window is not defined
at Object.../ (
/node.js/nools.js:13:9)
at i (/node.js/nools.js:1:281)
at
/node.js/nools.js:1:444
at Object. (~/node.js/nools.js:1:462)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)

How to pass classes to compile method?

According to the Readme, classes can be passed into the compile method for DSL files, but there is no documentation on the syntax the compile method expects.

more than two conditions in an or() block

I am looking for a way to have more than two conditions in an or() block.
The following rule will not parse:

rule hello {
when {
or(
a : String a == 'hello',
b : String b == 'hello',
c : String c == 'hello'
);
}
then {
}
}

A possible alternative notation might be something like:

rule hello {
when {
a : String b : String c : String a == 'hello' || b == 'hello' || c == 'hello'
}
then {
}
}

matchUntilHalt() uses a lot of CPU?

I've noticed that both in Node.js and in the browser matchUntilHalt() uses a lot of CPU. Is this observation correct and if so how can it be alleviated?

Compiling or() in DSL 'when' clause emits bad JS

I have a rule expressed in the DSL as follows:

rule beta {
    when {
        or(
           v1 : Value v1.id == 'hello',
           v2 : Value v2.id == 'goodbye'
           );
        r : Result
    }
    then {
        r.v.push("result"));
    }
}

Compiling (w. v0.1.8) the above yields the following JS (relevant excerpt):

                    }, ["or", , [Value, "v1", "v1.id == 'hello'"],
                        [Value, "v2", "v2.id == 'goodbye'"],
                        [Result, "r"]
                    ], function(facts, flow) {

...which causes a runtime error.

I'd expect the DSL rule to compile down to something more like:

                    }, ["or", [ 
                                  [Value, "v1", "v1.id == 'hello'"],
                                  [Value, "v2", "v2.id == 'goodbye'"]
                                ],
                        [Result, "r"]
                    ], function(facts, flow) {

...which works fine at runtime.

Is my expectation correct?

Clarify the purpose of next()

I'm guessing next() needs to be called when asserting from a callback within a then { } clause but I'm not sure because as far as I can tell next() is not clearly documented apart from:

If any arguments are passed into next it is assumed there was an error and the session will error out.

Example:

then {
  io.sockets.on('connection', function(socket) {
    assert(new Thing(socket));
    next();
  });
}

SEND + MORE = MONEY

Tried to solve this classic problem just for fun in NOOLS. Goes off and never returns and Chrome says it died. Based it on a CLIPS version found here:

http://commentsarelies.blogspot.com/2006/11/send-more-money-in-clips.html

I formulated this NOOLS file below and "asserted" all the Digits (0..9). Any ideas?
Thought it might be a good baseline test.

rule SendMoreMoney {
when {
s : Digit s.value != 0 { value : s1 };
e : Digit e.value != s1 { value: e1};
n : Digit n.value != s1 && n.value != e1 { value : n1 };
d : Digit d.value != s1 && d.value != e1 && d.value != n1 { value : d1 };
m : Digit m.value != s1 && m.value != e1 && m.value != n1 && m.value != d1 && m.value != 0 { value : m1 };
o : Digit o.value != s1 && o.value != e1 && o.value != n1 && o.value != d1 && o.value != m1 { value : o1 };
r : Digit r.value != s1 && r.value != e1 && r.value != n1 && r.value != d1 && r.value != m1 && r.value != o1 { value : r1 };
y : Digit y.value != s1 && y.value != e1 && y.value != n1 && y.value != d1 && y.value != m1 && y.value != o1 && y.value != r1 { value : y1 };
test : Digit s1_1000 + e1_100 + n1_10 + d1
+ m1_1000 + o1_100 + r1_10 + e1 ==
m1_10000 + o1_1000 + n1_100 + e1_10 + y1;

}
then {
    emit('pathDone', {sout : s, eout : e, nout : n, dout : d, mout : m, oout: o, rout : r, yout : y});
}

}

Logical AND not working in constraints

Example ($q.something is undefined):

$q: Thing !isUndefined($q.something) && $q.something.isTrue;

This will result in an error:

TypeError: Cannot read property 'isTrue' of undefined

If && would work as a logical AND the second term would not be evaluated.

Performance degradation in [email protected]

Hi,

We were using server side [email protected] for a while and recently upgraded to version 0.1.0.

We've seen almost a factor 2 degradation in performance (our test suite goes from 30-40 seconds to more than 1 minute).

We are very sensitive on performance as we are using big calculation models and it directly affects end user's response time.

I looked at both the current code and the changes introduced in 0.1.0 without a real clue about what is causing this performance degradation.

Would you be open to have a discussion on what may have caused this degradation and if there is a way we can help in improving performance ?

How to query for list of facts in the session?

I have a rule that polls an external system at a fixed interval. This call returns a JSON array with objects that are converted to facts.

I want to assert some of these facts (these are new), I want to modify certain other facts (these are existing facts) and I want to retract other facts.

However, I can't seem to add the existing facts to the when { } clause, at least I think I can't. My facts use the Thing type. Is it possible to get an array of all Thing facts from the when { } clause?

Recommended way to profile rules execution?

I'm trying to track down a significant slow-down in my rules execution. I'm fairly new to NodeJS's profiling tools, so this may be operator error. Here's what I'm doing...

export D8_PATH=/usr/local/bin
node --prof --log_all --log_snapshot_positions script.js
/usr/local/bin/tools/mac-tick-processor >> v8-processed.log

Strangely, it seems that most of the total ticks go unaccounted...

Notice that there are 1486 ticks, but there are just not that may reported in the bottom-up profile. I'm wondering if this has to do with the use of eval in compiling rules...

Statistical profiling result from v8.log, (1486 ticks, 12 unaccounted, 0 excluded).

 [Unknown]:
   ticks  total  nonlib   name
     12    0.8%

 [Shared libraries]:
   ticks  total  nonlib   name

 [JavaScript]:
   ticks  total  nonlib   name
      9    0.6%    0.6%  Function: wrapper /Volumes/Macintosh HD2/git/.../node_modules/nools/node_modules/declare.js/declare.js:617
      8    0.5%    0.5%  KeyedLoadIC: A keyed load IC from the snapshot
      6    0.4%    0.4%  LazyCompile: *EventEmitter.emit events.js:54
...

 [C++]:
   ticks  total  nonlib   name
    219   14.7%   14.7%  _chmod
     99    6.7%    6.7%  node::WrappedScript::CompileRunInThisContext
     37    2.5%    2.5%  ___vfprintf
...

 [GC]:
   ticks  total  nonlib   name
     74    5.0%

 [Bottom up (heavy) profile]:
  Note: percentage shows a share of a particular caller in the total
  amount of its parent calls.
  Callers occupying less than 2.0% are not shown.

   ticks parent  name
    219   14.7%  _chmod
     33   15.1%    LazyCompile: *fs.statSync fs.js:523
     33  100.0%      Function: statPath module.js:88
     29   87.9%        LazyCompile: *tryExtensions module.js:148
     29  100.0%          Function: ~Module._findPath module.js:160
     26   89.7%            Function: ~Module._resolveFilename module.js:323
      3   10.3%            LazyCompile: *Module._resolveFilename module.js:323
      4   12.1%        LazyCompile: *tryFile module.js:138
      4  100.0%          Function: ~Module._findPath module.js:160
      4  100.0%            Function: ~Module._resolveFilename module.js:323
     20    9.1%    Function: ~fs.statSync fs.js:523
     20  100.0%      Function: statPath module.js:88
      9   45.0%        LazyCompile: *tryExtensions module.js:148
      9  100.0%          Function: ~Module._findPath module.js:160
      9  100.0%            Function: ~Module._resolveFilename module.js:323
      7   35.0%        LazyCompile: *tryFile module.js:138
      5   71.4%          Function: ~tryExtensions module.js:148
      5  100.0%            Function: ~Module._findPath module.js:160
      2   28.6%          Function: ~Module._findPath module.js:160
      2  100.0%            Function: ~Module._resolveFilename module.js:323
      4   20.0%        Function: ~tryFile module.js:138
      4  100.0%          Function: ~tryExtensions module.js:148
      4  100.0%            Function: ~Module._findPath module.js:160
     16    7.3%    Function: ~defineProps /Volumes/Macintosh HD2/git/rebit/requalify3/server/node_modules/nools/node_modules/declare.js/declare.js:695
...

Conlcusion

_Is there a better way to see where the hot spots are in my rules execution?_

Equality operator not working as expected

I have an object defined thus:

define Value {
    id : null,
    v : null,
    constructor : function (id, value) {
        this.id = id;
        this.v = value;
     }
}

I'm asserting a fact like this:

s.assert(new Value("xyz", 27));

Then looking for it in a when clause like this:

v4 : Value v4.id =~ /xyz/ && v4.v == 27;

The == comparison fails to trigger the rule. The following does trigger the rule:

 v4 : Value v4.id =~ /xyz/ && v4.v >= 27 && v4.v <= 27;

I expected the == to work.

v0.1.10 breaks Node's require() function

I get this exception:

/home/steven/dev/xxxxxxxxxxx/node_modules/nools/lib/compile/common.js:26
        throw new Error("Invalid action : " + body + "\n" + e.message);
              ^
Error: Invalid action : ((function(){var io= scope.io;
    return require('/home/steven/dev/xxxxxxxxxxx/src/node/socket.io')
})())
Cannot find module '/home/steven/dev/xxxxxxxxxxx/src/node/socket.io'
    at createFunction (/home/steven/dev/xxxxxxxxxxx/node_modules/nools/lib/compile/common.js:26:15)
    at /home/steven/dev/xxxxxxxxxxx/node_modules/nools/lib/compile/index.js:172:25
    at Array.forEach (native)
    at forEach (/home/steven/dev/xxxxxxxxxxx/node_modules/nools/node_modules/array-extended/index.js:176:21)
    at Object.exports.compile (/home/steven/dev/xxxxxxxxxxx/node_modules/nools/lib/compile/index.js:171:5)
    at Object.nools.compile (/home/steven/dev/xxxxxxxxxxx/node_modules/nools/lib/index.js:288:21)
    at Object.<anonymous> (/home/steven/dev/xxxxxxxxxxx/src/node/nools.js:3:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)

I didn't have this problem with v0.1.9. To make sure I've downgraded and everything works A-OK.

Nools, node 0.10.0 support

It would be great to be able to use nools withe new version of node (much more performant version of node) however it currently breaks based on some deprecations the first encountered deprecation is a follows:

Currently nools breaks on when on node 0.10.0 because of the use of processTick.

Error: (node) warning: Recursive process.nextTick detected. This will break in the next version of node. Please use setImmediate for recursive deferral.
    at maxTickWarn (node.js:375:15)
    at process.nextTick (node.js:480:9)
    at wrapper.<anonymous> (.../node_modules/nools/lib/index.js:286:29)
    at .../node_modules/nools/node_modules/function-extended/index.js:43:39
    at fire (.../node_modules/nools/lib/index.js:258:21)
    at process._tickCallback (node.js:415:13)

Nools client-side!

Hi Doug,

I would like to use your excellent rules engine 'nools' in a single page browser app client-side.

I have a requirement for an 'occasionally (dis)connected app' which would benefit from having a rules engine run in the browser. This would mean I could use the same rules both in NodeJS and client-side... this would be awesome!

What would be required to have nools less dependent on node or at least available client side!?

Regards
Clinton

Two string comparisons in same expression fails

I have an object defined thus:

define Value {
    id : null,
    v : null,
    constructor : function (id, value) {
        this.id = id;
        this.v = value;
     }
}

I'm asserting a fact like this:

s.assert(new Value("xyz", "abc"));

Then looking for it in a when clause like this:

v4 : Value v4.id =~ /xyz/ && v4.v =~ /abc/;

The above fails to trigger the rule. The following does trigger the rule:

 v4 : Value v4.id =~ /xyz/ && v4.v ==  'abc';

For some reason, two string comparisons in the same rule don't want to play nice.

How to write a constraint that calls a custom function?

Just trying to understand the constraints model in nools.

I like to call any functions as part of constraint evaluation. Why is this not possible at the moment in nools. Why are only predefined functions and only property evaluations allowed?

How can I use 'external' facts

Say I have a fact and a rule that checks on that fact but I also wnat to check on e.g. the time of day. How would I do that?

My current config is:

define Event {
    uuid: '',
    property: '',
    value: undefined,
    constructor : function(event){
        this.uuid = event.uuid,
        this.property = event.property,
        this.value = event.value;
    }
}

rule PowerConsumption {
    when {
        e1: Event e1.uuid == 'ddee00df-399d-4a81-898e-60d7d4185cf5' &&
                  e1.property == 'actual_consumed_power' &&
                  e1.value > 1;
    }
    then {
        console.log('Matched');
    }
}

This rule checks whether the actual consumed power reported by a sensor with the specified uuid exceeds 1kW. However, I like to add constraints not directly related to that specific event, e.g. the time of day or the status of another sensor that not necessarily changed status. How would I do that?

Nools compile: Unexpected token name «start», expected punc «,»

I have no clue what is wrong with this rule:

rule "some rule" {
  when {
    $q: String $q == "start";
  }
  then {
  }
}

When I run nools compile I get this error:

Unexpected token name «start», expected punc «,»
Error
    at new JS_Parse_Error (/usr/lib/node_modules/uglify-js/lib/parse.js:196:18)
    at js_error (/usr/lib/node_modules/uglify-js/lib/parse.js:204:11)
    at croak (/usr/lib/node_modules/uglify-js/lib/parse.js:636:9)
    at token_error (/usr/lib/node_modules/uglify-js/lib/parse.js:644:9)
    at expect_token (/usr/lib/node_modules/uglify-js/lib/parse.js:657:9)
    at expect (/usr/lib/node_modules/uglify-js/lib/parse.js:660:36)
    at expr_list (/usr/lib/node_modules/uglify-js/lib/parse.js:1137:44)
    at /usr/lib/node_modules/uglify-js/lib/parse.js:1152:23
    at /usr/lib/node_modules/uglify-js/lib/parse.js:683:24
    at expr_atom (/usr/lib/node_modules/uglify-js/lib/parse.js:1115:35)

array reference gives invalid expression error

Example of a simple rule below.
The console.log of the _domainValues[0] & [1] report correct values.
However when used in the constraint expression, the rules compiler reports
"Invalid expression". Any thoughts?

rule CheckAndAssertActualWeight {
    when {
            actualWeight_domain: ActualWeight_Domain {values: _domainValues};
            actualWeight_EnteredValue: ActualWeight_EnteredValue 
                (
                    actualWeight_EnteredValue.value >= _domainValues[0] &&
                    actualWeight_EnteredValue.value <= _domainValues[1]
                ) {value : _entered};
    }
    then {
        assert( new ActualWeight_Value({value:_entered}) );
        console.log("ActualWeight value assigned: %s", _entered);   
        console.log("ActualWeight domain %s %s.", _domainValues[0], _domainValues[1]);  
    }
}

Deleting previously defined flows

I can't seem to find a way to delete a flow i previously defined in nools. I need this as my rule engine will be running for a long duration and may load several rule sets over time.

What's the best way to do this ?

Functions calls used in constraint predicates

The rule engine has trouble parsing rules with constructs like:

when {
        p : Property p.name != null && p.value != -1 {name:pn,value:pv};
        d : Dimension d.name!=null && isTrue(d.range.contains(pv));
    }

but this works:

when {
        d : Dimension d.name!=null && isTrue(d.range.contains(20));
}

Here range is a class "Range" that encapsulates the "contains" function that determines if the value is in range.

The pv doesn't seem to be considered a valid symbol by the parser when parsing the "contains(pv)" function call and returns the error that "pv is not defined" (I have tried p.value here also). Pulling off the "isTrue" parses, but the rule no longer functions correctly (it always fires).

Simple models without functions work as seen in the following:

when {
     p : Property p.name != null && p.value != -1;
     d : Dimension2 d.name!=null && p.value >= d.low && d.high >= p.value;
}

Is there a fix for this? Allowing function calls here is a step up in the expressive range of the language.

Full Code below:

the dsl: /rules/routebroken.nools

define Dimension {
    name:null,
    range: new Range(0,0),

    constructor : function(n,r){
        this.name = n;
        this.range = r;
    }
}

define Property {
    name:null,
    value:-1,

    constructor : function(n,v){
        this.name = n;
        this.value = v;
    }
}

rule RouteBroken {
    priority:1,
    when {
        p : Property p.name != null && p.value != -1 {name:pn,value:pv};
        d : Dimension d.name!=null && isTrue(d.range.contains(pv));
    }
    then {
        console.log("Route broken:  Dimension:"+d.name+"=>"+d.range.getRange()+" contains("+p.value+")");
    }
}

the program: routedslbroken.js

if (!(typeof exports === "undefined")) {
    var nools = require("nools");

    var range_module = require("./modules/range/range.class.js");
    var enum_module = require("./modules/enum/enum.js");

    var Range = range_module.Range;
    var Enum = enum_module.Enum;
}

var flow = nools.compile(__dirname + "/rules/routebroken.nools");
Dimension = flow.getDefined("Dimension");
Property = flow.getDefined("Property");

r = new Range(4,200);
d = new Dimension("Quantity",r);

var session = flow.getSession();

session.assert(new Dimension("Quantity",r));
session.assert(new Property("Quantity",10));
session.assert(new Property("Quantity",100));
session.assert(new Property("Quantity",1000)); // should not fire a rule.

session.match().then(
    function(){
        console.log("Done");
    },
    function(err){
        //uh oh an error occurred
        console.error(err);
    });

/modules/enum/enum.js

(function (exports) {
    function copyOwnFrom(target, source) {
        Object.getOwnPropertyNames(source).forEach(function(propName) {
            Object.defineProperty(target, propName,
                Object.getOwnPropertyDescriptor(source, propName));
        });
        return target;
    }

    function Symbol(name, props) {
        this.name = name;
        if (props) {
            copyOwnFrom(this, props);
        }
        Object.freeze(this);
    }
    /** We don’t want the mutable Object.prototype in the prototype chain */
    Symbol.prototype = Object.create(null);
    Symbol.prototype.constructor = Symbol;
    /**
     * Without Object.prototype in the prototype chain, we need toString()
     * in order to display symbols.
     */
    Symbol.prototype.toString = function () {
        return "|"+this.name+"|";
    };
    Object.freeze(Symbol.prototype);

    Enum = function (obj) {
        if (arguments.length === 1 && obj !== null && typeof obj === "object") {
            Object.keys(obj).forEach(function (name) {
                this[name] = new Symbol(name, obj[name]);
            }, this);
        } else {
            Array.prototype.forEach.call(arguments, function (name) {
                this[name] = new Symbol(name);
            }, this);
        }
        Object.freeze(this);
    }
    Enum.prototype.symbols = function() {
        return Object.keys(this).map(
            function(key) {
                return this[key];
            }, this
        );
    }
    Enum.prototype.contains = function(sym) {
        if (! sym instanceof Symbol) return false;
        return this[sym.name] === sym;
    }
    exports.Enum = Enum;
    exports.Symbol = Symbol;
}(typeof exports === "undefined" ? this.enums = {} : exports));
// Explanation of this pattern: http://www.2ality.com/2011/08/universal-modules.html

/modules/range/range.class.js

(function (exports) {

    Range = function (start_, end_, step_) {
        var range;
        var typeofrange;
        var typeofStart;
        var typeofEnd;
        var largerange = 100;
        var rangelow,rangehigh;

        Array.prototype.contains = function(k) {
            for(var p in this)
                if(this[p] === k)
                    return true;
            return false;
        }

        var init = function(start, end, step) {
            range = [];
            typeofStart = typeof start;
            typeofEnd = typeof end;

            if (typeof(start) == "object")
            {
                if (start instanceof Array) {
                    range = start;
                    typeofrange = "array";
                }
                // TODO: Hash?
                else { // assume an enum if it isn't an array.
                    range = start;
                    typeofrange = "enum";
                }

                return;
            }

            if (step === 0) {
                throw TypeError("Step cannot be zero.");
            }

            if (typeofStart == "undefined" || typeofEnd == "undefined") {
                throw TypeError("Must pass start and end arguments.");
            } else if (typeofStart != typeofEnd) {
                throw TypeError("Start and end arguments must be of same type.");
            }

            typeof step == "undefined" && (step = 1);

            if (end < start) {
                step = -step;
            }

            rangelow=start;
            rangehigh=end;
            if (typeofStart == "number") {
                if ((end-start)/step >= largerange || step == 1) {
                    typeofrange = "range";
                    if (step != 1){
                        throw TypeError("Step size must be 1 for ranges larger than "+largerange+".");
                    }
                }
                else {
                    typeofrange = typeofStart;
                    while (step > 0 ? end >= start : end <= start) {
                        range.push(start);
                        start += step;
                    }

                }

            } else if (typeofStart == "string") {

                typeofrange = typeofStart;
                if (start.length != 1 || end.length != 1) {
                    throw TypeError("Only strings with one character are supported.");
                }

                start = start.charCodeAt(0);
                end = end.charCodeAt(0);

                while (step > 0 ? end >= start : end <= start) {
                    range.push(String.fromCharCode(start));
                    start += step;
                }

            } else {
                throw TypeError("Only string and number types are supported");
            }
        };
        var getRange = function() { if (typeofrange=="range") return getLow()+".."+getHigh();
            else return range; };
        var getLow = function () { return rangelow; };
        var getHigh = function () { return rangehigh; };

        var contains = function (value) {
            if (typeofrange == "range") {
                return value >= rangelow && value <= rangehigh;
            }
            return range.contains(value)
            /*if (typeofrange == "enum") {
                return range.contains(value)
            }
            for(var p in range)
                if(this[p] === value)
                    return true;
            return false;

            */
        }

        init(start_, end_, step_);

        return {
            getRange:getRange,
            getLow:getLow,
            getHigh:getHigh,
            contains:contains
        };

    };

    exports.Range = Range;
}(typeof exports === "undefined" ? this.range = {} : exports));
//exports.Range = Range;

comb 0.2.0 breaks nools

Comb is set in package.json to be >=0.1.7 this breaks the build

To fix this you need to either revert the build to 0.1.7 or update the code, what do you suggest? can we have this fixed ASAP?

Serialize and deserialize rules compiles

I assume that the rules compile is one of the most expensive operations in this process. I know I can create an in memory cache of my compiled rule flows which will keep this from happening too often. I'm wondering however if you've thought of a way to serialize and then deserialize a precompiled set of rules something like:

var flow = nools.compile(__dirname + "/count.nools");

fs.writeFile(__dirname + '/count.nc', JSON.stringify(flow), function (err) {
    if (err) throw err;
    console.log('It\'s saved!');
});

and then on the other side

var flow = nools.load(__dirname + '/count.nc');

Thanks again for this awesome tool, if you haven't thought about it but think it might be a good idea I'd be willing to take a shot at getting it to work. Of course if you see a reason why it couldn't work please let me know.

Multiple Rules don't seem to be firing

Here is my rules file

define Message {
    message : '',
    count : 0,
    constructor : function(message) {
        this.message = message;
    }
}

rule Goodbye {
    when {
        m : Message m.message == 'Goodbye';
    }
    then {
        console.log("Completed");
    }
}

rule Hello {
    when {
        m : Message m.message == 'Hello';
    }
    then {
        modify(m, function() {
            this.message = 'Goodbye';
            this.count++;
        });
    }
}

I would expect the message 'Completed' to be displayed once all the rules fire but it seems that only the 'Hello' rule fires.

Here is my code

var flow = nools.compile(__dirname + "/rule1.nools");
var Message = flow.getDefined('Message');
var session = flow.getSession();

session.assert(new Message('Hello'));

session.match().then(
    function() {
        console.log('Done');
    },
    function(err) {
        console.log('Error');
    }
);

session.dispose();

and here is what is displayed in my console

Done

I would expect that once the Hello rule fires it will modify the message and then execute the second rule.

Any clues?

cheers

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.