|
13 | 13 | import com.github.sonus21.rqueue.config.NatsBackendCondition; |
14 | 14 | import com.github.sonus21.rqueue.dao.RqueueJobDao; |
15 | 15 | import com.github.sonus21.rqueue.models.db.RqueueJob; |
| 16 | +import io.nats.client.Connection; |
| 17 | +import io.nats.client.JetStreamApiException; |
| 18 | +import io.nats.client.KeyValue; |
| 19 | +import io.nats.client.KeyValueManagement; |
| 20 | +import io.nats.client.api.KeyValueConfiguration; |
| 21 | +import io.nats.client.api.KeyValueEntry; |
| 22 | +import io.nats.client.api.KeyValueStatus; |
| 23 | +import java.io.ByteArrayInputStream; |
| 24 | +import java.io.ByteArrayOutputStream; |
| 25 | +import java.io.IOException; |
| 26 | +import java.io.ObjectInputStream; |
| 27 | +import java.io.ObjectOutputStream; |
16 | 28 | import java.time.Duration; |
| 29 | +import java.util.ArrayList; |
17 | 30 | import java.util.Collection; |
18 | 31 | import java.util.Collections; |
19 | 32 | import java.util.List; |
| 33 | +import java.util.concurrent.atomic.AtomicReference; |
| 34 | +import java.util.logging.Level; |
| 35 | +import java.util.logging.Logger; |
20 | 36 | import org.springframework.context.annotation.Conditional; |
21 | 37 | import org.springframework.stereotype.Repository; |
22 | 38 |
|
23 | 39 | /** |
24 | | - * NATS-backend stub for {@link RqueueJobDao}. Job tracking persistence is a Redis-only feature |
25 | | - * in v1; this stub returns empty/null and silently drops writes so the bean graph stays |
26 | | - * consistent. A NATS-native implementation can replace this in a follow-up. |
| 40 | + * NATS-backed {@link RqueueJobDao} using a JetStream KV bucket as the job store. Entries are |
| 41 | + * keyed by job id and serialized via Java serialization. Look-ups by message id walk the bucket |
| 42 | + * keys; for the volumes rqueue typically tracks (current in-flight + recent retry history) this |
| 43 | + * is acceptable for v1 — the Redis impl uses an explicit reverse index, that's a follow-up here. |
| 44 | + * |
| 45 | + * <p>The {@code expiry} on save / create is currently best-effort: the bucket is created on the |
| 46 | + * first call with the expiry as its TTL. Subsequent saves reuse the same bucket regardless of |
| 47 | + * the requested per-key expiry. |
27 | 48 | */ |
28 | 49 | @Repository |
29 | 50 | @Conditional(NatsBackendCondition.class) |
30 | 51 | public class NatsRqueueJobDao implements RqueueJobDao { |
| 52 | + |
| 53 | + private static final Logger log = Logger.getLogger(NatsRqueueJobDao.class.getName()); |
| 54 | + private static final String BUCKET_NAME = "rqueue-jobs"; |
| 55 | + |
| 56 | + private final Connection connection; |
| 57 | + private final KeyValueManagement kvm; |
| 58 | + private final AtomicReference<KeyValue> kvRef = new AtomicReference<>(); |
| 59 | + |
| 60 | + public NatsRqueueJobDao(Connection connection) throws IOException { |
| 61 | + this.connection = connection; |
| 62 | + this.kvm = connection.keyValueManagement(); |
| 63 | + } |
| 64 | + |
| 65 | + private KeyValue ensureBucket(Duration ttl) throws IOException, JetStreamApiException { |
| 66 | + KeyValue cached = kvRef.get(); |
| 67 | + if (cached != null) { |
| 68 | + return cached; |
| 69 | + } |
| 70 | + synchronized (this) { |
| 71 | + cached = kvRef.get(); |
| 72 | + if (cached != null) { |
| 73 | + return cached; |
| 74 | + } |
| 75 | + try { |
| 76 | + KeyValueStatus status = kvm.getStatus(BUCKET_NAME); |
| 77 | + if (status != null) { |
| 78 | + KeyValue kv = connection.keyValue(BUCKET_NAME); |
| 79 | + kvRef.set(kv); |
| 80 | + return kv; |
| 81 | + } |
| 82 | + } catch (JetStreamApiException missing) { |
| 83 | + // fall through |
| 84 | + } |
| 85 | + KeyValueConfiguration.Builder cfg = KeyValueConfiguration.builder().name(BUCKET_NAME); |
| 86 | + if (ttl != null && !ttl.isZero() && !ttl.isNegative()) { |
| 87 | + cfg.ttl(ttl); |
| 88 | + } |
| 89 | + kvm.create(cfg.build()); |
| 90 | + KeyValue kv = connection.keyValue(BUCKET_NAME); |
| 91 | + kvRef.set(kv); |
| 92 | + return kv; |
| 93 | + } |
| 94 | + } |
| 95 | + |
31 | 96 | @Override |
32 | | - public void createJob(RqueueJob rqueueJob, Duration expiry) {} |
| 97 | + public void createJob(RqueueJob rqueueJob, Duration expiry) { |
| 98 | + save(rqueueJob, expiry); |
| 99 | + } |
33 | 100 |
|
34 | 101 | @Override |
35 | | - public void save(RqueueJob rqueueJob, Duration expiry) {} |
| 102 | + public void save(RqueueJob rqueueJob, Duration expiry) { |
| 103 | + try { |
| 104 | + KeyValue kv = ensureBucket(expiry); |
| 105 | + kv.put(sanitize(rqueueJob.getId()), serialize(rqueueJob)); |
| 106 | + } catch (IOException | JetStreamApiException e) { |
| 107 | + log.log(Level.WARNING, "save job " + rqueueJob.getId() + " failed", e); |
| 108 | + } |
| 109 | + } |
36 | 110 |
|
37 | 111 | @Override |
38 | 112 | public RqueueJob findById(String jobId) { |
39 | | - return null; |
| 113 | + return loadByKey(sanitize(jobId)); |
40 | 114 | } |
41 | 115 |
|
42 | 116 | @Override |
43 | 117 | public List<RqueueJob> findJobsByIdIn(Collection<String> jobIds) { |
44 | | - return Collections.emptyList(); |
| 118 | + List<RqueueJob> out = new ArrayList<>(jobIds.size()); |
| 119 | + for (String id : jobIds) { |
| 120 | + RqueueJob j = findById(id); |
| 121 | + if (j != null) { |
| 122 | + out.add(j); |
| 123 | + } |
| 124 | + } |
| 125 | + return out; |
45 | 126 | } |
46 | 127 |
|
47 | 128 | @Override |
48 | | - public List<RqueueJob> finByMessageIdIn(List<String> messageIds) { |
49 | | - return Collections.emptyList(); |
| 129 | + public List<RqueueJob> finByMessageId(String messageId) { |
| 130 | + if (messageId == null) { |
| 131 | + return Collections.emptyList(); |
| 132 | + } |
| 133 | + return scanForMessageIds(Collections.singletonList(messageId)); |
50 | 134 | } |
51 | 135 |
|
52 | 136 | @Override |
53 | | - public List<RqueueJob> finByMessageId(String messageId) { |
54 | | - return Collections.emptyList(); |
| 137 | + public List<RqueueJob> finByMessageIdIn(List<String> messageIds) { |
| 138 | + if (messageIds == null || messageIds.isEmpty()) { |
| 139 | + return Collections.emptyList(); |
| 140 | + } |
| 141 | + return scanForMessageIds(messageIds); |
55 | 142 | } |
56 | 143 |
|
57 | 144 | @Override |
58 | | - public void delete(String jobId) {} |
| 145 | + public void delete(String jobId) { |
| 146 | + try { |
| 147 | + KeyValue kv = ensureBucket(null); |
| 148 | + kv.delete(sanitize(jobId)); |
| 149 | + } catch (IOException | JetStreamApiException e) { |
| 150 | + log.log(Level.WARNING, "delete job " + jobId + " failed", e); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + // ---- helpers ---------------------------------------------------------- |
| 155 | + |
| 156 | + private RqueueJob loadByKey(String key) { |
| 157 | + try { |
| 158 | + KeyValue kv = ensureBucket(null); |
| 159 | + KeyValueEntry entry = kv.get(key); |
| 160 | + if (entry == null || entry.getValue() == null) { |
| 161 | + return null; |
| 162 | + } |
| 163 | + return deserialize(entry.getValue()); |
| 164 | + } catch (IOException | JetStreamApiException e) { |
| 165 | + log.log(Level.WARNING, "loadByKey " + key + " failed", e); |
| 166 | + return null; |
| 167 | + } |
| 168 | + } |
| 169 | + |
| 170 | + private List<RqueueJob> scanForMessageIds(Collection<String> messageIds) { |
| 171 | + try { |
| 172 | + KeyValue kv = ensureBucket(null); |
| 173 | + List<String> keys = new ArrayList<>(kv.keys()); |
| 174 | + List<RqueueJob> out = new ArrayList<>(); |
| 175 | + for (String k : keys) { |
| 176 | + RqueueJob j = loadByKey(k); |
| 177 | + if (j != null && messageIds.contains(j.getMessageId())) { |
| 178 | + out.add(j); |
| 179 | + } |
| 180 | + } |
| 181 | + return out; |
| 182 | + } catch (IOException | JetStreamApiException | InterruptedException e) { |
| 183 | + log.log(Level.WARNING, "scanForMessageIds failed", e); |
| 184 | + if (e instanceof InterruptedException) { |
| 185 | + Thread.currentThread().interrupt(); |
| 186 | + } |
| 187 | + return Collections.emptyList(); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + private static byte[] serialize(RqueueJob job) throws IOException { |
| 192 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 193 | + try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { |
| 194 | + oos.writeObject(job); |
| 195 | + } |
| 196 | + return baos.toByteArray(); |
| 197 | + } |
| 198 | + |
| 199 | + private static RqueueJob deserialize(byte[] bytes) { |
| 200 | + try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes))) { |
| 201 | + Object o = ois.readObject(); |
| 202 | + return o instanceof RqueueJob ? (RqueueJob) o : null; |
| 203 | + } catch (IOException | ClassNotFoundException e) { |
| 204 | + log.log(Level.WARNING, "deserialize RqueueJob failed", e); |
| 205 | + return null; |
| 206 | + } |
| 207 | + } |
| 208 | + |
| 209 | + /** KV keys allow {@code [A-Za-z0-9_=.-]} only. */ |
| 210 | + private static String sanitize(String key) { |
| 211 | + return key == null ? "_" : key.replaceAll("[^A-Za-z0-9_=.-]", "_"); |
| 212 | + } |
59 | 213 | } |
0 commit comments