Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion .github/scripts/windows_sdk_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def prepare(output):
output.mkdir(parents=True)
libraries = output / 'lib'
libraries.mkdir()
pending = {'libcmt.lib', 'libcpmt.lib', 'libucrt.lib', 'libvcruntime.lib', 'oldnames.lib', 'kernel32.lib'}
pending = {'libcmt.lib', 'libcpmt.lib', 'libucrt.lib', 'libvcruntime.lib', 'oldnames.lib', 'kernel32.lib', 'ws2_32.lib'}
for optional in ('legacy_stdio_definitions.lib', 'synchronization.lib', 'uuid.lib', 'ntdll.lib'):
if optional in candidates: pending.add(optional)
copied = set()
Expand Down
6 changes: 5 additions & 1 deletion .github/workflows/native-cross-os.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,16 @@ jobs:
cmake -S . -B build/macos -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON \
-DKALANDRA_LLVM_ROOT="$KALANDRA_LLVM_ROOT" -DCMAKE_OSX_DEPLOYMENT_TARGET=26.0 \
-DKALANDRA_BUILD_METAL_RUNTIME=OFF -DKALANDRA_BUILD_METAL_PROOF=OFF
cmake --build build/macos --target native-cpu-standalone-package kalandra kalandra-test-observer kalandra-cross-target-tests kalandra-type-capability-tests kalandra-native-subscription-tests -j2
cmake --build build/macos --target native-cpu-standalone-package kalandra kalandra-test-observer kalandra-cross-target-tests kalandra-type-capability-tests kalandra-native-subscription-tests kalandra-tcp-lifecycle-tests -j2
build/macos/native/kalandra-type-capability-tests
ctest --test-dir build/macos --output-on-failure \
-R '^native-(subscription-lifecycle|c-exports|c-portable-buffer-imports|c-header-imports|c-counted-imports|apple-sdk-imports|cross-target-codegen|cross-toolchain-validation|call-foundation-source)$'
- name: Verify native values through an installed package
run: python3 native/tests/NativeValueImportTests.py --compiler build/macos/native/kalandra
- name: Verify cancellation and socket ownership cleanup
run: build/macos/native/kalandra-tcp-lifecycle-tests
- name: Exercise TCP over IPv4 and IPv6 on macOS
run: ctest --test-dir build/macos --output-on-failure -R '^native-tcp-source-(debug|optimized|sanitized)$'
- name: Exercise AppKit windows and native event delivery
run: python3 native/tests/WindowInteropTests.py --compiler build/macos/native/kalandra
- name: Qualify explicit returns and primitive types
Expand Down
6 changes: 4 additions & 2 deletions .github/workflows/native-windows.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ jobs:
if ($LASTEXITCODE -ne 0) { throw 'Filesystem runtime ownership qualification failed' }
- name: Build native CPU toolchain
run: |
cmake --build build/windows --target native-cpu-toolchain kalandra kalandra-task-core-optimized kalandra-type-capability-tests kalandra-native-subscription-tests -j2 -- -k 0
cmake --build build/windows --target native-cpu-toolchain kalandra kalandra-task-core-optimized kalandra-type-capability-tests kalandra-native-subscription-tests kalandra-tcp-lifecycle-tests -j2 -- -k 0
if ($LASTEXITCODE -ne 0) { throw 'Native CPU toolchain build failed' }
& build/windows/native/kalandra-type-capability-tests.exe
if ($LASTEXITCODE -ne 0) { throw 'Type-capability contracts failed' }
Expand Down Expand Up @@ -161,6 +161,8 @@ jobs:
if ($LASTEXITCODE -ne 0) { throw 'Path runtime qualification failed' }
python native/tests/PathOracleTests.py --driver build/windows/path-runtime-tests.exe
if ($LASTEXITCODE -ne 0) { throw 'Path platform oracle failed' }
- name: Verify cancellation and socket ownership cleanup
run: "& build/windows/native/kalandra-tcp-lifecycle-tests.exe"
- name: Qualify application entries, console I/O and formatting
run: |
$env:PYTHONUTF8 = '1'
Expand All @@ -172,7 +174,7 @@ jobs:
$env:PATH = "$($sanitizerRuntime[0].FullName);$env:PATH"
}
foreach ($variant in $variants) {
foreach ($suite in @('StreamSourceTests', 'ProcessSourceTests')) {
foreach ($suite in @('StreamSourceTests', 'ProcessSourceTests', 'TcpSourceTests')) {
python "native/tests/$suite.py" --compiler build/windows/native/kalandra.exe --variant $variant
if ($LASTEXITCODE -ne 0) { throw "$suite $variant failed" }
}
Expand Down
1 change: 1 addition & 0 deletions apps/website/src/content/native/index.tiramisu
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ list {
link { url = "/docs/options", "std/option — present and absent values" },
link { url = "/docs/iteration", "std/iter — reusable integer ranges" },
link { url = "/docs/subprocesses", "std/process — launch programs, pipe bytes and wait for exit" },
link { url = "/docs/networking", "std/net — TCP connections, listeners and split streams" },
link { url = "/docs/streams", "std/stream — copy bytes between readers and writers" },
link { url = "/docs/buffers", "std/buffer — owned growable byte storage" },
link { url = "/docs/parsing", "std/parse — convert text to typed numbers and booleans" },
Expand Down
1 change: 1 addition & 0 deletions apps/website/src/content/native/library.tiramisu
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ list {
link { url = "/docs/options", "std/option — present and absent values" },
link { url = "/docs/filesystem", "std/fs — owned files, byte and line I/O, buffering" },
link { url = "/docs/subprocesses", "std/process — launch programs, pipe bytes and wait for exit" },
link { url = "/docs/networking", "std/net — TCP connections, listeners and split streams" },
link { url = "/docs/streams", "std/stream — copy bytes between readers and writers" },
link { url = "/docs/buffers", "std/buffer — owned growable byte storage" },
link { url = "/docs/parsing", "std/parse — convert text to typed numbers and booleans" },
Expand Down
107 changes: 107 additions & 0 deletions apps/website/src/content/native/networking.tiramisu
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
meta { title = "TCP networking", description = "Connect TCP peers, pass bytes with ByteBuffer, and split a connection between tasks.", order = 10, group = "Library reference" }

Use std/net to listen on a local address or connect to a TCP peer by hostname, IPv4 address, or IPv6 address. A TcpStream implements the ByteReader and ByteWriter traits from std/stream. The same readInto and writeAll calls work with sockets, files and subprocess pipes.

h2 { "Send bytes over loopback" }

This program runs both ends locally. Port zero asks the operating system to assign an available port. The client sends three bytes, then finishes writing. The server can read the bytes, observe EOF, and send its reply on the same connection.

codeblock { language = kalandra, """from "std/net" import listenTcp, localPort, connectTcp, accept, shutdownWrite, NetError
from "std/stream" import readInto, writeAll, StreamError
from "std/buffer" import byteBuffer, append, BufferError
from "std/fmt" import format
from "std/io" import println, IoError

fn main() -> unit ! (NetError | StreamError | BufferError | IoError):
listener = try listenTcp("127.0.0.1", 0)
client = try connectTcp("127.0.0.1", try localPort(listener))
server = try accept(listener)
chunk = try byteBuffer(64)
try append(chunk, [65, 0, 66])
try writeAll(client, chunk)
try shutdownWrite(client)
while try readInto(server, chunk, 64) > 0:
try writeAll(server, chunk)
try shutdownWrite(server)
total: u64 = 0
while true:
n = try readInto(client, chunk, 64)
if n == 0: break
total = total + n
try println(format("{}", total))
return ()
""" }

The program prints 3, including the zero byte. A positive read can deliver any number of bytes up to the requested maximum. A zero result for a positive request means the peer finished sending. Use a length or a delimiter when your protocol needs message boundaries.

h2 { "connectTcp" }

code { "connectTcp(host: String, port: u16) -> TcpStream ! NetError" }

Open a connection. The system resolver supplies IPv4 and IPv6 candidates for a hostname. The runtime tries them in order until one succeeds or the list is exhausted.

h2 { "connectTcpWithin" }

code { "connectTcpWithin(host: String, port: u16, timeout: Duration) -> TcpStream ! NetError" }

Use one time budget for resolution and all connection attempts. A zero duration expires immediately. Construct the duration with std/time.

h2 { "listenTcp" }

code { "listenTcp(host: String, port: u16) -> TcpListener ! NetError" }

Bind a listener to one local address. Use 127.0.0.1 or ::1 for loopback. Port zero asks the operating system to assign an available port.

h2 { "accept" }

code { "accept(listener: TcpListener) -> TcpStream ! NetError" }

Wait for one incoming connection. The listener stays available to accept another peer. Each accepted connection starts with unlimited read and write waits.

h2 { "localPort" }

code { "localPort(listener: TcpListener) -> u16 ! NetError" }

Read the port assigned to the listener. Use this after binding port zero to tell a client where to connect.

h2 { "shutdownWrite" }

code { "shutdownWrite(stream: TcpStream) -> unit ! NetError" }

Finish sending and keep reading. The peer sees EOF after receiving queued bytes. Application-level acknowledgement is needed to know the peer processed them.

h2 { "split" }

code { "split(own stream: TcpStream) -> TcpHalves ! NetError" }

Consume the connection and return an owner of its read and write halves. Each half can move into its own task. Closing the owner drops the halves still in its possession.

h2 { "takeReader" }

code { "takeReader(halves: TcpHalves) -> TcpReader ! NetError" }

Take the read half. A second call reports NetError.HalfUnavailable. The reader implements ByteReader.

h2 { "takeWriter" }

code { "takeWriter(halves: TcpHalves) -> TcpWriter ! NetError" }

Take the write half. A second call reports NetError.HalfUnavailable. The writer implements ByteWriter. Closing it signals EOF to the peer after queued bytes.

h2 { "setTimeout" }

code { "setTimeout[S: TcpTimeout](endpoint: S, timeout: Duration) -> unit ! NetError" }

Set the time budget for each subsequent accept, read or write on this endpoint. A split carries the current budget into both halves. Accept uses NetError.TimedOut. Reads and writes use StreamError.TimedOut. An unsuccessful writeAll may already have sent a prefix.

h2 { "Closure and errors" }

A listener, stream or half closes on scope exit. Use try close(endpoint) to consume it explicitly.

Connection setup reports NetError.Resolution with the resolver code, NetError.System with the OS code and message, or NetError.InvalidArgument for an invalid host. Stream operations have the same StreamError channel as files and pipes. Task cancellation follows the surrounding parallel scope. At most four operating-system lookups run concurrently. A lookup may outlive the task that requested it. The runtime retains at most 64 candidate addresses per operation and discards the result after cancellation. Network functions run on the host, including in applications that also run GPU work.

list {
link { url = "/docs/streams", "Transfer bytes with generic readers and writers" },
link { url = "/docs/buffers", "Reuse a ByteBuffer" },
link { url = "/docs/time", "Construct a timeout duration" }
}
10 changes: 7 additions & 3 deletions apps/website/src/content/native/streams.tiramisu
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
meta { title = "Byte streams", description = "Copy binary data with a reusable ByteBuffer and generic readers and writers.", order = 8, group = "Library reference" }

Use ByteReader and ByteWriter from std/stream when a function needs to move bytes between endpoints. A File implements both traits. A BufferedReader implements ByteReader and a BufferedWriter implements ByteWriter.
Use ByteReader and ByteWriter from std/stream when a function needs to move bytes between endpoints. A File and a TcpStream implement both traits. A split TCP reader or writer implements its corresponding trait. A BufferedReader implements ByteReader and a BufferedWriter implements ByteWriter.

h2 { "Copy a file with one reusable buffer" }

Expand Down Expand Up @@ -60,10 +60,14 @@ h2 { "writeAll" }

code { "writeAll[S: ByteWriter](stream: S, buffer: ByteBuffer) -> unit ! StreamError" }

Write the entire initialized prefix, suspending as space becomes available. On error some bytes may already have been delivered. StreamError.BrokenPipe carries the native code for a closed peer. StreamError.System carries the OS code and a diagnostic message. StreamError.InvalidArgument reports an incompatible operation.
Write the entire initialized prefix, suspending as space becomes available. On error some bytes may already have been delivered. StreamError.BrokenPipe carries the native code for a closed peer. StreamError.System carries the OS code and a diagnostic message. StreamError.InvalidArgument reports an incompatible operation. TCP endpoints with a time budget report StreamError.TimedOut when it expires.

h2 { "close" }

code { "close[S: PipeCloser](own stream: S) -> unit ! StreamError" }

Consume a PipeReader or PipeWriter. Closing the last writer delivers EOF after pending bytes have been read. Owned endpoints also close when their scope exits. Use std/fs.close for files and std/fs.finish to flush and close a BufferedWriter.
Consume a pipe or TCP endpoint. Closing the last pipe writer or the TCP writer half delivers EOF after pending bytes have been read. Owned endpoints also close when their scope exits. Use std/fs.close for files and std/fs.finish to flush and close a BufferedWriter.

list {
link { url = "/docs/networking", "TCP connections, timeouts and socket ownership" }
}
11 changes: 11 additions & 0 deletions native/cmake/ApplicationIO.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,19 @@ if(BUILD_TESTING)
endforeach()
endif()

if(BUILD_TESTING OR KALANDRA_BUILD_TEST_OBSERVER)
add_executable(kalandra-tcp-lifecycle-tests tests/TcpLifecycleTests.cpp)
target_link_libraries(kalandra-tcp-lifecycle-tests PRIVATE kalandra-native-runtime)
endif()
if(BUILD_TESTING)
add_dependencies(native-io-qualification kalandra-tcp-lifecycle-tests)
add_test(NAME native-tcp-lifecycle COMMAND kalandra-tcp-lifecycle-tests)
set_tests_properties(native-tcp-lifecycle PROPERTIES TIMEOUT 60 LABELS "feature-io")
foreach(variant IN ITEMS debug optimized sanitized thread-sanitized)
add_test(NAME native-tcp-source-${variant}
COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/TcpSourceTests.py"
--compiler "$<TARGET_FILE:kalandra>" --variant "${variant}")
set_tests_properties(native-tcp-source-${variant} PROPERTIES TIMEOUT 240 LABELS "feature-io")
add_test(NAME native-process-streams-${variant}
COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/tests/ProcessSourceTests.py"
--compiler "$<TARGET_FILE:kalandra>" --variant "${variant}")
Expand Down
2 changes: 1 addition & 1 deletion native/gpu-source/AggregateLayout.h
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ planDeviceAggregateLayouts(const TypedModule &input, std::span<const ValueType>
const auto &record = input.records[id];
if (record.standard == StandardRecord::ByteBuffer)
return reject("ByteBuffer is a host resource and cannot be transferred to a GPU");
if (record.standard == StandardRecord::Child ||
if (record.standard == StandardRecord::Child || tcpResource(record.standard) ||
record.standard == StandardRecord::PipeReader ||
record.standard == StandardRecord::PipeWriter ||
record.standard == StandardRecord::File ||
Expand Down
57 changes: 52 additions & 5 deletions native/include/kalandra/FileOperations.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,16 @@ enum class FileAction : std::uint32_t {
DirectoryCreateAll,
RemoveTree,
OpenWatch,
ReadWatch
ReadWatch,
TcpConnect,
TcpListen,
TcpAccept,
TcpLocalPort,
TcpShutdown,
TcpSplit,
TcpTakeReader,
TcpTakeWriter,
TcpTimeout
};
inline std::optional<FileAction> fileAction(std::string_view name) {
if (name == "__openWatch")
Expand Down Expand Up @@ -111,6 +120,43 @@ inline std::optional<FileAction> streamAction(std::string_view name) {
return FileAction::PipeClose;
return {};
}
inline bool netAddressAction(FileAction action) {
return action == FileAction::TcpConnect || action == FileAction::TcpListen;
}
inline bool netAction(FileAction action) {
return action >= FileAction::TcpConnect && action <= FileAction::TcpTimeout;
}
inline std::optional<FileAction> netAction(std::string_view name) {
if (name == "__connectTcp")
return FileAction::TcpConnect;
if (name == "listenTcp")
return FileAction::TcpListen;
if (name == "accept")
return FileAction::TcpAccept;
if (name == "localPort")
return FileAction::TcpLocalPort;
if (name == "shutdownWrite")
return FileAction::TcpShutdown;
if (name == "split")
return FileAction::TcpSplit;
if (name == "takeReader")
return FileAction::TcpTakeReader;
if (name == "takeWriter")
return FileAction::TcpTakeWriter;
if (name.starts_with("__readIntoTcp"))
return FileAction::StreamRead;
if (name.starts_with("__readAppendTcp"))
return FileAction::StreamAppend;
if (name.starts_with("__writeAllTcp"))
return FileAction::StreamWriteAll;
if (name.starts_with("__writeTcp"))
return FileAction::StreamWrite;
if (name.starts_with("__closeTcp"))
return FileAction::PipeClose;
if (name.starts_with("__timeoutTcp"))
return FileAction::TcpTimeout;
return {};
}
inline std::optional<FileAction> processAction(std::string_view name) {
if (name == "start")
return FileAction::Start;
Expand Down Expand Up @@ -149,15 +195,16 @@ inline FileAction streamFileAction(FileAction action) {
}
}
inline bool filePathAction(FileAction action) {
return action == FileAction::OpenWatch || action == FileAction::OpenWalk || action == FileAction::DirectoryCreateAll ||
return netAddressAction(action) || action == FileAction::OpenWatch ||
action == FileAction::OpenWalk || action == FileAction::DirectoryCreateAll ||
action == FileAction::RemoveTree || action == FileAction::Open ||
action == FileAction::OpenDirectory || action == FileAction::Metadata ||
action == FileAction::DirectoryCreate || action == FileAction::RemoveFile ||
action == FileAction::DirectoryRemove;
}
inline bool consumesFile(FileAction action) {
return action == FileAction::PipeClose || action == FileAction::BufferedReader ||
action == FileAction::BufferedWriter || action == FileAction::Finish ||
action == FileAction::Close;
return action == FileAction::TcpSplit || action == FileAction::PipeClose ||
action == FileAction::BufferedReader || action == FileAction::BufferedWriter ||
action == FileAction::Finish || action == FileAction::Close;
}
} // namespace kalandra
14 changes: 14 additions & 0 deletions native/include/kalandra/Semantics.h
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,12 @@ enum class StandardRecord {
WorkItem,
Shared,
Child,
NetError,
TcpStream,
TcpListener,
TcpHalves,
TcpReader,
TcpWriter,
PipeReader,
PipeWriter,
ProcessError,
Expand Down Expand Up @@ -669,6 +675,11 @@ inline OwnedResourceKind ownedResourceKind(const TypedModule &module, const Valu
if (!standard)
return OwnedResourceKind::None;
switch (*standard) {
case StandardRecord::TcpStream:
case StandardRecord::TcpListener:
case StandardRecord::TcpHalves:
case StandardRecord::TcpReader:
case StandardRecord::TcpWriter:
case StandardRecord::PipeReader:
case StandardRecord::PipeWriter:
case StandardRecord::Child:
Expand All @@ -683,6 +694,9 @@ inline OwnedResourceKind ownedResourceKind(const TypedModule &module, const Valu
inline bool isByteBuffer(const TypedModule &module, const ValueType &type) {
return ownedResourceKind(module, type) == OwnedResourceKind::ByteBuffer;
}
inline bool tcpResource(std::optional<StandardRecord> type) {
return type && *type >= StandardRecord::TcpStream && *type <= StandardRecord::TcpWriter;
}
inline bool isFileResource(const TypedModule &module, const ValueType &type) {
const auto kind = ownedResourceKind(module, type);
return kind == OwnedResourceKind::File || kind == OwnedResourceKind::BufferedReader ||
Expand Down
Loading
Loading