Debian Codegraph @

autopaho/queue/file/queue.go

raw symbols SCIP
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 "sync"
24 "time"
25
26 "github.com/eclipse/paho.golang/autopaho/queue"
27 )
28
29 // A queue implementation that stores all data on disk
30 // This will be slow when there are a lot of messages queued. That is because the directory is read with every call to
31 // Peek/DeQueue (could cache some of this in RAM, but there is a reasonable chance that the OS does this for us).
32
33 const (
34 folderPermissions = os.FileMode(0770)
35 filePermissions = os.FileMode(0666)
36 corruptExtension = ".CORRUPT" // quarantined files will be given this extension
37 )
38
39 var (
40 maxTime = time.Unix(1<<63-62135596801, 999999999)
41 )
42
43 // Queue - basic file based queue
44 type Queue struct {
45 mu sync.Mutex
46 path string
47 prefix string
48 extension string
49 queueEmpty bool // true is the queue is currently empty
50 waiting []chan<- struct{} // closed when something arrives in the queue
51 waitingForEmpty []chan<- struct{} // closed when queue is empty
52 }
53
54 // New creates a new file-based queue. Note that a file is written, read and deleted as part of this process to check
55 // that the path is usable.
56 // NOTE: Order is maintained using file ModTime, so there may be issues if the interval between messages is less than
57 // the file system ModTime resolution.
58 func New(path string, prefix string, extension string) (*Queue, error) {
59 if len(extension) > 0 && extension[0] != '.' {
60 extension = "." + extension
61 }
62
63 if err := os.MkdirAll(path, folderPermissions); err != nil {
64 return nil, fmt.Errorf("failed to create store folder: %w", err)
65 }
66
67 // Better to fail fast; so we check that a file can be written/read with the passed in info
68 fn := filepath.Join(path, prefix+"TEST"+extension)
69 if err := os.WriteFile(fn, []byte("test"), filePermissions); err != nil {
70 return nil, fmt.Errorf("failed to write test file to specified folder: %w", err)
71 }
72 if _, err := os.ReadFile(fn); err != nil {
73 return nil, fmt.Errorf("failed to read test file from specified folder: %w", err)
74 }
75 if err := os.Remove(fn); err != nil {
76 return nil, fmt.Errorf("failed to remove test file from specified folder: %w", err)
77 }
78
79 q := &Queue{
80 path: path,
81 prefix: prefix,
82 extension: extension,
83 }
84
85 _, err := q.oldestEntry()
86 if err == io.EOF {
87 q.queueEmpty = true
88 } else if err != nil {
89 return nil, fmt.Errorf("failed checking for oldest entry: %w", err)
90 }
91
92 return q, nil
93
94 }
95
96 // Wait returns a channel that will be closed when there is something in the queue
97 func (q *Queue) Wait() chan struct{} {
98 c := make(chan struct{})
99 q.mu.Lock()
100 if !q.queueEmpty {
101 q.mu.Unlock()
102 close(c)
103 return c
104 }
105 q.waiting = append(q.waiting, c)
106 q.mu.Unlock()
107 return c
108 }
109
110 // WaitForEmpty returns a channel that is closed when the queue is empty
111 func (q *Queue) WaitForEmpty() chan struct{} {
112 c := make(chan struct{})
113 q.mu.Lock()
114 if q.queueEmpty {
115 q.mu.Unlock()
116 close(c)
117 return c
118 }
119 q.waitingForEmpty = append(q.waitingForEmpty, c)
120 q.mu.Unlock()
121 return c
122 }
123
124 // Enqueue add item to the queue.
125 func (q *Queue) Enqueue(p io.Reader) error {
126 q.mu.Lock()
127 defer q.mu.Unlock()
128 err := q.put(p)
129 if err == nil && q.queueEmpty {
130 q.queueEmpty = false
131 for _, c := range q.waiting {
132 close(c)
133 }
134 q.waiting = q.waiting[:0]
135 }
136 return err
137 }
138
139 // Peek retrieves the oldest item from the queue (without removing it)
140 func (q *Queue) Peek() (queue.Entry, error) {
141 q.mu.Lock()
142 defer q.mu.Unlock()
143 if q.queueEmpty {
144 return nil, queue.ErrEmpty
145 }
146 e, err := q.get()
147 if err == io.EOF {
148 q.queueEmpty = true
149 for _, c := range q.waitingForEmpty {
150 close(c)
151 }
152 q.waitingForEmpty = q.waitingForEmpty[:0]
153 return nil, queue.ErrEmpty
154 }
155 return e, err
156 }
157
158 // put writes out an item to disk
159 func (q *Queue) put(p io.Reader) error {
160 // Use CreateTemp to generate a file with a unique name (it will be removed when packet has been transmitted)
161 f, err := os.CreateTemp(q.path, q.prefix+"*"+q.extension)
162 if err != nil {
163 return err
164 }
165
166 if _, err = io.Copy(f, p); err != nil {
167 f.Close()
168 _ = os.Remove(f.Name()) // Attempt to remove the partial file (not much we can do if this fails)
169 return err
170 }
171 if err = f.Close(); err != nil {
172 _ = os.Remove(f.Name()) // Attempt to remove the partial file (not much we can do if this fails)
173 return err
174 }
175 return nil
176 }
177
178 // get() returns a ReadCloser that accesses the oldest file available
179 // caller must hold lock on mu
180 func (q *Queue) get() (entry, error) {
181 fn, err := q.oldestEntry()
182 if err != nil {
183 return entry{}, err
184 }
185 f, err := os.Open(fn)
186 if err != nil {
187 return entry{}, err
188 }
189 return entry{f: f}, nil
190 }
191
192 // oldestEntry returns the filename of the oldest entry in the queue (if any - io.EOF means none)
193 func (q *Queue) oldestEntry() (string, error) {
194 entries, err := os.ReadDir(q.path)
195 if err != nil {
196 return "", fmt.Errorf("failed to read dir: %w", err)
197 }
198
199 // Search for the oldest file
200 var oldFn string
201 oldTime := maxTime
202
203 for _, entry := range entries {
204 if entry.IsDir() {
205 continue
206 }
207 fn := entry.Name()
208 if match, err := filepath.Match(q.prefix+"*"+q.extension, fn); err != nil {
209 return "", fmt.Errorf("failed to read match %s: %w", fn, err)
210 } else if !match {
211 continue
212 }
213 info, err := entry.Info()
214 if err != nil {
215 return "", fmt.Errorf("failed to retrieve file info for %s: %w", fn, err)
216 }
217 fileModTime := info.ModTime()
218 if !fileModTime.Before(oldTime) {
219 continue
220 }
221 oldFn = filepath.Join(q.path, fn)
222 oldTime = fileModTime
223 }
224 if oldTime.Equal(maxTime) {
225 return "", io.EOF
226 }
227 return oldFn, nil
228 }
229
230 // entry is used to return a queue entry from Peek
231 type entry struct {
232 f *os.File
233 }
234
235 // Reader provides access to the file contents
236 func (e entry) Reader() (io.Reader, error) {
237 return e.f, nil
238 }
239
240 // Leave closes the entry leaving it in the queue (will be returned on subsequent calls to Peek)
241 func (e entry) Leave() error {
242 return e.f.Close()
243 }
244
245 // Remove this entry from the queue
246 func (e entry) Remove() error {
247 cErr := e.f.Close() // Want to attempt to remove the file regardless of any errors here
248 if err := os.Remove(e.f.Name()); err != nil {
249 return err
250 }
251 if cErr != nil {
252 return cErr
253 }
254 return nil
255 }
256
257 // Quarantine flag that this entry has an error (remove from queue, potentially retaining data with error flagged)
258 func (e entry) Quarantine() error {
259 cErr := e.f.Close() // Want to attempt to move the file regardless of any errors here
260
261 // Attempt to add an extension so Peek no longer finds the file.
262 if err := os.Rename(e.f.Name(), e.f.Name()+corruptExtension); err != nil {
263 // Attempt to remove the file (important that we don't end up in an infinite loop retrieving the same file!)
264 if rErr := os.Remove(e.f.Name()); rErr != nil {
265 return err // Error from rename is best thing to return
266 }
267 return fmt.Errorf("rename failed so file deleted: %w", err)
268 }
269 if cErr != nil {
270 return cErr
271 }
272 return nil
273 }