Debian Codegraph @

paho/store/file/store.go

raw
1 /*
2 * Copyright (c) 2024 Contributors to the Eclipse Foundation
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v2.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * https://www.eclipse.org/legal/epl-2.0/
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
14 */
15
16 package file
17
18 import (
19 "fmt"
20 "io"
21 "os"
22 "path/filepath"
23 "sort"
24 "strconv"
25 "sync"
26 "time"
27 )
28
29 const (
30 folderPermissions = os.FileMode(0770)
31 filePermissions = os.FileMode(0666)
32 tmpExtension = ".tmp"
33 corruptExtension = ".CORRUPT" // quarantined files will be given this extension
34 )
35
36 // New creates a file Store. Note that a file is written, read and deleted as part of this process to check that the
37 // path is usable.
38 // NOTE: Order is maintained using file ModTime, so there may be issues if the interval between messages is less than
39 // the file system ModTime resolution.
40 func New(path string, prefix string, extension string) (*Store, error) {
41 if len(extension) > 0 && extension[0] != '.' {
42 extension = "." + extension
43 }
44
45 if err := os.MkdirAll(path, folderPermissions); err != nil {
46 return nil, fmt.Errorf("failed to create store folder: %w", err)
47 }
48
49 // Better to fail fast; so we check that a file can be written/read with the passed in info
50 fn := filepath.Join(path, prefix+"TEST"+extension)
51 if err := os.WriteFile(fn, []byte("test"), filePermissions); err != nil {
52 return nil, fmt.Errorf("failed to write test file to specified folder: %w", err)
53 }
54 if _, err := os.ReadFile(fn); err != nil {
55 return nil, fmt.Errorf("failed to read test file from specified folder: %w", err)
56 }
57 if err := os.Remove(fn); err != nil {
58 return nil, fmt.Errorf("failed to remove test file from specified folder: %w", err)
59 }
60
61 return &Store{
62 path: path,
63 prefix: prefix,
64 extension: extension,
65 }, nil
66
67 }
68
69 // Store is an implementation of a Store that stores the data on disk
70 type Store struct {
71 // server store - holds packets where the message ID was generated on the server
72 sync.Mutex // Is this needed?
73 path string
74 prefix string
75 extension string
76 }
77
78 // Put stores the packet
79 // The store is performed via a temporary file to reduce the chance that a partially written file will
80 // cause issues.
81 func (s *Store) Put(packetID uint16, packetType byte, w io.WriterTo) error {
82 s.Lock()
83 defer s.Unlock()
84
85 f, err := os.CreateTemp(s.path, s.fileNamePrefix(packetID)+"-*"+s.extension+tmpExtension)
86 if err != nil {
87 return fmt.Errorf("failed to create temp file: %w", err)
88 }
89 tmpFn := f.Name()
90 if _, err = w.WriteTo(f); err != nil {
91 f.Close()
92 _ = os.Remove(tmpFn)
93 return fmt.Errorf("failed to write packet to temp file: %w", err)
94 }
95 f.Sync() // want timestamps to be as accurate as possible (close and rename do not imply sync)
96 if err = f.Close(); err != nil {
97 _ = os.Remove(tmpFn)
98 return fmt.Errorf("failed to close temp file: %w", err)
99 }
100 if err = os.Rename(tmpFn, s.filePathForId(packetID)); err != nil {
101 _ = os.Remove(tmpFn)
102 return fmt.Errorf("failed to rename temp file: %w", err)
103 }
104 return nil
105 }
106
107 // Get retrieves the requested packet
108 // Note that callers MUST close the returned ReadCloser
109 func (s *Store) Get(packetID uint16) (io.ReadCloser, error) {
110 s.Lock()
111 defer s.Unlock()
112 f, err := os.OpenFile(s.filePathForId(packetID), os.O_RDONLY, 0)
113 if err != nil {
114 return nil, fmt.Errorf("failed to open packet file: %w", err)
115 }
116 return f, nil
117 }
118
119 // Delete removes the message with the specified store ID
120 func (s *Store) Delete(id uint16) error {
121 s.Lock()
122 defer s.Unlock()
123 return s.delete(id)
124 }
125
126 // Quarantine is called if a corrupt packet is detected.
127 // There is little we can do other than deleting the packet.
128 func (s *Store) Quarantine(id uint16) error {
129 s.Lock()
130 defer s.Unlock()
131 f, err := os.CreateTemp(s.path, s.fileNamePrefix(id)+"-*"+s.extension+corruptExtension)
132 if err != nil {
133 s.delete(id) // delete the file (otherwise it may be sent on every reconnection)
134 return fmt.Errorf("failed to create quarantine file: %w", err)
135 }
136 tmpFn := f.Name()
137 if err := f.Close(); err != nil {
138 s.delete(id) // delete the file (otherwise it may be sent on every reconnection)
139 return fmt.Errorf("failed to close newly created quarantine file: %w", err)
140 }
141 if err := os.Rename(s.filePathForId(id), tmpFn); err != nil {
142 s.delete(id) // delete the file (otherwise it may be sent on every reconnection)
143 return fmt.Errorf("failed to move packet into quarantine: %w", err)
144 }
145 return nil
146 }
147
148 type idAndModTime struct {
149 id uint16
150 modTime time.Time
151 }
152
153 // List returns packet IDs in the order they were Put
154 func (s *Store) List() ([]uint16, error) {
155 s.Lock()
156 defer s.Unlock()
157
158 return s.list()
159 }
160
161 // Reset clears the store (deleting all messages)
162 func (s *Store) Reset() error {
163 s.Lock()
164 defer s.Unlock()
165 ids, err := s.list()
166 if err != nil {
167 return err
168 }
169 for _, id := range ids {
170 if dErr := s.delete(id); dErr != nil {
171 err = dErr // Attempt to delete all files and just return the last error
172 }
173 }
174 return err
175 }
176
177 // String is for debugging purposes; it's too expensive to read in the data for this
178 func (s *Store) String() string {
179 return fmt.Sprintf("store path: %s, prefix: %s, extension: %s", s.path, s.prefix, s.extension)
180 }
181
182 // list returns packet IDs in the order they were Put
183 // caller must lock mutex
184 func (s *Store) list() ([]uint16, error) {
185 entries, err := os.ReadDir(s.path)
186 if err != nil {
187 return nil, fmt.Errorf("failed to read dir: %w", err)
188 }
189
190 ids := make([]idAndModTime, 0, len(entries))
191 for _, entry := range entries {
192 if entry.IsDir() {
193 continue
194 }
195 fn := entry.Name()
196 if match, err := filepath.Match(s.prefix+"*"+s.extension, fn); err != nil {
197 return nil, fmt.Errorf("failed to read match %s: %w", fn, err)
198 } else if !match {
199 continue
200 }
201 info, err := entry.Info()
202 if err != nil {
203 return nil, fmt.Errorf("failed to retrieve file info for %s: %w", fn, err)
204 }
205 idStr := fn[len(s.prefix) : len(fn)-len(s.extension)]
206 id, err := strconv.ParseInt(idStr, 10, 0)
207 if err != nil { // Could ignore, but raising an error seems safer
208 return nil, fmt.Errorf("invalid id in filename %s", fn)
209 }
210 ids = append(ids, idAndModTime{uint16(id), info.ModTime()}) // Possible this will truncate id
211 }
212 sort.Slice(ids, func(i, j int) bool {
213 return ids[i].modTime.Before(ids[j].modTime)
214 })
215 ret := make([]uint16, len(entries))
216 for i := range ids {
217 ret[i] = ids[i].id
218 }
219 return ret, nil
220 }
221
222 // delete removes the message with the specified store ID
223 // caller must gain any required locks
224 func (s *Store) delete(id uint16) error {
225 if err := os.Remove(s.filePathForId(id)); err != nil {
226 return fmt.Errorf("failed to remove packet file: %w", err)
227 }
228 return nil
229 }
230
231 // filePathForId returns the full path of the file used to store info for the passed in packet id
232 func (s *Store) filePathForId(packetID uint16) string {
233 return filepath.Join(s.path, s.fileNamePrefix(packetID)+s.extension)
234 }
235
236 // fileNamePrefix returns the beginning of the filename for the specified packet ID
237 func (s *Store) fileNamePrefix(packetID uint16) string {
238 return s.prefix + strconv.FormatInt(int64(packetID), 10)
239 }