Skip to content

Commit

Permalink
Merge pull request #27 from BunnyWay/feat-add-no-addr
Browse files Browse the repository at this point in the history
feat: Add no addr option
  • Loading branch information
antho-bunny authored Aug 28, 2024
2 parents 0187d7b + ec2d606 commit 968ccbb
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 12 deletions.
5 changes: 5 additions & 0 deletions .changeset/moody-cooks-retire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@bunny.net/edgescript-sdk": minor
---

Consider the fact we can have a TcpListener with no associated Addr
12 changes: 9 additions & 3 deletions libs/bunny-sdk/src/net/socket_addr.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,27 @@
import { IPv4 } from "./ip.ts";

export type SocketAddr = {
export type SocketAddr = SocketAddrV4 | NoAddr;

export type SocketAddrV4 = {
readonly _tag: "SocketAddrV4",
port: number,
ip: IPv4,
};

export type NoAddr = {
readonly _tag: "NoAddr",
};

/**
* Returns the port number associated with this socket address.
*/
export function port(addr: SocketAddr): number {
export function port(addr: SocketAddrV4): number {
return addr.port;
}

/**
* Returns the IP address associated with this socket address.
*/
export function ip(addr: SocketAddr): IPv4 {
export function ip(addr: SocketAddrV4): IPv4 {
return addr.ip;
}
37 changes: 28 additions & 9 deletions libs/bunny-sdk/src/net/tcp.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { internal_getPlatform } from "../platform.ts";
import * as SocketAddr from "./socket_addr.ts";

export type TcpListener = {
Expand All @@ -24,20 +25,38 @@ export function unstable_local_addr(tcp: TcpListener): SocketAddr.SocketAddr {
* Format the associated [TcpListener] to a String
*/
export function toString(tcp: TcpListener): string {
return `${SocketAddr.ip(tcp.addr).join('.')}:${SocketAddr.port(tcp.addr)}`;
switch (tcp.addr._tag) {
case "SocketAddrV4":
return `${SocketAddr.ip(tcp.addr).join('.')}:${SocketAddr.port(tcp.addr)}`;
case "NoAddr":
return "No addr associated to this listener. You should be running in a controlled environment.";
}
}

/**
* Create a new [TcpListener].
*/
export function unstable_new(): TcpListener {
return ({
_tag: 'TcpListener',
addr: {
_tag: "SocketAddrV4",
port: 8080,
ip: [127, 0, 0, 1],
},
})
const platform = internal_getPlatform();
switch (platform.runtime) {
case "bunny": {
return ({
_tag: "TcpListener",
addr: {
_tag: "NoAddr"
}
});
}
default:
return ({
_tag: 'TcpListener',
addr: {
_tag: "SocketAddrV4",
port: 8080,
ip: [127, 0, 0, 1],
},
});

}
}

0 comments on commit 968ccbb

Please sign in to comment.