-
Notifications
You must be signed in to change notification settings - Fork 894
fix: fix duplicated agent logs #17806
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
Merged
Merged
Changes from 2 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
3f9a1bd
fix: duplicated agent logs
BrunoQuaresma cd050cc
Fix fmt
BrunoQuaresma ffe3d84
Rollback containers intervals
BrunoQuaresma 7238734
Simplify logic
BrunoQuaresma 4e4c405
Merge branch 'main' of https://github.com/coder/coder into bq/fix-dup…
BrunoQuaresma 5160e28
Fix tests
BrunoQuaresma 6d33649
FMT
BrunoQuaresma 38a8d62
Apply review comments
BrunoQuaresma a7e13a0
Mock websocket on storybook to support OneWayWebsocket
BrunoQuaresma c98a8dd
FMT
BrunoQuaresma f385ce9
Fix test
BrunoQuaresma File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,95 +1,73 @@ | ||
import { watchWorkspaceAgentLogs } from "api/api"; | ||
import { agentLogs } from "api/queries/workspaces"; | ||
import type { | ||
WorkspaceAgent, | ||
WorkspaceAgentLifecycle, | ||
WorkspaceAgentLog, | ||
} from "api/typesGenerated"; | ||
import { displayError } from "components/GlobalSnackbar/utils"; | ||
import { useEffectEvent } from "hooks/hookPolyfills"; | ||
import { useEffect, useRef } from "react"; | ||
import { useEffect } from "react"; | ||
import { useQuery, useQueryClient } from "react-query"; | ||
|
||
export type UseAgentLogsOptions = Readonly<{ | ||
workspaceId: string; | ||
agentId: string; | ||
agentLifeCycleState: WorkspaceAgentLifecycle; | ||
enabled?: boolean; | ||
}>; | ||
const ON_GOING_STATES: WorkspaceAgentLifecycle[] = ["starting", "created"]; | ||
|
||
/** | ||
* Defines a custom hook that gives you all workspace agent logs for a given | ||
* workspace.Depending on the status of the workspace, all logs may or may not | ||
* be available. | ||
*/ | ||
export function useAgentLogs( | ||
options: UseAgentLogsOptions, | ||
agent: WorkspaceAgent, | ||
): readonly WorkspaceAgentLog[] | undefined { | ||
const { workspaceId, agentId, agentLifeCycleState, enabled = true } = options; | ||
const queryClient = useQueryClient(); | ||
const queryOptions = agentLogs(workspaceId, agentId); | ||
const { data: logs, isFetched } = useQuery({ ...queryOptions, enabled }); | ||
|
||
// Track the ID of the last log received when the initial logs response comes | ||
// back. If the logs are not complete, the ID will mark the start point of the | ||
// Web sockets response so that the remaining logs can be received over time | ||
const lastQueriedLogId = useRef(0); | ||
useEffect(() => { | ||
const isAlreadyTracking = lastQueriedLogId.current !== 0; | ||
if (isAlreadyTracking) { | ||
return; | ||
} | ||
const agentLogsOptions = agentLogs(agent.id); | ||
const shouldUseSocket = ON_GOING_STATES.includes(agent.lifecycle_state); | ||
const { data: logs } = useQuery({ | ||
...agentLogsOptions, | ||
enabled: !shouldUseSocket, | ||
}); | ||
|
||
const lastLog = logs?.at(-1); | ||
if (lastLog !== undefined) { | ||
lastQueriedLogId.current = lastLog.id; | ||
} | ||
}, [logs]); | ||
const appendAgentLogs = useEffectEvent( | ||
async (newLogs: WorkspaceAgentLog[]) => { | ||
await queryClient.cancelQueries(agentLogsOptions.queryKey); | ||
queryClient.setQueryData<WorkspaceAgentLog[]>( | ||
agentLogsOptions.queryKey, | ||
(oldLogs) => (oldLogs ? [...oldLogs, ...newLogs] : newLogs), | ||
); | ||
}, | ||
); | ||
|
||
const addLogs = useEffectEvent((newLogs: WorkspaceAgentLog[]) => { | ||
queryClient.setQueryData( | ||
queryOptions.queryKey, | ||
(oldData: WorkspaceAgentLog[] = []) => [...oldData, ...newLogs], | ||
); | ||
const refreshAgentLogs = useEffectEvent(() => { | ||
queryClient.invalidateQueries(agentLogsOptions.queryKey); | ||
}); | ||
|
||
useEffect(() => { | ||
// Stream data only for new logs. Old logs should be loaded beforehand | ||
// using a regular fetch to avoid overloading the websocket with all | ||
// logs at once. | ||
if (!isFetched) { | ||
if (!shouldUseSocket) { | ||
return; | ||
} | ||
|
||
// If the agent is off, we don't need to stream logs. This is the only state | ||
// where the Coder API can't receive logs for the agent from third-party | ||
// apps like envbuilder. | ||
if (agentLifeCycleState === "off") { | ||
return; | ||
} | ||
const socket = watchWorkspaceAgentLogs(agent.id, { after: 0 }); | ||
socket.addEventListener("message", (e) => { | ||
if (e.parseError) { | ||
console.warn("Error parsing agent log: ", e.parseError); | ||
return; | ||
} | ||
appendAgentLogs(e.parsedMessage); | ||
}); | ||
|
||
const socket = watchWorkspaceAgentLogs(agentId, { | ||
after: lastQueriedLogId.current, | ||
onMessage: (newLogs) => { | ||
// Prevent new logs getting added when a connection is not open | ||
if (socket.readyState !== WebSocket.OPEN) { | ||
return; | ||
} | ||
addLogs(newLogs); | ||
}, | ||
onError: (error) => { | ||
// For some reason Firefox and Safari throw an error when a websocket | ||
// connection is close in the middle of a message and because of that we | ||
// can't safely show to the users an error message since most of the | ||
// time they are just internal stuff. This does not happen to Chrome at | ||
// all and I tried to find better way to "soft close" a WS connection on | ||
// those browsers without success. | ||
console.error(error); | ||
}, | ||
socket.addEventListener("error", (e) => { | ||
console.error("Error in agent log socket: ", e); | ||
displayError( | ||
"Unable to watch the agent logs", | ||
"Please try refreshing the browser", | ||
); | ||
socket.close(); | ||
}); | ||
|
||
return () => { | ||
socket.close(); | ||
// For some reason, after closing the socket, a few logs still getting | ||
// generated in the BE. This is a workaround to avoid we don't display | ||
// them in the UI. | ||
refreshAgentLogs(); | ||
}; | ||
}, [addLogs, agentId, agentLifeCycleState, isFetched]); | ||
}, [agent.id, shouldUseSocket, appendAgentLogs, refreshAgentLogs]); | ||
|
||
return logs; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we make this
params?.after.toString() ?? ""
?