oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
74.26k stars 2.77k forks source link

Segfault using Discord.JS and ts3-nodejs-library #10720

Open gardc opened 6 months ago

gardc commented 6 months ago

How can we reproduce the crash?

import { TeamSpeak, QueryProtocol } from "ts3-nodejs-library";
import { Client, TextChannel } from "discord.js";

const TS_SERVER = {
  host: "10.0.0.33",
  queryport: 10011, // Default TeamSpeak query port
  username: "username",
  password: "password",
  nickname: "something",
};

const DISCORD_TOKEN =
  "some token";
const CHANNEL_ID = "some channel id";

// Initialize the TeamSpeak client
const tsClient = new TeamSpeak({
  protocol: QueryProtocol.RAW, // This could be RAW or SSH depending on your setup
  host: TS_SERVER.host,
  queryport: TS_SERVER.queryport,
  username: TS_SERVER.username,
  password: TS_SERVER.password,
  nickname: TS_SERVER.nickname,
  serverport: 9987, // Default TeamSpeak server port
});

// Initialize the Discord client
const discordClient = new Client({ intents: ["Guilds", "GuildMessages"] });

discordClient.on("ready", () => {
  if (discordClient.user) {
    console.log(`Logged in as ${discordClient.user.tag}!`);
    setInterval(() => updateChannelNamePeriodically(), 5000); // Update every 5 seconds
  } else throw new Error("Failed to login to Discord");
});

// Function to update Discord channel name
async function updateChannelNamePeriodically() {
  const userCount = await getActiveUsersFromTeamSpeak();

  // Fetch the channel and assert the type after checking if it's text-based
  const channel = await discordClient.channels.fetch(CHANNEL_ID);
  if (channel != null && channel.isTextBased() && "setName" in channel) {
    // Checking if setName method exists
    let newName = "";
    userCount === 0
      ? (newName = "nobody-on-ts")
      : (newName = `${userCount}-on-ts`);
    // We assert channel as TextChannel since isTextBased() confirms it and we have checked for setName
    if ((channel as TextChannel).name !== newName) {
      try {
        await (channel as TextChannel).setName(newName);
        console.log(`Updated channel name to "${newName}"`);
      } catch (error) {
        console.error("Failed to update channel name:", error);
      }
    }
  }
}

// Function to fetch the number of active users on TeamSpeak
async function getActiveUsersFromTeamSpeak() {
  try {
    const server = await tsClient.serverInfo();
    return (
      server.virtualserverClientsonline - server.virtualserverQueryclientsonline
    ); // Subtract query clients
  } catch (error) {
    console.error("Failed to retrieve TeamSpeak user count:", error);
    return 0; // Return 0 if the query fails
  }
}

// Logging in the Discord bot
discordClient.login(DISCORD_TOKEN);

Relevant log output

============================================================
Bun v1.1.6 (e58d67b4) Windows x64
Args: "C:\Users\gaming\.bun\bin\bun.exe", "run", ".\index.ts"
Features: Bun.stdin(2) fetch transpiler_cache(9) tsconfig(6) WebSocket
Builtins: "bun:main" "node:assert" "node:buffer" "node:child_process" "node:crypto" "node:dns" "node:events" "node:fs" "node:fs/promises" "node:http" "node:https" "node:net" "node:path" "node:stream" "node:string_decoder" "node:timers" "node:timers/promises" "node:tls" "node:url" "node:util" "node:util/types" "node:zlib" "node:worker_threads" "undici" "ws"
Elapsed: 747ms | User: 109ms | Sys: 46ms
RSS: 0.24GB | Peak: 0.24GB | Commit: 4.60GB | Faults: 61655

panic(main thread): Segmentation fault at address 0xFFFFFFFFFFFFFFFF
oh no: Bun has crashed. This indicates a bug in Bun, not your code.

panic: Segmentation fault at address 0x7FF9F807550C
panicked during a panic. Aborting.

Stack Trace (bun.report)

Bun v1.1.6 (e58d67b) on windows x86_64 [RunCommand]

Segmentation fault at address 0xFFFFFFFFFFFFFFFF

dylan-conway commented 6 months ago

Here's a debug stack trace. It appears to be a crash on exit:

133 |    * @private
134 |    */
135 |   async connect() {
136 |     const invalidToken = new DiscordjsError(ErrorCodes.TokenInvalid);
137 |     const { shards, shardCount, intents, ws } = this.client.options;
138 |     if (this._ws && this._ws.options.token !== this.client.token) {
                          ^
error: An invalid token was provided.
 code: "TokenInvalid"

      at C:\bun\node_modules\discord.js\src\client\websocket\WebSocketManager.js:138:21
      at connect (C:\bun\node_modules\discord.js\src\client\websocket\WebSocketManager.js:243:6)
      at C:\bun\node_modules\discord.js\src\client\Client.js:524:7
      at login (C:\bun\node_modules\discord.js\src\client\Client.js:502:23)
      at module code (C:\bun\index.js:53:2)
      at moduleEvaluation (native:1:1)
      at moduleEvaluation (native:1:1)
      at native:1:1
============================================================
Bun v1.1.7 (459928c9) Windows x64
Args: "C:\bun\build\bun-debug.exe", "index.js"
Features: Bun.stdin(2) bunfig fetch transpiler_cache(9) tsconfig(8) 
Builtins: "bun:main" "node:assert" "node:buffer" "node:child_process" "node:crypto" "node:dns" "node:events" "node:fs" "node:fs/promises" "node:http" "node:https" "node:net" "node:path" "node:stream" "node:string_decoder" "node:timers" "node:timers/promises" "node:tls" "node:url" "node:util" "node:util/types" "node:zlib" "node:worker_threads" "undici" "ws" 
Elapsed: 22630ms | User: 93ms | Sys: 62ms
RSS: 0.26GB | Peak: 0.26GB | Commit: 4.60GB | Faults: 93690

panic(main thread): Segmentation fault at address 0x7FFEB3E754CC
???:?:?: 0x7ffeb3e754cb in ??? (???)
???:?:?: 0x7ffef5f6129b in ??? (ntdll.dll)
???:?:?: 0x7ffef5f60ff6 in ??? (ntdll.dll)
???:?:?: 0x7ffef5f60c9c in ??? (ntdll.dll)
???:?:?: 0x7ffef4e27faa in ??? (KERNEL32.DLL)
???:?:?: 0x7ffef324bed7 in ??? (ucrtbase.dll)
???:?:?: 0x7ffef324c098 in ??? (ucrtbase.dll)
C:\bun\src\Global.zig:105:21: 0x7ff693158611 in exitWide (bun-zig.o)
    bun.C.quick_exit(@bitCast(code));
                    ^
C:\bun\src\Global.zig:98:13: 0x7ff692d03a14 in exit (bun-zig.o)
    exitWide(@as(u32, code));
            ^
C:\bun\src\bun_js.zig:412:20: 0x7ff69379205c in start (bun-zig.o)
        Global.exit(exit_code);
                   ^
gardc commented 6 months ago

Here's a debug stack trace. It appears to be a crash on exit:

Yes you're right, it segfaulted on exit (crash). After fixing all issues with the script on node and running it again with Bun, it doesn't segfault. Complete script can be found here.

However, it should probably not segfault on errors though :)

Edit: it might have been ts3-nodejs-library causing the segfault issues. At least it was preventing the docker build from completing.

gardc commented 6 months ago

I'm closing because the error happened using ts3-nodejs-library, but switching to node-ts made the script run without errors.