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

feat: native support for Websockets #12973

Open
wants to merge 204 commits into
base: main
Choose a base branch
from
Open

Conversation

LukeHagar
Copy link
Contributor

@LukeHagar LukeHagar commented Nov 8, 2024

This PR is a replacement to #12961 with a completely different Websocket implementation using crossws that should be fully compatible with all major runtimes.

Functionality has been validated locally using basic tests in the options-2 test app.

Here is the new usage experience.
+server.js

import { error, accept } from '@sveltejs/kit';

export const socket = {
	upgrade(req) {
		 // Accept the websocket connection with a return
		return accept();

                // Reject the websocket connection with an error
                error(401, 'unauthorized');
	},

	open(peer) {
		//... handle socket open
	},

	message(peer, message) {
		//... handle socket message
	},

	close(peer, event) {
		//... handle socket close
	},

	error(peer, error) {
		//... handle socket error
	}
};

The newest implementation allows different sets of handlers to be implemented on a per-route basis. I have tested some basic uses of websockets locally to much success.

This PR is intended to:
Resolve #12358
Resolve #1491

Steps left

  • Ensure handle runs before upgrading requests
  • Gather feedback
  • Add or update tests
  • Fix the types
  • Update the adapters
  • Update the documentation
  • Add a changeset
  • Update language tools +server exports validation
  • Automatic typing for sockets

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.

Tests

  • Run the tests with pnpm test and lint the project with pnpm lint and pnpm check

Changesets

  • If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpm changeset and following the prompts. Changesets that add features should be minor and those that fix bugs should be patch. Please prefix changeset messages with feat:, fix:, or chore:.

Edits

  • Please ensure that 'Allow edits from maintainers' is checked. PRs without this option may be closed.

…ionality for different handlers at different URLs, added example use cases to options-2 test app, added upgrade function for supporting additional adapters, and much more.
Copy link

changeset-bot bot commented Nov 8, 2024

🦋 Changeset detected

Latest commit: 6ca1034

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@sveltejs/adapter-cloudflare-workers Minor
@sveltejs/adapter-cloudflare Minor
@sveltejs/adapter-node Minor
@sveltejs/kit Minor
@sveltejs/adapter-auto Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@LukeHagar LukeHagar mentioned this pull request Nov 8, 2024
6 tasks
@Rich-Harris
Copy link
Member

preview: https://svelte-dev-git-preview-kit-12973-svelte.vercel.app/

this is an automated message

@eltigerchino eltigerchino changed the title Native support for Websockets feat: native support for Websockets Nov 11, 2024
@eltigerchino eltigerchino added the feature / enhancement New feature or request label Nov 11, 2024
@eltigerchino eltigerchino marked this pull request as draft November 11, 2024 03:18
@pi0
Copy link

pi0 commented Jan 22, 2025

@LukeHagar LMK, if you need any help with this (you can reach me also on discord @pi0)

@LukeHagar LukeHagar marked this pull request as ready for review January 23, 2025 14:52
@LukeHagar
Copy link
Contributor Author

Hey @ciscoheat,

I think the accept function was removed in favor of just returning headers, These files should showcase how upgrades and errors should be handled for now

Upgrade:
52677d7#diff-ea6a6a78a1f81838fca612ef67430b4ae2b5f79946c9a9acebc5acc9cca9c19aR3-R7

Error:
52677d7#diff-4f62d3e799ec3b6382c37bef94a125df22cfda05a5ac458133250de86037aab2R5-R7

@alanxp
Copy link

alanxp commented Feb 23, 2025

Testing..

Why if i send the headers 'Sec-WebSocket-Protocol': 'test' exactly as the clients 'test' it disconects the client?
it's the only bug i've got.

every time i test i get error on client,
WebSocket connection to 'ws://localhost:5173/ws' failed:

however, if i do not send the headers, it continues working

@alanxp
Copy link

alanxp commented Feb 24, 2025

really hope they continue with this implementation. I’ve been testing it using ArrayBuffer and haven’t encountered any problems so far. Congrats to the devs—it looks promising! Do not give up!

@eltigerchino
Copy link
Member

eltigerchino commented Feb 24, 2025

Why if i send the headers 'Sec-WebSocket-Protocol': 'test' exactly as the clients 'test' it disconects the client? it's the only bug i've got.

every time i test i get error on client, WebSocket connection to 'ws://localhost:5173/ws' failed:

however, if i do not send the headers, it continues working

Currently, there's an issue with returning the Sec-WebSocket-Protocol header because it is also returned by the crossws node adapter, causing the two to conflict. unjs/crossws#141

