Skip to content

feat(URL): Support seeking logs by timestamp via URL parameter (resolves #117). #152

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5477d0a
snapshot
Henry8192 Dec 1, 2024
4a8aeb7
draft without implementing getLogEventIdxByTimestamp
Henry8192 Dec 5, 2024
7f5cc7f
patch
Henry8192 Dec 6, 2024
54ef03c
implementing JSONL getLogEventIdxByTimestamp, fix timestamp type to b…
Henry8192 Dec 9, 2024
6c2b45a
fix JSONL getEventIdxByTimestamp + timestamp hash param not cleared
Henry8192 Dec 11, 2024
255f3e3
revert timestamp type back to Number; Only keeping bigint for DecodeR…
Henry8192 Dec 12, 2024
3972319
address changes from code review
Henry8192 Dec 19, 2024
5ecdaab
Merge branch 'main' into search-timestamp
Henry8192 Feb 10, 2025
f1f93f7
rename getLogEventIdxByTimestamp to getLogEventIdxByTimestamp
Henry8192 Feb 10, 2025
683350a
update clp-ffi-js dependency
Henry8192 Feb 11, 2025
7b72d93
Merge branch 'main' into search-timestamp
Henry8192 Feb 13, 2025
0cc3649
Add docstring for findNearestLogEventByTimestamp; Change function beh…
Henry8192 Feb 13, 2025
a81d570
Fix JSONL findNearestLogEventByTimestamp not always returning the cor…
Henry8192 Feb 16, 2025
e8e58f5
fix corner case
Henry8192 Feb 20, 2025
206b01f
minor format fixes
Henry8192 Feb 24, 2025
07ef527
Merge branch 'main' into search-timestamp
junhaoliao Feb 27, 2025
6c910d4
Merge branch 'main' into search-timestamp
junhaoliao Feb 28, 2025
bc16de2
Merge remote-tracking branch 'yscope/main' into search-timestamp
Henry8192 Mar 24, 2025
e04dadb
Merge branch 'main' into search-timestamp
Henry8192 Mar 24, 2025
3c051e8
temporarily lift state context provider's max lines; eventually we wi…
Henry8192 Mar 24, 2025
32de344
Merge branch 'main' into search-timestamp
Henry8192 May 21, 2025
127d56b
Merge branch 'main' into search-timestamp
Henry8192 May 21, 2025
e5725c2
finish merging main branch
Henry8192 May 21, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion src/components/AppController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,10 @@ interface AppControllerProps {
* @param props.children
* @return
*/
// eslint-disable-next-line max-lines-per-function,max-statements
const AppController = ({children}: AppControllerProps) => {
const {postPopUp} = useContext(NotificationContext);
const {filePath, isPrettified, logEventNum} = useContext(UrlContext);
const {filePath, isPrettified, logEventNum, timestamp} = useContext(UrlContext);

// States
const setLogEventNum = useContextStore((state) => state.setLogEventNum);
Expand All @@ -97,6 +98,7 @@ const AppController = ({children}: AppControllerProps) => {
// Refs
const isPrettifiedRef = useRef<boolean>(isPrettified ?? false);
const logEventNumRef = useRef(logEventNum);
const timestampRef = useRef(timestamp);

// Synchronize `logEventNumRef` with `logEventNum`.
useEffect(() => {
Expand All @@ -118,6 +120,37 @@ const AppController = ({children}: AppControllerProps) => {
setIsPrettified,
]);

// On `timestamp` update, findNearestLogEventByTimestamp and clear itself from URL.
useEffect(() => {
if (null === timestamp) {
return;
}

(async () => {
const cursor: CursorType = {
code: CURSOR_CODE.TIMESTAMP,
args: {timestamp: timestamp},
};

const pageData = await logFileManagerProxy.loadPage(cursor, isPrettifiedRef.current);
updatePageData(pageData);
})().catch((e: unknown) => {
console.error(e);
postPopUp({
level: LOG_LEVEL.ERROR,
message: String(e),
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Action failed",
});
});
updateWindowUrlHashParams({timestamp: null});
}, [
logFileManagerProxy,
postPopUp,
updatePageData,
timestamp,
]);
Comment on lines +124 to +152
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Implement timestamp tracking similar to logEventNum

The effect correctly handles timestamp changes by loading the corresponding page and clearing the timestamp from URL. However, unlike logEventNum, there's no code to update timestampRef when timestamp changes.

Consider adding an effect to synchronize timestampRef with timestamp, similar to how logEventNumRef is synchronized:

+// Synchronize `timestampRef` with `timestamp`.
+useEffect(() => {
+    timestampRef.current = timestamp;
+}, [timestamp]);

This would ensure that timestampRef always reflects the latest timestamp value.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
useEffect(() => {
if (null === timestamp) {
return;
}
(async () => {
const cursor: CursorType = {
code: CURSOR_CODE.TIMESTAMP,
args: {timestamp: timestamp},
};
const pageData = await logFileManagerProxy.loadPage(cursor, isPrettifiedRef.current);
updatePageData(pageData);
})().catch((e: unknown) => {
console.error(e);
postPopUp({
level: LOG_LEVEL.ERROR,
message: String(e),
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Action failed",
});
});
updateWindowUrlHashParams({timestamp: null});
}, [
logFileManagerProxy,
postPopUp,
updatePageData,
timestamp,
]);
useEffect(() => {
if (null === timestamp) {
return;
}
(async () => {
const cursor: CursorType = {
code: CURSOR_CODE.TIMESTAMP,
args: {timestamp: timestamp},
};
const pageData = await logFileManagerProxy.loadPage(cursor, isPrettifiedRef.current);
updatePageData(pageData);
})().catch((e: unknown) => {
console.error(e);
postPopUp({
level: LOG_LEVEL.ERROR,
message: String(e),
timeoutMillis: DO_NOT_TIMEOUT_VALUE,
title: "Action failed",
});
});
updateWindowUrlHashParams({timestamp: null});
}, [
logFileManagerProxy,
postPopUp,
updatePageData,
timestamp,
]);
// Synchronize `timestampRef` with `timestamp`.
useEffect(() => {
timestampRef.current = timestamp;
}, [timestamp]);
🤖 Prompt for AI Agents
In src/components/AppController.tsx around lines 124 to 152, the useEffect
handles timestamp changes but does not update timestampRef to reflect the latest
timestamp value. To fix this, add a separate useEffect that listens to changes
in timestamp and updates timestampRef.current accordingly, similar to how
logEventNumRef is synchronized. This ensures timestampRef always holds the
current timestamp value.


// On `logEventNum` update, clamp it then switch page if necessary or simply update the URL.
useEffect(() => {
if (0 === numEvents || URL_HASH_PARAMS_DEFAULT.logEventNum === logEventNum) {
Expand Down Expand Up @@ -174,6 +207,12 @@ const AppController = ({children}: AppControllerProps) => {
args: {eventNum: logEventNumRef.current},
};
}
if (URL_HASH_PARAMS_DEFAULT.timestamp !== timestampRef.current) {
cursor = {
code: CURSOR_CODE.TIMESTAMP,
args: {timestamp: timestampRef.current},
};
}
loadFile(filePath, cursor);
}, [
filePath,
Expand Down
Empty file.
20 changes: 14 additions & 6 deletions src/contexts/UrlContextProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ const URL_SEARCH_PARAMS_DEFAULT = Object.freeze({
const URL_HASH_PARAMS_DEFAULT = Object.freeze({
[HASH_PARAM_NAMES.IS_PRETTIFIED]: false,
[HASH_PARAM_NAMES.LOG_EVENT_NUM]: null,
[HASH_PARAM_NAMES.TIMESTAMP]: null,
});

/**
Expand Down Expand Up @@ -210,12 +211,19 @@ const getWindowUrlHashParams = () => {
structuredClone(URL_HASH_PARAMS_DEFAULT);
const hashParams = new URLSearchParams(window.location.hash.substring(1));

const logEventNum = hashParams.get(HASH_PARAM_NAMES.LOG_EVENT_NUM);
if (null !== logEventNum) {
const parsed = Number(logEventNum);
urlHashParams[HASH_PARAM_NAMES.LOG_EVENT_NUM] = Number.isNaN(parsed) ?
null :
parsed;
const numberHashParamNames = [
HASH_PARAM_NAMES.LOG_EVENT_NUM,
HASH_PARAM_NAMES.TIMESTAMP,
];

for (const paramName of numberHashParamNames) {
const hashParam = hashParams.get(paramName);
if (null !== hashParam) {
const parsed = Number(hashParam);
urlHashParams[paramName] = Number.isNaN(parsed) ?
null :
parsed;
}
}

const isPrettified = hashParams.get(HASH_PARAM_NAMES.IS_PRETTIFIED);
Expand Down
44 changes: 25 additions & 19 deletions src/services/LogFileManager/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -491,26 +491,32 @@ class LogFileManager {
*/
#getCursorData (cursor: CursorType, numActiveEvents: number): CursorData {
const {code, args} = cursor;
switch (code) {
case CURSOR_CODE.PAGE_NUM:
return getPageNumCursorData(
args.pageNum,
args.eventPositionOnPage,
numActiveEvents,
this.#pageSize,
);
case CURSOR_CODE.LAST_EVENT:
return getLastEventCursorData(numActiveEvents, this.#pageSize);
case CURSOR_CODE.EVENT_NUM:
return getEventNumCursorData(
args.eventNum,
numActiveEvents,
this.#pageSize,
this.#decoder.getFilteredLogEventMap(),
);
default:
throw new Error(`Unsupported cursor type: ${code}`);

let eventNum: number = 0;
if (CURSOR_CODE.PAGE_NUM === code) {
return getPageNumCursorData(
args.pageNum,
args.eventPositionOnPage,
numActiveEvents,
this.#pageSize,
);
} else if (CURSOR_CODE.LAST_EVENT === code) {
return getLastEventCursorData(numActiveEvents, this.#pageSize);
} else if (CURSOR_CODE.EVENT_NUM === code) {
({eventNum} = args);
} else {
const eventIdx = this.#decoder.findNearestLogEventByTimestamp(args.timestamp);
if (null !== eventIdx) {
eventNum = eventIdx + 1;
}
}
Comment on lines +496 to 512
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Unhandled cursor codes & zero-event fallback can break pagination

  1. The else branch executes whenever codePAGE_NUM | LAST_EVENT | EVENT_NUM, yet you unconditionally read args.timestamp.
    • If an entirely different cursor code is introduced later, this will crash with args.timestamp is undefined.
    • Make the branch explicit (CURSOR_CODE.TIMESTAMP) and throw for truly unknown codes.

  2. When no event is found for the timestamp, eventNum stays 0.
    getEventNumCursorData expects event numbers ≥ 1; passing 0 will yield incorrect page offsets or throw.

Suggested robust handling:

-        } else {
-            const eventIdx = this.#decoder.findNearestLogEventByTimestamp(args.timestamp);
-            if (null !== eventIdx) {
-                eventNum = eventIdx + 1;
-            }
+        } else if (CURSOR_CODE.TIMESTAMP === code) {
+            const eventIdx = this.#decoder.findNearestLogEventByTimestamp(args.timestamp);
+            if (null === eventIdx) {
+                // Fallback: first event
+                return getPageNumCursorData(1, 0, numActiveEvents, this.#pageSize);
+            }
+            eventNum = eventIdx + 1;
+        } else {
+            throw new Error(`Unsupported cursor code: ${code as string}`);
         }

This removes undefined behaviour, restores the original “fail-fast” philosophy, and clarifies intent.

🤖 Prompt for AI Agents
In src/services/LogFileManager/index.ts around lines 496 to 512, the else branch
currently assumes any unknown cursor code means a timestamp lookup, which can
cause crashes if args.timestamp is undefined for new cursor codes. Refactor this
by explicitly checking if code equals CURSOR_CODE.TIMESTAMP before accessing
args.timestamp, and throw an error for any truly unknown cursor codes to fail
fast. Additionally, handle the case where no event is found for the timestamp by
throwing or returning early instead of allowing eventNum to remain 0, since
getEventNumCursorData requires eventNum ≥ 1 to avoid incorrect pagination.


return getEventNumCursorData(
eventNum,
numActiveEvents,
this.#pageSize,
this.#decoder.getFilteredLogEventMap(),
);
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/services/decoders/ClpIrDecoder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,10 @@ class ClpIrDecoder implements Decoder {
return this.#streamReader.getFilteredLogEventMap();
}

findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
}
Comment on lines +109 to +111
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Ensure type-safety & handle out-of-range values in findNearestLogEventByTimestamp

  1. The public API now only accepts a number, but you immediately cast it to BigInt.
    a. Callers could mistakenly pass a number that is not an integer or exceeds Number.MAX_SAFE_INTEGER, producing an inaccurate BigInt or runtime throw.
    b. Upstream (Decoder interface) may already expose the parameter as bigint; keeping the converter here silently widens the contract.

  2. No validation is performed for negative or NaN timestamps—BigInt(NaN) will throw at runtime.

A small defensive wrapper prevents both issues:

findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
-    return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
+    if (!Number.isFinite(timestamp) || timestamp < 0 || !Number.isInteger(timestamp)) {
+        return null;
+    }
+    return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
}

Optionally, change the signature to bigint to avoid repeated casting at every call-site.


🏁 Script executed:

#!/bin/bash
set -e

echo "=== All occurrences of findNearestLogEventByTimestamp in src ==="
rg "findNearestLogEventByTimestamp" -n src

echo -e "\n=== Context around #streamReader in ClpIrDecoder ==="
rg -C3 -n "#streamReader" src/services/decoders/ClpIrDecoder/index.ts

Length of output: 2862


🏁 Script executed:

#!/bin/bash
set -e

echo "=== Context around findNearestLogEventByTimestamp in JsonlDecoder ==="
rg -C3 -n "findNearestLogEventByTimestamp" src/services/decoders/JsonlDecoder/index.ts

Length of output: 472


Validate timestamp before casting to BigInt in ClpIrDecoder.findNearestLogEventByTimestamp

To prevent runtime errors and inaccurate conversions, ensure the timestamp is a non-negative, finite integer within JavaScript’s safe range before calling the FFI:

• File: src/services/decoders/ClpIrDecoder/index.ts
• Lines: 109–111

Proposed change:

 findNearestLogEventByTimestamp(timestamp: number): Nullable<number> {
-    return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
+    // Reject NaN, non-integers, negatives or values beyond Number.MAX_SAFE_INTEGER
+    if (
+        !Number.isFinite(timestamp) ||
+        !Number.isInteger(timestamp) ||
+        timestamp < 0 ||
+        timestamp > Number.MAX_SAFE_INTEGER
+    ) {
+        return null;
+    }
+    return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
 }

• This guards against BigInt(NaN)/BigInt(1.5)/overflow errors.
• The Decoder interface currently uses number, so we retain that signature here.
• Optionally, once all implementations can support it, you may revisit the interface to accept bigint directly.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
}
findNearestLogEventByTimestamp(timestamp: number): Nullable<number> {
// Reject NaN, non-integers, negatives or values beyond Number.MAX_SAFE_INTEGER
if (
!Number.isFinite(timestamp) ||
!Number.isInteger(timestamp) ||
timestamp < 0 ||
timestamp > Number.MAX_SAFE_INTEGER
) {
return null;
}
return this.#streamReader.findNearestLogEventByTimestamp(BigInt(timestamp));
}
🤖 Prompt for AI Agents
In src/services/decoders/ClpIrDecoder/index.ts at lines 109 to 111, the method
findNearestLogEventByTimestamp currently casts the input number to BigInt
without validation, which can cause runtime errors or inaccurate conversions for
non-integer, negative, NaN, or out-of-range values. Fix this by adding
validation to ensure the timestamp is a non-negative, finite integer within the
safe integer range before casting to BigInt. If the validation fails, handle the
error appropriately or return null. Retain the method signature using number as
per the Decoder interface.


setLogLevelFilter (logLevelFilter: LogLevelFilter): boolean {
this.#streamReader.filterLogEvents(logLevelFilter);

Expand Down
26 changes: 26 additions & 0 deletions src/services/decoders/JsonlDecoder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,32 @@ class JsonlDecoder implements Decoder {
return results;
}

findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
let low = 0;
let high = this.#logEvents.length - 1;
if (high < low) {
return null;
}

while (low <= high) {
const mid = Math.floor((low + high) / 2);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const midTimestamp = this.#logEvents[mid]!.timestamp.valueOf();
if (midTimestamp <= timestamp) {
Comment on lines +135 to +137
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Address the non-null assertion warning.

The non-null assertion is flagged by the static analysis tool. While the current implementation includes a comment to suppress the warning, it would be better to refactor to avoid the non-null assertion entirely.

 const mid = Math.floor((low + high) / 2);
-// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-const midTimestamp = this.#logEvents[mid]!.timestamp.valueOf();
+// We've already checked bounds, so this access is safe
+const midLogEvent = this.#logEvents[mid];
+const midTimestamp = midLogEvent.timestamp.valueOf();

This approach is cleaner than using a non-null assertion and makes the code's safety more explicit.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const midTimestamp = this.#logEvents[mid]!.timestamp.valueOf();
if (midTimestamp <= timestamp) {
const mid = Math.floor((low + high) / 2);
// We've already checked bounds, so this access is safe
const midLogEvent = this.#logEvents[mid];
const midTimestamp = midLogEvent.timestamp.valueOf();
if (midTimestamp <= timestamp) {
// …
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 136-136: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)

🤖 Prompt for AI Agents
In src/services/decoders/JsonlDecoder/index.ts around lines 135 to 137, avoid
using the non-null assertion operator on this.#logEvents[mid]. Instead, add an
explicit check to ensure this.#logEvents[mid] is not null or undefined before
accessing its timestamp property. This makes the code safer and removes the need
for the eslint-disable comment.

low = mid + 1;
} else {
high = mid - 1;
}
}

// corner case: all log events have timestamps >= timestamp
if (0 > high) {
return 0;
}

return high;
}
Comment on lines +126 to +150
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Binary search implementation looks correct, but could be optimized.

The method correctly implements a binary search to find the nearest log event by timestamp, handling important edge cases like empty logs and when all timestamps are greater than the target.

Could be slightly optimized by reducing duplicate bounds checks:

 findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
     let low = 0;
     let high = this.#logEvents.length - 1;
     if (high < low) {
         return null;
     }

     while (low <= high) {
         const mid = Math.floor((low + high) / 2);
-        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        const midTimestamp = this.#logEvents[mid]!.timestamp.valueOf();
+        // We've checked bounds so this array access is safe
+        const midLogEvent = this.#logEvents[mid];
+        const midTimestamp = midLogEvent.timestamp.valueOf();
         if (midTimestamp <= timestamp) {
             low = mid + 1;
         } else {
             high = mid - 1;
         }
     }

     // corner case: all log events have timestamps >= timestamp
     if (0 > high) {
         return 0;
     }

     return high;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
let low = 0;
let high = this.#logEvents.length - 1;
if (high < low) {
return null;
}
while (low <= high) {
const mid = Math.floor((low + high) / 2);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const midTimestamp = this.#logEvents[mid]!.timestamp.valueOf();
if (midTimestamp <= timestamp) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// corner case: all log events have timestamps >= timestamp
if (0 > high) {
return 0;
}
return high;
}
findNearestLogEventByTimestamp (timestamp: number): Nullable<number> {
let low = 0;
let high = this.#logEvents.length - 1;
if (high < low) {
return null;
}
while (low <= high) {
const mid = Math.floor((low + high) / 2);
// We've checked bounds so this array access is safe
const midLogEvent = this.#logEvents[mid];
const midTimestamp = midLogEvent.timestamp.valueOf();
if (midTimestamp <= timestamp) {
low = mid + 1;
} else {
high = mid - 1;
}
}
// corner case: all log events have timestamps >= timestamp
if (0 > high) {
return 0;
}
return high;
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 136-136: Forbidden non-null assertion.

Unsafe fix: Replace with optional chain operator ?. This operator includes runtime checks, so it is safer than the compile-only non-null assertion operator

(lint/style/noNonNullAssertion)

🤖 Prompt for AI Agents
In src/services/decoders/JsonlDecoder/index.ts around lines 126 to 150, optimize
the binary search by reducing duplicate boundary checks inside the loop.
Refactor the while loop conditions and updates to minimize redundant comparisons
of low and high bounds, ensuring the logic still correctly finds the nearest log
event by timestamp while improving efficiency.


/**
* Parses each line from the data array and buffers it internally.
*
Expand Down
19 changes: 19 additions & 0 deletions src/typings/decoders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,25 @@ interface Decoder {
endIdx: number,
useFilter: boolean
): Nullable<DecodeResult[]>;

/**
* Finds the log event, L, where if we assume:
*
* - the collection of log events is sorted in chronological order;
* - and we insert a marker log event, M, with timestamp `timestamp` into the collection (if log
* events with timestamp `timestamp` already exist in the collection, M should be inserted
* after them).
*
* L is the event just before M, if M is not the first event in the collection; otherwise L is
* the event just after M.
*
* NOTE: If the collection of log events isn't in chronological order, this method has undefined
* behaviour.
*
* @param timestamp
* @return The index of the log event L.
*/
findNearestLogEventByTimestamp(timestamp: number): Nullable<number>;
}

export type {
Expand Down
2 changes: 2 additions & 0 deletions src/typings/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ enum SEARCH_PARAM_NAMES {
enum HASH_PARAM_NAMES {
LOG_EVENT_NUM = "logEventNum",
IS_PRETTIFIED = "isPrettified",
TIMESTAMP = "timestamp",
}

interface UrlSearchParams {
Expand All @@ -17,6 +18,7 @@ interface UrlSearchParams {
interface UrlHashParams {
[HASH_PARAM_NAMES.IS_PRETTIFIED]: boolean;
[HASH_PARAM_NAMES.LOG_EVENT_NUM]: number;
[HASH_PARAM_NAMES.TIMESTAMP]: number;
}
Comment on lines 18 to 22
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

timestamp should be optional in UrlHashParams

UrlHashParams now requires TIMESTAMP, making every consumer supply a value even when no timestamp cursor is used. This breaks existing code that only cares about logEventNum or isPrettified.

Mark it optional (or Nullable) just like the update helpers already expect:

-interface UrlHashParams {
-    [HASH_PARAM_NAMES.IS_PRETTIFIED]: boolean;
-    [HASH_PARAM_NAMES.LOG_EVENT_NUM]: number;
-    [HASH_PARAM_NAMES.TIMESTAMP]: number;
-}
+interface UrlHashParams {
+    [HASH_PARAM_NAMES.IS_PRETTIFIED]: boolean;
+    [HASH_PARAM_NAMES.LOG_EVENT_NUM]: number;
+    [HASH_PARAM_NAMES.TIMESTAMP]?: number; // optional
+}

This keeps type-checks happy and matches real-world URL usage.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
interface UrlHashParams {
[HASH_PARAM_NAMES.IS_PRETTIFIED]: boolean;
[HASH_PARAM_NAMES.LOG_EVENT_NUM]: number;
[HASH_PARAM_NAMES.TIMESTAMP]: number;
}
interface UrlHashParams {
[HASH_PARAM_NAMES.IS_PRETTIFIED]: boolean;
[HASH_PARAM_NAMES.LOG_EVENT_NUM]: number;
[HASH_PARAM_NAMES.TIMESTAMP]?: number; // optional
}
🤖 Prompt for AI Agents
In src/typings/url.ts around lines 18 to 22, the TIMESTAMP property in the
UrlHashParams interface is currently required, which forces all consumers to
provide a timestamp even when it's not used. To fix this, mark the TIMESTAMP
property as optional by adding a question mark after the key, making it
consistent with how update helpers expect it and allowing consumers to omit it
when unnecessary.


type UrlSearchParamUpdatesType = {
Expand Down