Skip to content

fix hello race condition #1132

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 1 commit into from
Mar 23, 2024
Merged
Changes from all commits
Commits
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
15 changes: 9 additions & 6 deletions src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,9 @@ export class PreviewServer {
}
};

_handleConnection = async (socket: WebSocket, req: IncomingMessage) => {
_handleConnection = (socket: WebSocket, req: IncomingMessage) => {
if (req.url === "/_observablehq") {
handleWatch(socket, req, await this._readConfig());
handleWatch(socket, req, this._readConfig()); // can’t await; messages would be dropped
} else {
socket.close();
}
Expand Down Expand Up @@ -273,8 +273,8 @@ function getWatchFiles(resolvers: Resolvers): Iterable<string> {
return files;
}

function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
const {root, loaders} = config;
function handleWatch(socket: WebSocket, req: IncomingMessage, configPromise: Promise<Config>) {
let config: Config | null = null;
let path: string | null = null;
let hash: string | null = null;
let html: string[] | null = null;
Expand All @@ -289,7 +289,8 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
console.log(faint("socket open"), req.url);

async function watcher(event: WatchEventType, force = false) {
if (!path) throw new Error("not initialized");
if (!path || !config) throw new Error("not initialized");
const {root, loaders} = config;
switch (event) {
case "rename": {
markdownWatcher?.close();
Expand Down Expand Up @@ -356,6 +357,8 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
if (!(path = normalize(path)).startsWith("/")) throw new Error("Invalid path: " + initialPath);
if (path.endsWith("/")) path += "index";
path = join(dirname(path), basename(path, ".html") + ".md");
config = await configPromise;
const {root, loaders} = config;
const source = await readFile(join(root, path), "utf8");
const page = parseMarkdown(source, {path, ...config});
const resolvers = await getResolvers(page, {root, path, loaders});
Expand Down Expand Up @@ -402,7 +405,7 @@ function handleWatch(socket: WebSocket, req: IncomingMessage, config: Config) {
console.log(faint("socket close"), req.url);
});

function send(message) {
function send(message: any) {
console.log(faint("↓"), message);
socket.send(JSON.stringify(message));
}
Expand Down