| 64 | } |
| 65 | |
| 66 | func (this *Set) AddElement(key []byte, options *ElementOptions, overwrite bool) error { |
| 67 | // check if already exists |
| 68 | if this.expiration != nil && !overwrite && this.expiration.Contains(key) { |
| 69 | return nil |
| 70 | } |
| 71 | |
| 72 | var expiresTime = time.Time{} |
| 73 | var rawElement = nft.SetElement{ |
| 74 | Key: key, |
| 75 | } |
| 76 | if options != nil { |
| 77 | rawElement.Timeout = options.Timeout |
| 78 | |
| 79 | if options.Timeout > 0 { |
| 80 | expiresTime = time.UnixMilli(time.Now().UnixMilli() + options.Timeout.Milliseconds()) |
| 81 | } |
| 82 | } |
| 83 | err := this.conn.Raw().SetAddElements(this.rawSet, []nft.SetElement{ |
| 84 | rawElement, |
| 85 | }) |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | |
| 90 | err = this.conn.Commit() |
| 91 | if err == nil { |
| 92 | if this.expiration != nil { |
| 93 | this.expiration.Add(key, expiresTime) |
| 94 | } |
| 95 | } else { |
| 96 | var isFileExistsErr = strings.Contains(err.Error(), "file exists") |
| 97 | if !overwrite && isFileExistsErr { |
| 98 | // ignore file exists error |
| 99 | return nil |
| 100 | } |
| 101 | |
| 102 | // retry if exists |
| 103 | if overwrite && isFileExistsErr { |
| 104 | deleteErr := this.conn.Raw().SetDeleteElements(this.rawSet, []nft.SetElement{ |
| 105 | { |
| 106 | Key: key, |
| 107 | }, |
| 108 | }) |
| 109 | if deleteErr == nil { |
| 110 | err = this.conn.Raw().SetAddElements(this.rawSet, []nft.SetElement{ |
| 111 | rawElement, |
| 112 | }) |
| 113 | if err == nil { |
| 114 | err = this.conn.Commit() |
| 115 | if err == nil { |
| 116 | if this.expiration != nil { |
| 117 | this.expiration.Add(key, expiresTime) |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | } |