Skip to content

Commit 134dccc

Browse files
committed
add .env file, simplify graph initialization
1 parent c411278 commit 134dccc

File tree

6 files changed

+51
-142
lines changed

6 files changed

+51
-142
lines changed

.env

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
FALKORDB_HOST=localhost
2+
FALKORDB_PORT=6379
3+

code_graph/analyzers/source_analyzer.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,6 @@
2020
'.py': PythonAnalyzer()}
2121

2222
class SourceAnalyzer():
23-
def __init__(self) -> None:
24-
self.host = os.getenv('FALKORDB_HOST')
25-
self.port = os.getenv('FALKORDB_PORT')
26-
self.username = os.getenv('FALKORDB_USERNAME')
27-
self.password = os.getenv('FALKORDB_PASSWORD')
28-
2923
def first_pass(self, ignore: List[str], executor: concurrent.futures.Executor) -> None:
3024
"""
3125
Perform the first pass analysis on source files in the given directory tree.
@@ -167,8 +161,7 @@ def analyze_github_repository(
167161

168162
try:
169163
# Initialize the graph and analyzer
170-
self.graph = Graph(repo_name, self.host, self.port, self.username,
171-
self.password)
164+
self.graph = Graph(repo_name)
172165

173166
# Analyze repository
174167
self.analyze_sources(ignore)
@@ -195,8 +188,7 @@ def analyze_local_folder(self, path: str, ignore: Optional[List[str]] = []) -> G
195188
logger.debug(f'proj_name: {proj_name}')
196189

197190
# Initialize the graph and analyzer
198-
self.graph = Graph(proj_name, self.host, self.port, self.username,
199-
self.password)
191+
self.graph = Graph(proj_name)
200192

201193
# Analyze source files
202194
self.analyze_sources(ignore)

code_graph/git_utils/git_graph.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import os
12
from falkordb import FalkorDB, Node
23
from typing import List, Optional
34

@@ -9,11 +10,13 @@ class GitGraph():
910
from the current commit to parent / child
1011
"""
1112

12-
def __init__(self, name: str, host: str = 'localhost', port: int = 6379,
13-
username: Optional[str] = None, password: Optional[str] = None):
13+
def __init__(self, name: str):
14+
15+
self.db = FalkorDB(host=os.getenv('FALKORDB_HOST'),
16+
port=os.getenv('FALKORDB_PORT'),
17+
username=os.getenv('FALKORDB_USERNAME'),
18+
password=os.getenv('FALKORDB_PASSWORD'))
1419

15-
self.db = FalkorDB(host=host, port=port, username=username,
16-
password=password)
1720
self.g = self.db.select_graph(name)
1821

1922
# create indicies

code_graph/git_utils/git_utils.py

Lines changed: 0 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -20,93 +20,6 @@
2020
def GitRepoName(repo_name):
2121
return "{" + repo_name + "}_git"
2222