@alanxp
Copy link

alanxp commented Feb 24, 2025

I want to handle message() outside of +server.ts using my own messageHandler implementation, but it does not let me import type { peer } from "@sveltejs/kit" outside of +server.ts, this is crucial to handle logic with modules.

also, is there anyway i can declare peer.context to the types i want instead of unknown?

@LukeHagar
Copy link
Contributor Author

@alanxp

it does not let me import type { peer } from "@sveltejs/kit"

Peer is a type exported from crossws, but I don't think its one that's reexported. we can rectify that.

@alanxp
Copy link

alanxp commented Feb 25, 2025

@alanxp

it does not let me import type { peer } from "@sveltejs/kit"

Peer is a type exported from crossws, but I don't think its one that's reexported. we can rectify that.

I can confirm that it was a cache problem, it does work, so dont worry about it. Worked by deleting .sveltekit and restarting vscode + svelte dev server

Now what is really important, and it's not letting me continue my testing is the need to extend my types to peer.context

@luke-hagar-sp
Copy link

Now what is really important, and it's not letting me continue my testing is the need to extend my types to peer.context

You can review the docs here:
https://crossws.unjs.io/guide/peer

Though I don't see anything specific for typing context.

@pi0 Do you want to weigh in here, on how one could properly type peer.context or is this something we should look to solve in SvelteKit land?

@eltigerchino
Copy link
Member

eltigerchino commented Mar 3, 2025

Now what is really important, and it's not letting me continue my testing is the need to extend my types to peer.context

Can you expand on your use case for this? It doesn't seem like peer.context contains any data unless explicitly set by the user. If you're adding your own data to the peer object, you could set it on a new property and modify the type like this:

// src/app.d.ts

// ...

declare module 'crossws' {
	export interface Peer {
		myData?: string; // augment the Peer object type with your own property
	}
}

export {};
// src/routes/server.ts
import type { Socket } from '@sveltejs/kit';

export const socket: Socket = {
  	open(peer) {
  	  peer.myData = 'my value'; // use your custom property
  	}
}

@nerg4l
Copy link

nerg4l commented Mar 3, 2025

I'm missing two functionalities which I think would be a great addition. Please let me know if these are already there and I just missed them.

  1. I did not find a way to access the adapters. With access to the adapter one can call publish outside of the hooks. See adapterUtils.
  2. Expose RequestEvent in the upgrade method. This would be quite useful to keep compatibility with Svelte Kit and not deviate from the functionality of other type of request/response flow. (e.g. access locals)

@eltigerchino
Copy link
Member

I'm missing two functionalities which I think would be a great addition. Please let me know if these are already there and I just missed them.

1. I did not find a way to access the adapters. With access to the adapter one can call `publish` outside of the hooks. See [`adapterUtils`](https://github.com/unjs/crossws/blob/cad4a65b041d8f956067bded303a84f15e5278ef/src/adapter.ts#L4-L21).

2. Expose `RequestEvent` in the upgrade method. This would be quite useful to keep compatibility with Svelte Kit and not deviate from the functionality of other type of request/response flow. (e.g. access `locals`)

Thanks for your feedback! I've implemented these two changes and will test them over the next few days. The getPeers and publish functions can be imported from $app/server.

# sveltekit
npm i https://pkg.pr.new/sveltejs/kit/@sveltejs/kit@5e2bfc8

# node
npm i https://pkg.pr.new/sveltejs/kit/@sveltejs/adapter-node@5e2bfc8

# cloudflare
npm i https://pkg.pr.new/sveltejs/kit/@sveltejs/adapter-cloudflare@5e2bfc8

# cloudflare workers
npm i https://pkg.pr.new/sveltejs/kit/@sveltejs/adapter-cloudflare-workers@5e2bfc8

@nerg4l
Copy link

nerg4l commented Mar 7, 2025

I tried the changes and they are working so far. Now that I have access to RequestEvent in the upgrade method, I can access locals and it is nicely populated in hooks.server.ts. Unfortunately, this change removed the possibility of accessing the crossws context during upgrade, and I'm unable to share data with the hooks. Maybe svelte could populate context with locals? It feels a bit hackish.
In my particular case, crossws Resolver API might be a better option but that probably out of scope for this PR.

Also, I noticed that I cannot simply send a SIGINT (CTRL+C) to shut down the node server while at least one WebSocket connection is alive. Do I have to register sveltekit:shutdown or something similar? It might be better to handle this on the adapter level.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature / enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

implement "Upgrade" as a function in a api route to support websocket Native support for web sockets
10 participants