Skip to content

Commit

Permalink
CertLogic extras and doc++
Browse files Browse the repository at this point in the history
  • Loading branch information
panzi committed Sep 11, 2021
1 parent 9b4b35b commit 0d17703
Show file tree
Hide file tree
Showing 3 changed files with 328 additions and 10 deletions.
318 changes: 312 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,308 @@ Pure Python 3 [JsonLogic](https://jsonlogic.com/) and
[CertLogic](https://github.com/ehn-dcc-development/dgc-business-rules/blob/main/certlogic/specification/README.md)
implementation.

The JsonLogic format is designed to allow you to share rules (logic) between
front-end and back-end code (regardless of language difference), even to store
logic along with a record in a database. JsonLogic is documented at
[JsonLogic.com](http://jsonlogic.com), including examples of every
[supported operation](http://jsonlogic.com/operations.html) and a place to
[try out rules in your browser](http://jsonlogic.com/play.html).

CertLogic is a dialect of JsonLogic with slightly different semantics and
operations.

There are already other JsonLogic implementations in Python, but last I looked
they don't emulate all the JavaScript operator behaviors quite right and they
don't implement CertLogic at all.
don't implement CertLogic at all. This implementation tries to be as close to
the [JavaScript implementation](https://github.com/jwadhams/json-logic-js) of
JsonLogic as feasible.

* [Examples](#examples)
* [Simple](#simple)
* [Compound](#compound)
* [Data-Driven](#data-driven)
* [Always and Never](#always-and-never)
* [CertLogic](#certlogic)
* [Custom Operations](#custom-operations)
* [Extras](#extras)
* [Remarks](#remarks)
* [Credits](#credits)

Examples
--------

### Simple

```python
from json_logic import jsonLogic
jsonLogic( { "==" : [1, 1] } )
# True
```

This is a simple test, equivalent to `1 == 1`. A few things about the format:

1. The operator is always in the "key" position. There is only one key per
JsonLogic rule.
2. The values are typically an array.
3. Each value can be a string, number, boolean, array (non-associative), or null

Note that `==` tries to emulate the JavaScript `==` operator and as such it is
adviseable to rather use `===`, which in this implementations simply uses
Python's `==`.

### Compound

Here rules are nested.

```Python
jsonLogic(
{ "and" : [
{ ">" : [3, 1] },
{ "<" : [1, 3] }
] }
)
# True
```

In an infix language (like Python) this could be written as:

```Python
( (3 > 1) and (1 < 3) )
```

### Data-Driven

Obviously these rules aren't very interesting if they can only take static
literal data. Typically `jsonLogic()` will be called with a rule object and a
data object. You can use the `var` operator to get attributes of the data object:

```Python
jsonLogic(
{ "var" : ["a"] }, # Rule
{ a : 1, b : 2 } # Data
)
# 1
```

If you like, [syntactic sugar](https://en.wikipedia.org/wiki/Syntactic_sugar)
on unary operators to skip the array around values is supported:

```Python
jsonLogic(
{ "var" : "a" },
{ a : 1, b : 2 }
)
# 1
```

You can also use the `var` operator to access an array by numeric index:

```Python
jsonLogic(
{ "var" : 1 },
[ "apple", "banana", "carrot" ]
)
# "banana"
```

Here's a complex rule that mixes literals and data. The pie isn't ready to eat
unless it's cooler than 110 degrees, *and* filled with apples.

```Python
rules = { "and" : [
{ "<" : [ { "var" : "temp" }, 110 ]},
{ "==" : [ { "var" : "pie.filling" }, "apple" ] }
] }

data = { "temp" : 100, "pie" : { "filling" : "apple" } }

jsonLogic(rules, data)
# True
```

### Always and Never

Sometimes the rule you want to process is "Always" or "Never." If the first
parameter passed to `jsonLogic()` is a non-object, non-associative-array, it is
returned immediately.

```Python
# Always
jsonLogic(True, data_will_be_ignored)
# True

# Never
jsonLogic(False, i_wasnt_even_supposed_to_be_here)
# False
```

### CertLogic

CertLogic is implemented in the `json_logic.cert_logic` sub-module:

```Python
from json_logic.cert_logic import certLogic

certLogic({
"plusTime": [
"2022-01-02T15:00:00+02:00",
2,
"day"
]
}).isoformat()
# '2022-01-04T15:00:00+02:00'
```

Custom Operations
-----------------

In contrast to other JsonLogic implementations you are not supposed to
manipulate the libraries dictionary of operations, but instead pass your own
dictionary as optional 3rd argument to `jsonLogic()`. If you want to use
the predefined operations you have to manually include them:

```Python
from json_logic import jsonLogic
from json_logic.builtins import BUILTINS

ops = { **BUILTINS, 'pow': lambda data, a, b: a ** b }
jsonLogic({ 'pow': [3, 2]}, None, ops)
# 9
```

Note that in contrast to other Python JsonLogic libraries the data as passed to
the `jsonLogic()` function (or the context data in
`map`/`filter`/`reduce`/`all`/`some`/`none`) is passed to operator functions as
the first argument (you can call it `self` if you want to, to be consistent with
the JavaScript implementation where it is the `this` argument).

Note that not all operations can be overwritten with the operations dictionary.
In particular these operations are hard coded in because of their short circuit
behavior or because they execute one operand on all the items of a list: `if`
(alternative spelling: `?:`), `and`, `or`, `map`, `filter`, `reduce`, `all`,
`some`, `none`.

The `certLogic()` function can be called in the same way with extra operations.
The CertLogic builtins can be found under `json_logic.cert_logic.builtins.BUILTINS`.

Extras
------

This library also includes some extra operators that are not part of JsonLogic
under `json_logic.extras.EXTRAS`. This dictionary already includes
`json_logic.builtins.BUILTINS`. The same extras but combined with
`json_logic.cert_logic.builtins.BUILTINS` can be found under
`json_logic.cert_logic.extras.EXTRAS`.

### `now`

Retrieve current time as Python `datetime` object in UTC.

```
{
"now": []
}
```

### `parseTime`

Parse RFC 3339 date and date-time strings. No time zone is assumed to be UTC.
If the argument is a number it is interpreted as milliseconds since the Unix
epoch (1970-01-01 UTC).

```
{
"parseTime": [
<string-or-datetime-or-number>
]
}
```

### `timeSince`

Milliseconds since given date-time.

```
{
"timeSince": [
<string-or-datetime-or-number>
]
}
```

### `hours`

Convert hours to milliseconds. Useful in combination with `timeSince`.

```
{
"hours": [
<number>
]
}
```

### `days`

Convert days to milliseconds. Useful in combination with `timeSince`.

```
{
"hours": [
<number>
]
}
```

### `combinations`

Return array of arrays that represent all combinations of the elements of all
the lists.

```
{
"combinations": [
<array>...
]
}
```

Example:

```Python
from json_logic import jsonLogic
from json_logic.extras import EXTRAS

jsonLogic({"combinations": [
[1, 2, 3],
["a", "b", "c"],
["x", "y", "z"],
]}, None, EXTRAS)
# [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]
```

### `zip`

Like Python's `zip()`, but returns array of arrays (instead of generator of
tuples).

```
{
"zip": [
<array>...
]
}
```

Example:

```Python
jsonLogic({"zip": [
[1, 2],
["a", "b"],
]}, None, EXTRAS)
# [[1, 'a'], [2, 'b']]
```

Remarks
-------
Expand All @@ -16,9 +315,9 @@ There is currently one known way where this implementation differs from the
[JavaScript implementation](https://github.com/jwadhams/json-logic-js/) of
JsonLogic: The `substr` operator in this implementation operates on code points,
but in json-logic-js it operates on UTF-16 code units. To emulate this in
Python I would need to do an UTF-16 encode/decode round-trip in `substr`, and
even then there are differences where Python disallows broken UTF-16, but
JavaScript allows it.
Python an UTF-16 encode/decode round-trip is needed in `substr`, and even then
there are differences where Python disallows broken UTF-16, but JavaScript
allows it.

But if you really want the JavaScript behavior this library provides an
alternative `substr` implementation that does the UTF-16 round-trip. You can use
Expand All @@ -31,9 +330,16 @@ from json_logic.builtins import BUILTINS, op_substr_utf16
result = jsonLogic(logic, data, { **BUILTINS, 'substr': op_substr_utf16 })
```

Credits
-------

Some of this README is copied from [json-logic-py](https://github.com/nadirizr/json-logic-py),
some of the tests are ported from [json-logic-js](https://github.com/jwadhams/json-logic-js)
and the [JsonLogic test suite](https://jsonlogic.com/tests.json) and the
[CertLogic test suite](https://github.com/ehn-dcc-development/dgc-business-rules/tree/main/certlogic/specification/testSuite)
are included in the tests of this library.

TODO
----

* (more) documentation
* even more testing (it already passes the JsonLogic and CertLogic test suites)
* pypi package
8 changes: 8 additions & 0 deletions json_logic/cert_logic/extras.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from ..extras import EXTRAS_ONLY
from ..types import Operations
from .builtins import BUILTINS

EXTRAS: Operations = {
**BUILTINS,
**EXTRAS_ONLY,
}
12 changes: 8 additions & 4 deletions json_logic/extras.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from typing import List, Any
from datetime import datetime, timezone

from .builtins import BUILTINS
from .builtins import BUILTINS, to_number
from .types import Operations, JsonValue
from .cert_logic.builtins import parse_time, to_number
from .cert_logic.builtins import parse_time

def op_time_since(data=None, timestamp=None, *_ignored) -> float:
dt = parse_time(timestamp)
Expand Down Expand Up @@ -35,8 +35,7 @@ def combinations(*lists: List[JsonValue]) -> List[List[JsonValue]]:

return combinations

EXTRAS: Operations = {
**BUILTINS,
EXTRAS_ONLY: Operations = {
'now': lambda *_ignored: datetime.utcnow().replace(tzinfo=timezone.utc),
'hours': lambda data=None, value=None, *_ignored: to_number(value) * 60 * 60 * 1000,
'days': lambda data=None, value=None, *_ignored: to_number(value) * 24 * 60 * 60 * 1000,
Expand All @@ -46,3 +45,8 @@ def combinations(*lists: List[JsonValue]) -> List[List[JsonValue]]:
'combinations': lambda data=None, *lists: combinations(*lists), # type: ignore
'zip': lambda data=None, *lists: [list(item) for item in zip(*lists)],
}

EXTRAS: Operations = {
**BUILTINS,
**EXTRAS_ONLY,
}

0 comments on commit 0d17703

Please sign in to comment.