23-
# setup replication to the master
24-
def setup_replication():
25-
global replica_process
26-
27-
# start replica server
28-
command = [
29-
"redis-server",
30-
"--port", "6380",
31-
"--replicaof", "localhost", "6379",
32-
"--loadmodule", "/Users/roilipman/Dev/FalkorDB/bin/macos-arm64v8-release/src/falkordb.so"
33-
]
34-
replica_process = subprocess.Popen(command)
35-
36-
# closes redis replica
37-
def teardown_replica():
38-
print("closing replica")
39-
40-
# Gracefully terminate the process
41-
replica_process.terminate()
42-
43-
# Wait for the process to exit
44-
replica_process.wait()
45-
46-
print("replica terminated.")
47-
48-
# runs on a dedicated thread, capture GRAPH.EFFECT commands
49-
def _monitor_effects(graph_name):
50-
# Connect to Redis server
51-
r = redis.Redis(host='localhost', port=6380)
52-
53-
# Start monitoring the Redis server
54-
with r.monitor() as m:
55-
print("MONITOR ACTIVATED!")
56-
# Print commands as they are executed on the Redis server
57-
for command in m.listen():
58-
print("listening for monitor commands")
59-
# check for exit signal
60-
if monitor_exit_event.is_set():
61-
print("exit signal recived")
62-
break
63-
64-
cmd = command['command']
65-
print(f"cmd: {cmd}")
66-
if "GRAPH.EFFECT" in cmd and graph_name in cmd:
67-
# "GRAPH.EFFECT" "FalkorDB" "\x01\x05\x00\x00\x00\x90\x14\x00\x00\x00\x00\x00\x00"
68-
print(f"Detected effect: {cmd}")
69-
70-
# save effect
71-
72-
#{'time': 1728840094.85141, 'db': 0, 'client_address': '[::1]', 'client_port': '6379', 'client_type': 'tcp'
73-
#, 'command': 'set x 7'}
74-
75-
# monitor graph.effect commands
76-
def start_monitor_effects(graph_name):
77-
print(f"graph_name: {graph_name}")
78-
r = redis.Redis(host='localhost', port=6380, decode_responses=True)
79-
80-
# wait for replica to become responsive
81-
connected = False
82-
while not connected:
83-
# wait one sec
84-
time.sleep(1)
85-
try:
86-
role = r.role()
87-
connected = (role[0] == 'slave' and role[1] == 'localhost' and role[2] == 6379 and role[3] == 'connected')
88-
except Exception:
89-
pass
90-
91-
print("starting monitor thread")
92-
93-
monitor_thread = threading.Thread(target=_monitor_effects, args=(graph_name,))
94-
monitor_thread.start()
95-
96-
print("monitor thread started")
97-
98-
# stop monitoring graph.effect commands
99-
def stop_monitor_effects():
100-
print("signaling monitor thread to exit")
101-
102-
# Signal the thread to exit
103-
monitor_exit_event.set()
104-
105-
# Wait for the thread to finish
106-
monitor_thread.join()
107-
108-
print("monitor thread exited")
109-
11023
# build a graph capturing the git commit history
11124
def build_commit_graph(path: str, repo_name: str, ignore_list: Optional[List[str]] = []) -> GitGraph:
11225
repo = Repo(path)

code_graph/graph.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,18 @@
1+
import os
12
import time
23
from .entities import *
34
from typing import Dict, List, Optional
45
from falkordb import FalkorDB, Path, Node, QueryResult
56

6-
FALKORDB_HOST = "localhost"
7-
FALKORDB_PORT = 6379
8-
FALKORDB_USERNAME = None
9-
FALKORDB_PASSWORD = None
10-
117
def list_repos() -> List[str]:
128
"""
139
List processed repositories
1410
"""
1511

16-
db = FalkorDB(host=FALKORDB_HOST, port=FALKORDB_PORT,
17-
username=FALKORDB_USERNAME, password=FALKORDB_PASSWORD)
12+
db = FalkorDB(host=os.getenv('FALKORDB_HOST'),
13+
port=os.getenv('FALKORDB_PORT'),
14+
username=os.getenv('FALKORDB_USERNAME'),
15+
password=os.getenv('FALKORDB_PASSWORD'))
1816

