-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[WIP] GRIP engine embedded in a python library #316
Open
kellrott
wants to merge
16
commits into
develop
Choose a base branch
from
feature/python-lib
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
0415dc7
Adding mem based key-value driver and testing a python lib
kellrott d352fa8
Working python wrapper library
kellrott 80b1652
Fixing client
kellrott 4e79dd7
Adding setup.py for pygrip
kellrott ebc227a
Working on adding unit tests
kellrott da288a3
Doing user install for python
kellrott cf3613c
add step to actually run the pygrip unit tests
kellrott 1441f5d
Adding missing file
kellrott 2200d28
Debugging unit test running
kellrott 7421fe8
Removing stdout error statements
kellrott 0467c4e
adds pythonpath for pytest
bwalsh 0b16fbe
make ./test a package
bwalsh 9515322
test FHIR load, dataframe traversals
bwalsh 9770579
adds comments and TODO
bwalsh 6658643
Merge branch 'develop' into feature/python-lib
kellrott 24f2110
Adding python dependencies to unit tests
kellrott File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -36,4 +36,4 @@ | |
count | ||
] | ||
|
||
__version__ = "0.7.1" | ||
__version__ = "0.8.0" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
package leveldb | ||
|
||
import ( | ||
"bytes" | ||
"fmt" | ||
|
||
"github.com/bmeg/grip/kvi" | ||
"github.com/bmeg/grip/log" | ||
"github.com/syndtr/goleveldb/leveldb/comparer" | ||
"github.com/syndtr/goleveldb/leveldb/iterator" | ||
"github.com/syndtr/goleveldb/leveldb/memdb" | ||
) | ||
|
||
var mem_loaded = kvi.AddKVDriver("memdb", NewMemKVInterface) | ||
|
||
type LevelMemKV struct { | ||
db *memdb.DB | ||
} | ||
|
||
// NewKVInterface creates new LevelDB backed KVInterface at `path` | ||
func NewMemKVInterface(path string, opts kvi.Options) (kvi.KVInterface, error) { | ||
log.Info("Starting In-Memory LevelDB") | ||
db := memdb.New(comparer.DefaultComparer, 1000) | ||
return &LevelMemKV{db: db}, nil | ||
} | ||
|
||
// BulkWrite implements kvi.KVInterface. | ||
func (l *LevelMemKV) BulkWrite(u func(bl kvi.KVBulkWrite) error) error { | ||
ktx := &memIterator{l.db, nil, true, nil, nil} | ||
return u(ktx) | ||
} | ||
|
||
// Close implements kvi.KVInterface. | ||
func (l *LevelMemKV) Close() error { | ||
return nil | ||
} | ||
|
||
// Delete implements kvi.KVInterface. | ||
func (l *LevelMemKV) Delete(key []byte) error { | ||
return l.db.Delete(key) | ||
} | ||
|
||
// DeletePrefix implements kvi.KVInterface. | ||
func (l *LevelMemKV) DeletePrefix(prefix []byte) error { | ||
deleteBlockSize := 10000 | ||
for found := true; found; { | ||
found = false | ||
wb := make([][]byte, 0, deleteBlockSize) | ||
it := l.db.NewIterator(nil) | ||
for it.Seek(prefix); it.Valid() && bytes.HasPrefix(it.Key(), prefix) && len(wb) < deleteBlockSize-1; it.Next() { | ||
wb = append(wb, copyBytes(it.Key())) | ||
} | ||
it.Release() | ||
for _, i := range wb { | ||
l.db.Delete(i) | ||
found = true | ||
} | ||
} | ||
return nil | ||
|
||
} | ||
|
||
// Get implements kvi.KVInterface. | ||
func (l *LevelMemKV) Get(key []byte) ([]byte, error) { | ||
return l.db.Get(key) | ||
} | ||
|
||
// HasKey implements kvi.KVInterface. | ||
func (l *LevelMemKV) HasKey(key []byte) bool { | ||
_, err := l.db.Get(key) | ||
return err == nil | ||
} | ||
|
||
// Set implements kvi.KVInterface. | ||
func (l *LevelMemKV) Set(key []byte, value []byte) error { | ||
return l.db.Put(key, value) | ||
} | ||
|
||
// Update implements kvi.KVInterface. | ||
func (l *LevelMemKV) Update(func(tx kvi.KVTransaction) error) error { | ||
panic("unimplemented") | ||
} | ||
|
||
// View implements kvi.KVInterface. | ||
func (l *LevelMemKV) View(u func(it kvi.KVIterator) error) error { | ||
it := l.db.NewIterator(nil) | ||
defer it.Release() | ||
lit := memIterator{l.db, it, true, nil, nil} | ||
return u(&lit) | ||
} | ||
|
||
type memIterator struct { | ||
db *memdb.DB | ||
it iterator.Iterator | ||
forward bool | ||
key []byte | ||
value []byte | ||
} | ||
|
||
// Get retrieves the value of key `id` | ||
func (lit *memIterator) Get(id []byte) ([]byte, error) { | ||
return lit.db.Get(id) | ||
} | ||
|
||
func (lit *memIterator) Set(key, val []byte) error { | ||
return lit.db.Put(key, val) | ||
} | ||
|
||
// Key returns the key the iterator is currently pointed at | ||
func (lit *memIterator) Key() []byte { | ||
return lit.key | ||
} | ||
|
||
// Value returns the valud of the iterator is currently pointed at | ||
func (lit *memIterator) Value() ([]byte, error) { | ||
return lit.value, nil | ||
} | ||
|
||
// Next move the iterator to the next key | ||
func (lit *memIterator) Next() error { | ||
var more bool | ||
if lit.forward { | ||
more = lit.it.Next() | ||
} else { | ||
more = lit.it.Prev() | ||
} | ||
if !more { | ||
lit.key = nil | ||
lit.value = nil | ||
return fmt.Errorf("Invalid") | ||
} | ||
lit.key = copyBytes(lit.it.Key()) | ||
lit.value = copyBytes(lit.it.Value()) | ||
return nil | ||
} | ||
|
||
func (lit *memIterator) Seek(id []byte) error { | ||
lit.forward = true | ||
if lit.it.Seek(id) { | ||
lit.key = copyBytes(lit.it.Key()) | ||
lit.value = copyBytes(lit.it.Value()) | ||
return nil | ||
} | ||
return fmt.Errorf("Invalid") | ||
} | ||
|
||
func (lit *memIterator) SeekReverse(id []byte) error { | ||
lit.forward = false | ||
if lit.it.Seek(id) { | ||
//Level iterator will land on the first value above the request | ||
//if we're there, move once to get below start request | ||
if bytes.Compare(id, lit.it.Key()) < 0 { | ||
lit.it.Prev() | ||
} | ||
lit.key = copyBytes(lit.it.Key()) | ||
lit.value = copyBytes(lit.it.Value()) | ||
return nil | ||
} | ||
return fmt.Errorf("Invalid") | ||
} | ||
|
||
// Valid returns true if iterator is still in valid location | ||
func (lit *memIterator) Valid() bool { | ||
if lit.key == nil || lit.value == nil { | ||
return false | ||
} | ||
return true | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
|
||
|
||
pygrip.so: wrapper.go | ||
go build -o pygrip.so -buildmode=c-shared wrapper.go |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
|
||
|
||
from __future__ import print_function | ||
from ctypes import * | ||
from ctypes.util import find_library | ||
import os, inspect, sysconfig | ||
import random, string | ||
import json | ||
from gripql.query import QueryBuilder | ||
|
||
cwd = os.getcwd() | ||
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) | ||
#print("frame: %s" % (inspect.getfile(inspect.currentframe()))) | ||
#print("cd to %s" % (currentdir)) | ||
os.chdir(currentdir) | ||
_lib = cdll.LoadLibrary("./_pygrip" + sysconfig.get_config_vars()["EXT_SUFFIX"]) | ||
os.chdir(cwd) | ||
|
||
_lib.ReaderNext.restype = c_char_p | ||
|
||
class GoString(Structure): | ||
_fields_ = [("p", c_char_p), ("n", c_longlong)] | ||
|
||
def NewMemServer(): | ||
return GraphDBWrapper( _lib.NewMemServer() ) | ||
|
||
def getGoString(s): | ||
return GoString(bytes(s, encoding="raw_unicode_escape"), len(s)) | ||
|
||
def id_generator(size=6, chars=string.ascii_uppercase + string.digits): | ||
return ''.join(random.choice(chars) for _ in range(size)) | ||
|
||
class QueryWrapper(QueryBuilder): | ||
def __init__(self, wrapper): | ||
super(QueryBuilder, self).__init__() | ||
self.query = [] | ||
self.wrapper = wrapper | ||
|
||
def __iter__(self): | ||
jquery = json.dumps({ "graph" : "default", "query" : self.query }) | ||
reader = _lib.Query( self.wrapper._handle, getGoString(jquery) ) | ||
while not _lib.ReaderDone(reader): | ||
j = _lib.ReaderNext(reader) | ||
yield json.loads(j) | ||
|
||
def _builder(self): | ||
return QueryWrapper(self.wrapper) | ||
|
||
class GraphDBWrapper: | ||
def __init__(self, handle) -> None: | ||
self._handle = handle | ||
|
||
def addVertex(self, gid, label, data={}): | ||
""" | ||
Add vertex to a graph. | ||
""" | ||
_lib.AddVertex(self._handle, getGoString(gid), getGoString(label), | ||
getGoString(json.dumps(data))) | ||
|
||
def addEdge(self, src, dst, label, data={}, gid=None): | ||
""" | ||
Add edge to a graph. | ||
""" | ||
if gid is None: | ||
gid = id_generator(10) | ||
|
||
_lib.AddEdge(self._handle, getGoString(gid), | ||
getGoString(src), getGoString(dst), getGoString(label), | ||
getGoString(json.dumps(data))) | ||
|
||
|
||
|
||
def V(self, *ids): | ||
return QueryWrapper(self).V(*ids) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
python setup.py install --user
produces:There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Changed to 3.12, works now
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
However, it doesn't look like it installed?
$ pytest test/pygrip_test/test_pygrip.py
========================================================================================== test session starts ==========================================================================================
platform darwin -- Python 3.12.1, pytest-8.1.1, pluggy-1.4.0
rootdir: /Users/walsbr/bmeg/grip
collected 0 items / 1 error
================================================================================================ ERRORS =================================================================================================
___________________________________________________________________________ ERROR collecting test/pygrip_test/test_pygrip.py ____________________________________________________________________________
ImportError while importing test module '/Users/walsbr/bmeg/grip/test/pygrip_test/test_pygrip.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../.pyenv/versions/3.12.1/lib/python3.12/importlib/init.py:90: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
test/pygrip_test/test_pygrip.py:2: in
import pygrip
E ModuleNotFoundError: No module named 'pygrip'
======================================================================================== short test summary info ========================================================================================
ERROR test/pygrip_test/test_pygrip.py```