package common

import (
	"common/db/etcd"
	"common/log"
	clientv3 "go.etcd.io/etcd/client/v3"
)

// NewLeaseAndKeepAlive 创建租约并保活
func NewLeaseAndKeepAlive(ttl int64) (clientv3.LeaseID, error) {
	lease, err := etcd.GetClient().Grant(ttl)
	if err != nil {
		return 0, err
	}
	chKeepAlive, err := etcd.GetClient().KeepAlive(lease.ID)
	if err != nil {
		return 0, err
	}
	go func(leaseID clientv3.LeaseID) {
		for range chKeepAlive {
		}
		log.Warnf("Lease %x expired or revoked", leaseID)
	}(lease.ID)
	return lease.ID, nil
}