1917
graphs = db.list_graphs()
2018
graphs = [g for g in graphs if not g.endswith('_git')]
@@ -25,17 +23,13 @@ class Graph():
2523
Represents a connection to a graph database using FalkorDB.
2624
"""
2725

28-
def __init__(self, name: str, host: str = 'localhost', port: int = 6379,
29-
username: Optional[str] = None, password: Optional[str] = None) -> None:
30-
self.db = FalkorDB(host=host, port=port, username=username,
31-
password=password)
32-
33-
self.host = host
34-
self.port = port
35-
self.username = username
36-
self.password = password
37-
38-
self.g = self.db.select_graph(name)
26+
def __init__(self, name: str) -> None:
27+
self.name = name
28+
self.db = FalkorDB(host=os.getenv('FALKORDB_HOST'),
29+
port=os.getenv('FALKORDB_PORT'),
30+
username=os.getenv('FALKORDB_USERNAME'),
31+
password=os.getenv('FALKORDB_PASSWORD'))
32+
self.g = self.db.select_graph(name)
3933

4034
# create indicies
4135

@@ -76,7 +70,7 @@ def clone(self, clone: str) -> "Graph":
7670
# TODO: add a waiting limit
7771
time.sleep(1)
7872

79-
return Graph(clone, self.host, self.port, self.username, self.password)
73+
return Graph(clone)
8074

8175

8276
def delete(self) -> None:

main.py

Lines changed: 26 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,6 @@
1212
load_dotenv()
1313

1414
# Access environment variables
15-
FALKORDB_HOST = os.getenv('FALKORDB_HOST')
16-
FALKORDB_PORT = os.getenv('FALKORDB_PORT')
17-
FALKORDB_USERNAME = os.getenv('FALKORDB_USERNAME')
18-
FALKORDB_PASSWORD = os.getenv('FALKORDB_PASSWORD')
19-
2015
app = Flask(__name__, static_folder='static')
2116

2217
# Configure the logger
@@ -57,8 +52,7 @@ def graph_entities():
5752

5853
try:
5954
# Initialize the graph with the provided repo and credentials
60-
g = Graph(repo, host=FALKORDB_HOST, port=FALKORDB_PORT,
61-
username=FALKORDB_USERNAME, password=FALKORDB_PASSWORD)
55+
g = Graph(repo)
6256

6357
# Retrieve a sub-graph of up to 100 entities
6458
sub_graph = g.get_sub_graph(100)
@@ -96,8 +90,7 @@ def get_neighbors():
9690

9791
try:
9892
# Initialize the graph with the provided repo and credentials
99-
g = Graph(repo, host=FALKORDB_HOST, port=FALKORDB_PORT,
100-
username=FALKORDB_USERNAME, password=FALKORDB_PASSWORD)
93+
g = Graph(repo)
10194

10295
# Get neighbors of the given node
10396
neighbors = g.get_neighbors(node_id)
@@ -324,8 +317,7 @@ def process_list_commits():
324317
return jsonify({'status': f'Missing mandatory parameter "repo"'}), 400
325318

326319
# Get JSON data from the request
327-
git_graph = GitGraph(GitRepoName(repo), host=FALKORDB_HOST, port=FALKORDB_PORT,
328-
username=FALKORDB_USERNAME, password=FALKORDB_PASSWORD)
320+
git_graph = GitGraph(GitRepoName(repo))
329321

330322
commits = git_graph.list_commits()
331323

@@ -339,35 +331,47 @@ def process_list_commits():
339331

340332
@app.route('/find_paths', methods=['POST'])
341333
def find_paths():
334+
"""
335+
Finds all paths between a source node (src) and a destination node (dest) in the graph.
336+
The graph is associated with the repository (repo) provided in the request.
337+
338+
Request Body (JSON):
339+
- repo (str): Name of the repository.
340+
- src (int): ID of the source node.
341+
- dest (int): ID of the destination node.
342+
343+
Returns:
344+
A JSON response with:
345+
- status (str): Status of the request ("success" or "error").
346+
- paths (list): List of paths between the source and destination nodes.
347+
"""
348+
342349
# Get JSON data from the request
343350
data = request.get_json()
344351

345-
# name of repository
352+
# Validate 'repo' parameter
346353
repo = data.get('repo')
347354
if repo is None:
348355
return jsonify({'status': f'Missing mandatory parameter "repo"'}), 400
349356

350-
# source ID
357+
# Validate 'src' parameter
351358
src = data.get('src')
352359
if src is None:
353360
return jsonify({'status': f'Missing mandatory parameter "src"'}), 400
354361

355-
# dest ID
362+
# Validate 'dest' parameter
356363
dest = data.get('dest')
357364
if dest is None:
358365
return jsonify({'status': f'Missing mandatory parameter "dest"'}), 400
359366

360-
# Get JSON data from the request
361-
g = Graph(repo, host=FALKORDB_HOST, port=FALKORDB_PORT,
362-
username=FALKORDB_USERNAME, password=FALKORDB_PASSWORD)
367+
# Initialize graph with provided repo and credentials
368+
g = Graph(repo)
363369

370+
# Find paths between the source and destination nodes
364371
paths = g.find_paths(src, dest)
365372

366-
# Create a response
367-
response = {
368-
'status': 'success',
369-
'paths': paths
370-
}
373+
# Create and return a successful response
374+
response = { 'status': 'success', 'paths': paths }
371375

372376
return jsonify(response), 200
373377

0 commit comments

Comments
 (0)