|
| 1 | +/* |
| 2 | + * Copyright 2024-2026 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package io.agentscope.durable; |
| 17 | + |
| 18 | +import io.agentscope.durable.DurableTypes.EventPage; |
| 19 | +import io.agentscope.durable.DurableTypes.PublicEvent; |
| 20 | +import io.agentscope.durable.DurableTypes.SessionActivity; |
| 21 | +import io.agentscope.durable.DurableTypes.SessionKey; |
| 22 | +import io.agentscope.durable.DurableTypes.SessionPhase; |
| 23 | +import io.agentscope.durable.store.RecordStore; |
| 24 | +import java.util.ArrayList; |
| 25 | +import java.util.Collection; |
| 26 | +import java.util.List; |
| 27 | +import java.util.Locale; |
| 28 | +import java.util.Map; |
| 29 | +import java.util.TreeMap; |
| 30 | +import java.util.TreeSet; |
| 31 | + |
| 32 | +/** Storage-side ordered index used by a payload-bearing Session event transport. */ |
| 33 | +public final class SessionCommittedLog { |
| 34 | + public record Entry(String stream, PublicEvent event) {} |
| 35 | + |
| 36 | + public record Prune(String stream, long through) {} |
| 37 | + |
| 38 | + public record Published(PublicEvent event, PublicEvent threadEvent) {} |
| 39 | + |
| 40 | + private record Stored(String stream, long offset, PublicEvent event) {} |
| 41 | + |
| 42 | + public static final class Head { |
| 43 | + public long sequence; |
| 44 | + public long retained; |
| 45 | + public String retainedCursor; |
| 46 | + public Map<String, Long> offsets = new TreeMap<>(); |
| 47 | + public Map<String, SessionActivity> activity = new TreeMap<>(); |
| 48 | + } |
| 49 | + |
| 50 | + private SessionCommittedLog() {} |
| 51 | + |
| 52 | + public static String key(SessionKey session) { |
| 53 | + return "committed-session-events:" + DurableJson.hash(session); |
| 54 | + } |
| 55 | + |
| 56 | + private static Head head(RecordStore.Transaction tx) { |
| 57 | + var value = tx.get(""); |
| 58 | + return value == null ? null : DurableJson.convert(value, Head.class); |
| 59 | + } |
| 60 | + |
| 61 | + static boolean exists(RecordStore.Transaction tx) { |
| 62 | + return head(tx) != null; |
| 63 | + } |
| 64 | + |
| 65 | + public static List<Published> append(RecordStore.Transaction tx, List<Entry> entries) { |
| 66 | + if (entries.isEmpty()) return List.of(); |
| 67 | + var first = entries.get(0); |
| 68 | + var head = head(tx); |
| 69 | + if (head == null) { |
| 70 | + // A Session that predates application of this storage mode keeps its existing history. |
| 71 | + if (!first.stream().isEmpty() || !"1".equals(first.event().sequence())) |
| 72 | + return List.of(); |
| 73 | + head = new Head(); |
| 74 | + } |
| 75 | + var events = new ArrayList<Published>(); |
| 76 | + for (var entry : entries) { |
| 77 | + var raw = entry.event(); |
| 78 | + long offset = Long.parseLong(raw.sequence()); |
| 79 | + if (offset != head.offsets.getOrDefault(entry.stream(), 0L) + 1) |
| 80 | + throw new DurableException( |
| 81 | + DurableException.Code.CONFLICT, "Session committed event index has a gap"); |
| 82 | + head.offsets.put(entry.stream(), offset); |
| 83 | + String type = raw.type(); |
| 84 | + String thread = raw.threadId(); |
| 85 | + var data = raw.data(); |
| 86 | + if ("thread.activity_changed".equals(type)) { |
| 87 | + var previous = activity(head.activity.values()); |
| 88 | + head.activity.put(entry.stream(), DurableJson.convert(data, SessionActivity.class)); |
| 89 | + var next = activity(head.activity.values()); |
| 90 | + if (!next.equals(previous)) { |
| 91 | + type = "session.activity_changed"; |
| 92 | + thread = null; |
| 93 | + data = DurableJson.value(next); |
| 94 | + } |
| 95 | + } |
| 96 | + long sequence = ++head.sequence; |
| 97 | + var event = |
| 98 | + new PublicEvent( |
| 99 | + raw.schemaVersion(), |
| 100 | + raw.eventId(), |
| 101 | + raw.session(), |
| 102 | + thread, |
| 103 | + raw.turnId(), |
| 104 | + raw.runId(), |
| 105 | + raw.stepId(), |
| 106 | + Long.toString(sequence), |
| 107 | + SessionEventCursor.encode(raw.session(), head.offsets), |
| 108 | + raw.occurredAt(), |
| 109 | + type, |
| 110 | + data); |
| 111 | + tx.put(part(sequence), DurableJson.value(new Stored(entry.stream(), offset, event))); |
| 112 | + tx.put(source(entry.stream(), offset), DurableJson.value(sequence)); |
| 113 | + events.add(new Published(event, entry.stream().isEmpty() ? null : raw)); |
| 114 | + } |
| 115 | + tx.put("", DurableJson.value(head)); |
| 116 | + return events; |
| 117 | + } |
| 118 | + |
| 119 | + public static void prune(RecordStore.Transaction tx, List<Prune> prunes) { |
| 120 | + if (prunes.isEmpty()) return; |
| 121 | + var head = head(tx); |
| 122 | + if (head == null) return; |
| 123 | + long through = head.retained; |
| 124 | + for (var prune : prunes) { |
| 125 | + var sequence = tx.get(source(prune.stream(), prune.through())); |
| 126 | + if (sequence != null) through = Math.max(through, sequence.longValue()); |
| 127 | + } |
| 128 | + if (through == head.retained) return; |
| 129 | + for (long sequence = head.retained + 1; sequence <= through; sequence++) { |
| 130 | + var value = read(tx, sequence); |
| 131 | + tx.put(source(value.stream(), value.offset()), null); |
| 132 | + tx.put(part(sequence), null); |
| 133 | + head.retainedCursor = value.event().cursor(); |
| 134 | + } |
| 135 | + head.retained = through; |
| 136 | + tx.put("", DurableJson.value(head)); |
| 137 | + } |
| 138 | + |
| 139 | + static EventPage page( |
| 140 | + RecordStore.Transaction tx, |
| 141 | + SessionKey session, |
| 142 | + String cursor, |
| 143 | + int limit, |
| 144 | + boolean reverse) { |
| 145 | + var head = head(tx); |
| 146 | + if (head == null) return null; |
| 147 | + String high = SessionEventCursor.encode(session, head.offsets); |
| 148 | + long position = |
| 149 | + cursor == null |
| 150 | + ? (reverse ? head.sequence + 1 : 0) |
| 151 | + : position(tx, session, head, cursor); |
| 152 | + if (!reverse && position < head.retained |
| 153 | + || reverse && cursor != null && head.retained > 0 && position - 1 <= head.retained) |
| 154 | + throw expired(); |
| 155 | + var events = new ArrayList<PublicEvent>(); |
| 156 | + if (reverse) { |
| 157 | + for (long i = position - 1; i > head.retained && events.size() < limit; i--) |
| 158 | + events.add(read(tx, i).event()); |
| 159 | + } else { |
| 160 | + var parts = tx.parts("ordered:", part(position), limit); |
| 161 | + parts.forEach( |
| 162 | + value -> events.add(DurableJson.convert(value.value(), Stored.class).event())); |
| 163 | + } |
| 164 | + String scanned = |
| 165 | + events.isEmpty() |
| 166 | + ? cursor == null ? SessionEventCursor.encode(session, Map.of()) : cursor |
| 167 | + : events.get(events.size() - 1).cursor(); |
| 168 | + String sequence = |
| 169 | + events.isEmpty() |
| 170 | + ? Long.toString(reverse && cursor == null ? 0 : position) |
| 171 | + : events.get(events.size() - 1).sequence(); |
| 172 | + return new EventPage(events, scanned, high, sequence, Long.toString(head.sequence)); |
| 173 | + } |
| 174 | + |
| 175 | + private static long position( |
| 176 | + RecordStore.Transaction tx, SessionKey session, Head head, String cursor) { |
| 177 | + try { |
| 178 | + var fields = SessionEventCursor.decode(session, cursor).fields(); |
| 179 | + long position = 0; |
| 180 | + while (fields.hasNext()) { |
| 181 | + var value = fields.next(); |
| 182 | + long offset = value.getValue().longValue(); |
| 183 | + if (!value.getValue().isIntegralNumber() |
| 184 | + || !value.getValue().canConvertToLong() |
| 185 | + || offset <= 0 |
| 186 | + || offset > head.offsets.getOrDefault(value.getKey(), 0L)) |
| 187 | + throw new IllegalArgumentException(); |
| 188 | + position = Math.addExact(position, offset); |
| 189 | + } |
| 190 | + if (position < head.retained) throw expired(); |
| 191 | + String expected = |
| 192 | + position == 0 |
| 193 | + ? SessionEventCursor.encode(session, Map.of()) |
| 194 | + : position == head.retained |
| 195 | + ? head.retainedCursor |
| 196 | + : read(tx, position).event().cursor(); |
| 197 | + if (!cursor.equals(expected)) throw new IllegalArgumentException(); |
| 198 | + return position; |
| 199 | + } catch (IllegalArgumentException | ArithmeticException invalid) { |
| 200 | + throw new DurableException( |
| 201 | + DurableException.Code.INVALID, "Invalid Session event cursor"); |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + private static DurableException expired() { |
| 206 | + return new DurableException( |
| 207 | + DurableException.Code.CURSOR_EXPIRED, "Cursor expired; load a snapshot"); |
| 208 | + } |
| 209 | + |
| 210 | + private static Stored read(RecordStore.Transaction tx, long sequence) { |
| 211 | + return DurableJson.convert(tx.get(part(sequence)), Stored.class); |
| 212 | + } |
| 213 | + |
| 214 | + private static String part(long sequence) { |
| 215 | + return "ordered:" + String.format(Locale.ROOT, "%020d", sequence); |
| 216 | + } |
| 217 | + |
| 218 | + private static String source(String stream, long offset) { |
| 219 | + return "source:" + DurableJson.hash(stream) + ":" + offset; |
| 220 | + } |
| 221 | + |
| 222 | + static SessionActivity activity(Collection<SessionActivity> states) { |
| 223 | + var pending = new TreeSet<String>(); |
| 224 | + boolean exhausted = false; |
| 225 | + for (var state : states) { |
| 226 | + if (state.phase() == SessionPhase.RUNNING) |
| 227 | + return new SessionActivity(SessionPhase.RUNNING, List.of()); |
| 228 | + pending.addAll(state.interactionIds()); |
| 229 | + exhausted |= state.phase() == SessionPhase.RETRIES_EXHAUSTED; |
| 230 | + } |
| 231 | + if (!pending.isEmpty()) |
| 232 | + return new SessionActivity(SessionPhase.REQUIRES_ACTION, List.copyOf(pending)); |
| 233 | + return new SessionActivity( |
| 234 | + exhausted ? SessionPhase.RETRIES_EXHAUSTED : SessionPhase.IDLE, List.of()); |
| 235 | + } |
| 236 | +} |
0 commit comments