Skip to content
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

Include ConsoleStdout for incremental output? #66

Closed
amesgen opened this issue Jan 13, 2024 · 1 comment · Fixed by #67
Closed

Include ConsoleStdout for incremental output? #66

amesgen opened this issue Jan 13, 2024 · 1 comment · Fixed by #67

Comments

@amesgen
Copy link
Contributor

amesgen commented Jan 13, 2024

I find ConsoleStdout from an existing test very useful to incrementally get log output while running WASI programs that use stdout/stderr:

class ConsoleStdout extends Fd {
constructor(write) {
super();
this.write = write;
}
fd_filestat_get() {
const filestat = new wasi.Filestat(
wasi.FILETYPE_CHARACTER_DEVICE,
BigInt(0),
);
return { ret: 0, filestat };
}
fd_fdstat_get() {
const fdstat = new wasi.Fdstat(wasi.FILETYPE_CHARACTER_DEVICE, 0);
fdstat.fs_rights_base = BigInt(wasi.RIGHTS_FD_WRITE);
return { ret: 0, fdstat };
}
fd_write(view8, iovs) {
let nwritten = 0;
for (let iovec of iovs) {
let buffer = view8.slice(iovec.buf, iovec.buf + iovec.buf_len);
this.write(buffer);
nwritten += iovec.buf_len;
}
return { ret: 0, nwritten };
}
}

In particular, in conjunction with an additional static method

  static lineBuffered(write) {
    const dec = new TextDecoder("utf-8", { fatal: false });
    let line_buf = "";
    return new ConsoleStdout((buffer) => {
      line_buf += dec.decode(buffer, { stream: true });
      const lines = line_buf.split("\n");
      for (const [i, line] of lines.entries()) {
        if (i < lines.length - 1) {
          write(line);
        } else {
          line_buf = line;
        }
      }
    });
  }

which can eg be used like this

[
  new OpenFile(new File([])), // stdin
  ConsoleStdout.lineBuffered(msg => console.log(`[WASI stdout] ${msg}`)),
  ConsoleStdout.lineBuffered(msg => console.warn(`[WASI stderr] ${msg}`)),
]

Is it in scope to add this to the library such that it can be reused by other projects? If so, happy to create a PR.

@bjorn3
Copy link
Owner

bjorn3 commented Jan 13, 2024

Yeah, seems useful to have.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants