MCPcopy Index your code
hub / github.com/simstudioai/sim / readTableEventsSince

Function readTableEventsSince

apps/sim/lib/table/events.ts:285–340  ·  view source on GitHub ↗
(
  tableId: string,
  afterEventId: number
)

Source from the content-addressed store, hash-verified

283 * and resuming streaming from the new earliestEventId.
284 */
285export async function readTableEventsSince(
286 tableId: string,
287 afterEventId: number
288): Promise<TableEventsReadResult> {
289 const redis = getRedisClient()
290 if (!redis) {
291 if (canUseMemoryBuffer()) {
292 return readMemory(tableId, afterEventId)
293 }
294 return { status: 'unavailable', error: 'Redis client unavailable' }
295 }
296 try {
297 const meta = await redis.hgetall(getMetaKey(tableId))
298 const earliestEventId =
299 meta?.earliestEventId !== undefined ? Number(meta.earliestEventId) : undefined
300 if (earliestEventId !== undefined && afterEventId + 1 < earliestEventId) {
301 return { status: 'pruned', earliestEventId }
302 }
303 // Read in capped chunks so a 5000-event backlog doesn't materialize as one
304 // multi-MB Redis reply + JSON parse + SSE flush. The route loop drains
305 // chunks across ticks.
306 const raw = await redis.zrangebyscore(
307 getEventsKey(tableId),
308 afterEventId + 1,
309 '+inf',
310 'LIMIT',
311 0,
312 TABLE_EVENT_READ_CHUNK
313 )
314 if (raw.length === 0 && afterEventId > 0) {
315 // Total TTL expiry: events + meta both gone. The seq counter has the
316 // same TTL — its absence means the buffer was wiped and the caller's
317 // `afterEventId` is stale. Signal pruned so the client refetches.
318 const seqExists = await redis.exists(getSeqKey(tableId))
319 if (seqExists === 0) {
320 return { status: 'pruned', earliestEventId: undefined }
321 }
322 }
323 return {
324 status: 'ok',
325 events: raw
326 .map((entry) => {
327 try {
328 return JSON.parse(entry) as TableEventEntry
329 } catch {
330 return null
331 }
332 })
333 .filter((entry): entry is TableEventEntry => Boolean(entry)),
334 }
335 } catch (error) {
336 const message = toError(error).message
337 logger.warn('readTableEventsSince failed', { tableId, error: message })
338 return { status: 'unavailable', error: message }
339 }
340}

Callers 1

startFunction · 0.90

Calls 10

getRedisClientFunction · 0.90
toErrorFunction · 0.90
canUseMemoryBufferFunction · 0.85
readMemoryFunction · 0.85
existsMethod · 0.80
parseMethod · 0.80
getMetaKeyFunction · 0.70
getEventsKeyFunction · 0.70
getSeqKeyFunction · 0.70
warnMethod · 0.65

Tested by

no test coverage detected