Skip to content

Commit 5eafd9a

Browse files
iamrz1dabasov
andauthored
New simplified User ReadPool related changes (#685)
* Updated related methods for new simplified read-pool * fixed lint error Co-authored-by: dabasov <yuderbasov@gmail.com>
1 parent 7b9053d commit 5eafd9a

File tree

9 files changed

+76
-208
lines changed

9 files changed

+76
-208
lines changed

code/go/0chain.net/blobbercore/allocation/entity.go

Lines changed: 29 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -193,13 +193,13 @@ func (Terms) TableName() string {
193193
return TableNameTerms
194194
}
195195

196+
// ReadPool represents new trimmed down readPool consisting of two balances,
197+
// one for the allocations that the client (client_id) owns
198+
// and the other for the allocations that the client (client_id) doesn't own
196199
type ReadPool struct {
197-
PoolID string `gorm:"column:pool_id;size:64;primaryKey"`
198-
ClientID string `gorm:"column:client_id;size:64;not null;index:idx_read_pools_cab,priority:1"`
199-
AllocationID string `gorm:"column:allocation_id;size:64;not null;index:idx_read_pools_cab,priority:2"`
200-
// Cached balance in read pool. Might need update when balance - pending is less than 0
201-
Balance int64 `gorm:"column:balance;not null"`
202-
ExpireAt common.Timestamp `gorm:"column:expire_at;not null"`
200+
ClientID string `gorm:"column:client_id;size:64;primaryKey" json:"client_id"`
201+
OwnerBalance int64 `gorm:"column:owner_balance;not null" json:"owner_balance"`
202+
VisitorBalance int64 `gorm:"column:visitor_balance;not null" json:"visitor_balance"`
203203
}
204204

205205
func (ReadPool) TableName() string {
@@ -218,57 +218,42 @@ func (WritePool) TableName() string {
218218
return "write_pools"
219219
}
220220

221-
func GetReadPools(db *gorm.DB, allocationID, clientID string, until common.Timestamp) (rps []*ReadPool, err error) {
222-
err = db.Model(&ReadPool{}).Select("pool_id", "balance", "expire_at").
223-
Where(
224-
"allocation_id = ? AND "+
225-
"client_id = ? AND "+
226-
"expire_at > ?", allocationID, clientID, until).Find(&rps).Error
227-
228-
if err != nil {
229-
return nil, err
230-
}
231-
return
221+
func GetReadPool(db *gorm.DB, clientID string) (*ReadPool, error) {
222+
var rp ReadPool
223+
return &rp, db.Model(&ReadPool{}).Where("client_id = ?", clientID).Scan(&rp).Error
232224
}
233225

234-
func GetReadPoolsBalance(db *gorm.DB, allocationID, clientID string, until common.Timestamp) (balance int64, err error) {
235-
var b *int64 // pointer to int64 for possible total sum as null
236-
err = db.Model(&ReadPool{}).Select("sum(balance) as tot_balance").Where(
237-
"client_id = ? AND "+
238-
"allocation_id = ? AND "+
239-
"expire_at > ?", clientID, allocationID, until).Scan(&b).Error
240-
226+
func GetReadPoolsBalance(db *gorm.DB, clientID string, isOwner bool) (int64, error) {
227+
rp, err := GetReadPool(db, clientID)
241228
if err != nil {
242229
return 0, err
243230
}
244-
if b == nil {
245-
return 0, nil
231+
232+
if isOwner {
233+
return rp.OwnerBalance, nil
246234
}
247-
return *b, nil
235+
return rp.VisitorBalance, nil
248236
}
249237

250-
func SetReadPools(db *gorm.DB, clientID, allocationID string, rps []*ReadPool) (err error) {
251-
// cleanup and batch insert (remove old pools, add / update new)
252-
const query = `client_id = ? AND
253-
allocation_id = ?`
254-
255-
var stub []*ReadPool
256-
err = db.Model(&ReadPool{}).
257-
Where(query, clientID, allocationID).
258-
Delete(&stub).Error
238+
func SetReadPool(db *gorm.DB, rp *ReadPool) error {
239+
var erp ReadPool //find existing read pool
240+
err := db.Model(&ReadPool{}).Where("client_id = ?", rp.ClientID).FirstOrCreate(&erp, rp).Error
259241
if err != nil {
260-
return
242+
return err
261243
}
262244

263-
if len(rps) == 0 {
264-
return
245+
if erp.OwnerBalance == rp.OwnerBalance && erp.VisitorBalance == rp.VisitorBalance {
246+
return nil
265247
}
248+
// update existing
249+
return UpdateReadPool(db, rp)
250+
}
266251

267-
err = db.Model(&ReadPool{}).Clauses(clause.OnConflict{
268-
Columns: []clause.Column{{Name: "pool_id"}},
269-
DoUpdates: clause.AssignmentColumns([]string{"balance"}),
270-
}).Create(rps).Error
271-
return
252+
func UpdateReadPool(db *gorm.DB, rp *ReadPool) error {
253+
return db.Model(&ReadPool{}).Where("client_id = ?", rp.ClientID).Updates(map[string]interface{}{
254+
"owner_balance": rp.OwnerBalance,
255+
"visitor_balance": rp.VisitorBalance,
256+
}).Error
272257
}
273258

274259
func SetWritePools(db *gorm.DB, clientID, allocationID string, wps []*WritePool) (err error) {
@@ -302,18 +287,3 @@ type ReadPoolRedeem struct {
302287
PoolID string `json:"pool_id"` // read pool ID
303288
Balance int64 `json:"balance"` // balance reduction
304289
}
305-
306-
// SubReadRedeemed subtracts tokens redeemed from read pools.
307-
func SubReadRedeemed(rps []*ReadPool, redeems []ReadPoolRedeem) {
308-
var rm = make(map[string]int64)
309-
310-
for _, rd := range redeems {
311-
rm[rd.PoolID] += rd.Balance
312-
}
313-
314-
for _, rp := range rps {
315-
if sub, ok := rm[rp.PoolID]; ok {
316-
rp.Balance -= sub
317-
}
318-
}
319-
}

code/go/0chain.net/blobbercore/allocation/protocol.go

Lines changed: 7 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"encoding/json"
66
"errors"
77
"fmt"
8-
98
"github.com/0chain/blobber/code/go/0chain.net/blobbercore/datastore"
109
"github.com/0chain/blobber/code/go/0chain.net/blobbercore/filestore"
1110
"github.com/0chain/blobber/code/go/0chain.net/core/chain"
@@ -193,47 +192,23 @@ type PoolStat struct {
193192
ExpireAt common.Timestamp `json:"expire_at"`
194193
}
195194

196-
func RequestReadPools(clientID, allocationID string) (rps []*ReadPool, err error) {
195+
func RequestReadPoolStat(clientID string) (*ReadPool, error) {
197196
Logger.Info("request read pools")
198197

199-
var (
200-
blobberID = node.Self.ID
201-
resp []byte
202-
)
203-
204198
params := map[string]string{
205-
"client_id": clientID,
206-
"allocation_id": allocationID,
207-
"blobber_id": blobberID,
199+
"client_id": clientID,
208200
}
209-
resp, err = transaction.MakeSCRestAPICall(transaction.STORAGE_CONTRACT_ADDRESS, "/getReadPoolAllocBlobberStat", params, chain.GetServerChain())
201+
resp, err := transaction.MakeSCRestAPICall(transaction.STORAGE_CONTRACT_ADDRESS, "/getReadPoolStat", params, chain.GetServerChain())
210202
if err != nil {
211203
return nil, fmt.Errorf("requesting read pools stat: %v", err)
212204
}
213205

214-
var pss []*PoolStat
215-
if err = json.Unmarshal(resp, &pss); err != nil {
216-
return nil, fmt.Errorf("decoding read pools stat response: %v", err)
206+
var readPool ReadPool
207+
if err = json.Unmarshal(resp, &readPool); err != nil {
208+
return nil, fmt.Errorf("decoding read pools stat response: %v, \n==> resp: %s", err, string(resp))
217209
}
218210

219-
if len(pss) == 0 {
220-
return nil, nil // empty
221-
}
222-
223-
rps = make([]*ReadPool, 0, len(pss))
224-
for _, ps := range pss {
225-
rps = append(rps, &ReadPool{
226-
PoolID: ps.PoolID,
227-
228-
ClientID: clientID,
229-
AllocationID: allocationID,
230-
231-
Balance: ps.Balance,
232-
ExpireAt: ps.ExpireAt,
233-
})
234-
}
235-
236-
return // got them
211+
return &readPool, nil
237212
}
238213

239214
func RequestWritePools(clientID, allocationID string) (wps []*WritePool, err error) {

code/go/0chain.net/blobbercore/handler/handler.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -498,8 +498,8 @@ func InsertShare(ctx context.Context, r *http.Request) (interface{}, error) {
498498
FilePathHash: authTicket.FilePathHash,
499499
ReEncryptionKey: authTicket.ReEncryptionKey,
500500
ClientEncryptionPublicKey: encryptionPublicKey,
501-
ExpiryAt: common.ToTime(authTicket.Expiration),
502-
AvailableAt: common.ToTime(availableAt),
501+
ExpiryAt: common.ToTime(authTicket.Expiration).UTC(),
502+
AvailableAt: common.ToTime(availableAt).UTC(),
503503
}
504504

505505
existingShare, _ := reference.GetShareInfo(ctx, authTicket.ClientID, authTicket.FilePathHash)

code/go/0chain.net/blobbercore/handler/object_operation_handler.go

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,8 @@ import (
66
"encoding/json"
77
"errors"
88
"fmt"
9-
109
"github.com/0chain/blobber/code/go/0chain.net/blobbercore/blobberhttp"
1110
"github.com/0chain/blobber/code/go/0chain.net/blobbercore/stats"
12-
1311
"net/http"
1412
"path/filepath"
1513
"strconv"
@@ -52,45 +50,41 @@ func readPreRedeem(ctx context.Context, alloc *allocation.Allocation, numBlocks,
5250
var (
5351
db = datastore.GetStore().GetTransaction(ctx)
5452
blobberID = node.Self.ID
55-
until = common.Now() + common.Timestamp(config.Configuration.ReadLockTimeout)
56-
57-
rps []*allocation.ReadPool
5853
)
5954

6055
if alloc.GetRequiredReadBalance(blobberID, numBlocks) <= 0 {
6156
return // skip if read price is zero
6257
}
6358

64-
readPoolsBalance, err := allocation.GetReadPoolsBalance(db, alloc.ID, payerID, until)
59+
isOwner := alloc.OwnerID == payerID
60+
readPoolsBalance, err := allocation.GetReadPoolsBalance(db, payerID, isOwner)
6561
if err != nil {
6662
return common.NewError("read_pre_redeem", "database error while reading read pools balance")
6763
}
6864

6965
requiredBalance := alloc.GetRequiredReadBalance(blobberID, numBlocks+pendNumBlocks)
7066

7167
if float64(readPoolsBalance) < requiredBalance {
72-
rps, err = allocation.RequestReadPools(payerID, alloc.ID)
68+
rp, err := allocation.RequestReadPoolStat(payerID)
7369
if err != nil {
7470
return common.NewErrorf("read_pre_redeem", "can't request read pools from sharders: %v", err)
7571
}
7672

77-
err = allocation.SetReadPools(db, payerID, alloc.ID, rps)
73+
rp.ClientID = payerID
74+
err = allocation.UpdateReadPool(db, rp)
7875
if err != nil {
7976
return common.NewErrorf("read_pre_redeem", "can't save requested read pools: %v", err)
8077
}
8178

82-
readPoolsBalance = 0
83-
for _, rp := range rps {
84-
if rp.ExpireAt < until {
85-
continue
86-
}
87-
readPoolsBalance += rp.Balance
79+
if isOwner {
80+
readPoolsBalance = rp.OwnerBalance
81+
} else {
82+
readPoolsBalance = rp.VisitorBalance
8883
}
8984

9085
if float64(readPoolsBalance) < requiredBalance {
91-
return common.NewError("read_pre_redeem", "not enough "+
92-
"tokens in client's read pools associated with the"+
93-
" allocation->blobber")
86+
return common.NewError("read_pre_redeem",
87+
"not enough tokens in client's read pools associated with the allocation->blobber")
9488
}
9589
}
9690

0 commit comments

Comments
 (0)