Skip to content

Commit

Permalink
Rebal stats api (#257)
Browse files Browse the repository at this point in the history
  • Loading branch information
cryptosharks131 authored Mar 28, 2023
1 parent 76cca10 commit cc825fc
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 18 deletions.
1 change: 0 additions & 1 deletion gui/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,6 @@ class RebalancerSerializer(serializers.HyperlinkedModelSerializer):
stop = serializers.ReadOnlyField()
fees_paid = serializers.ReadOnlyField()
payment_hash = serializers.ReadOnlyField()

class Meta:
model = Rebalancer
exclude = []
Expand Down
1 change: 1 addition & 0 deletions gui/static/api.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
async function GET(url, {method = 'GET', data = null}){
if(!data.limit) data.limit = 100000
if(!data.format) data.format = 'json'
return call({url, method, data})
}

Expand Down
23 changes: 7 additions & 16 deletions gui/templates/rebalancing.html
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ <h5 style="float:left" title="Select outgoing channels above">Manual Rebalance R
<script>
document.addEventListener('DOMContentLoaded', async () => {
const _7days_ago = new Date(new Date().setDate(new Date().getDate()-7)).toISOString().substring(0,19)
const rebalancer_task = GET('rebalancer', {data: {stop__gt: _7days_ago, status__gt: 1, status__lt: 400}})
const resp = await GET('channels', {data: {is_open:true, private:false, auto_rebalance:'{{request.GET.auto_rebalance}}', is_active:'{{request.GET.is_active}}'}})
const rebal_stats = GET('rebalance_stats', {method : 'GET', data : {}})
const container = document.getElementById("rebalances_container")
if (resp.results.length == 0){
container.innerHTML = '<center><h1>You dont have any channels to rebalance yet.</h1></center>'
Expand Down Expand Up @@ -165,22 +165,13 @@ <h5 style="float:left" title="Select outgoing channels above">Manual Rebalance R
})
.forEach(ch => rebal_table.append(template.fillWith(ch)))

update_stats((await rebalancer_task).results, rebal_table)
update_stats(await rebal_stats, rebal_table)
})
function update_stats(rebalances, rebal_table){
if(rebalances.length == 0) return
[...rebal_table.rows].forEach(row => {

const rate_7day = [...row.cells].at(-2)
let [attempts, success, success_rate] = [0,0,0]
for(i in rebalances){
if(rebalances[i].last_hop_pubkey == rate_7day.dataTag){
[r] = rebalances.splice(i, 1)
attempts += 1
if(r.status == 2) success_rate = success += 1
}
}
rate_7day.innerHTML = attempts == 0? '---' : `${parseInt(success_rate*100/attempts)}% (${success}/${attempts})`
function update_stats(stats, rebal_table){
[...rebal_table.rows].forEach(row => {
const rate_7day = [...row.cells].at(-2)
let stat = stats.find(obj => obj.last_hop_pubkey === rate_7day.dataTag)
rate_7day.innerHTML = stat == null? '---' : `${parseInt(stat['successes']*100/stat['attempts'])}% (${(stat['successes'] || 0)}/${stat['attempts']})`
})
}
</script>
Expand Down
1 change: 1 addition & 0 deletions gui/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
path('api/', include(router.urls), name='api-root'),
path('api-auth/', include('rest_framework.urls'), name='api-auth'),
path('api/connectpeer/', views.connect_peer, name='connect-peer'),
path('api/rebalance_stats/', views.rebalance_stats, name='rebalance-stats'),
path('api/openchannel/', views.open_channel, name='open-channel'),
path('api/closechannel/', views.close_channel, name='close-channel'),
path('api/createinvoice/', views.add_invoice, name='add-invoice'),
Expand Down
13 changes: 12 additions & 1 deletion gui/views.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from django.contrib import messages
from django.shortcuts import get_object_or_404, render, redirect
from django.db.models import Sum, IntegerField, Count, Max, F, Q
from django.db.models import Sum, IntegerField, Count, Max, F, Q, Case, When
from django.db.models.functions import Round
from django.contrib.auth.decorators import login_required
from datetime import datetime, timedelta
Expand Down Expand Up @@ -2539,6 +2539,17 @@ def connect_peer(request):
else:
return Response({'error': 'Invalid request!'})

@api_view(['GET'])
@is_login_required(permission_classes([IsAuthenticated]), settings.LOGIN_REQUIRED)
def rebalance_stats(request):
try:
filter_7day = datetime.now() - timedelta(days=7)
rebalances = Rebalancer.objects.filter(stop__gt=filter_7day).values('last_hop_pubkey').annotate(attempts=Count('last_hop_pubkey'), successes=Sum(Case(When(status=2, then=1), output_field=IntegerField())))
return Response(rebalances)
except Exception as e:
error = str(e)
return Response({'error': 'Unable to fetch stats! Error: ' + error})

@api_view(['POST'])
@is_login_required(permission_classes([IsAuthenticated]), settings.LOGIN_REQUIRED)
def open_channel(request):
Expand Down

0 comments on commit cc825fc

Please sign in to comment.