Блог*
#prog #rust #rustlib assay — более мощный тест-раннер для Rust. В частности, позволяет запускать каждый тест в отдельном процессе
#prog #rust #rustlib
testcontainers
A library for integration testing against docker containers from within Rust.
This crate is the official Rust language fork of Testcontainers.
Tests should be self-contained and isolated. While this is usually easy for unit-tests, integration-tests typically require a more complex environment. The testcontainers ecosystem facilitates self-contained and isolated integration tests. It allows to easily spin up Docker containers from within your tests and removes them afterwards.
testcontainers
A library for integration testing against docker containers from within Rust.
This crate is the official Rust language fork of Testcontainers.
Tests should be self-contained and isolated. While this is usually easy for unit-tests, integration-tests typically require a more complex environment. The testcontainers ecosystem facilitates self-contained and isolated integration tests. It allows to easily spin up Docker containers from within your tests and removes them afterwards.
docs.rs
testcontainers - Rust
A library for integration testing against docker containers from within Rust.
👍7
#prog #rust #rustasync #rustlib #amazingopensource
Вот
Странно, что я раньше про это не рассказывал. Для tokio есть инструментарий, который позволяет собирать информацию об исполнении тасок в программе на Rust на tokio и потом эту информацию отображать. Конкретно tokio-console реализует CLI с TUI, но за счёт формата, определённого отдельно, бекенд для визуализации можно сделать и другой.
Вот
Странно, что я раньше про это не рассказывал. Для tokio есть инструментарий, который позволяет собирать информацию об исполнении тасок в программе на Rust на tokio и потом эту информацию отображать. Конкретно tokio-console реализует CLI с TUI, но за счёт формата, определённого отдельно, бекенд для визуализации можно сделать и другой.
🔥21👎1
#prog #rust #article
Atomicless Concurrency
Let’s say we’re building an allocator. Good allocators need to serve many threads simultaneously, and as such any lock they take is going to be highly contended. One way to work around this, pioneered by TCMalloc, is to have thread-local caches of blocks (hence, the “TC” - thread cached).
Unfortunately threads can be ephemeral, so book-keeping needs to grow dynamically, and large, complex programs (like the Google Search ranking server) can have tens of thousands of threads, so per-thread cost can add up. Also, any time a thread context-switches and resumes, its CPU cache will contain different cache lines – likely the wrong ones. This is because either another thread doing something completely different executed on that CPU, or the switched thread migrated to execute on a different core.
These days, instead of caching per-thread, TCMalloc uses per-CPU data. This means that book-keeping is fixed, and this is incredibly friendly to the CPU’s cache: in the steady-state, each piece of the data will only ever be read or written to by a single CPU. It also has the amazing property that there are no atomic operations involved in the fast path, because operations on per-CPU data, by definition, do not need to be synchronized with other cores.
This post gives an overview of how to build a CPU-local data structure on modern Linux. The exposition will be for x86, but other than the small bits of assembly you need to write, the technique is architecture-independent.
Atomicless Concurrency
Let’s say we’re building an allocator. Good allocators need to serve many threads simultaneously, and as such any lock they take is going to be highly contended. One way to work around this, pioneered by TCMalloc, is to have thread-local caches of blocks (hence, the “TC” - thread cached).
Unfortunately threads can be ephemeral, so book-keeping needs to grow dynamically, and large, complex programs (like the Google Search ranking server) can have tens of thousands of threads, so per-thread cost can add up. Also, any time a thread context-switches and resumes, its CPU cache will contain different cache lines – likely the wrong ones. This is because either another thread doing something completely different executed on that CPU, or the switched thread migrated to execute on a different core.
These days, instead of caching per-thread, TCMalloc uses per-CPU data. This means that book-keeping is fixed, and this is incredibly friendly to the CPU’s cache: in the steady-state, each piece of the data will only ever be read or written to by a single CPU. It also has the amazing property that there are no atomic operations involved in the fast path, because operations on per-CPU data, by definition, do not need to be synchronized with other cores.
This post gives an overview of how to build a CPU-local data structure on modern Linux. The exposition will be for x86, but other than the small bits of assembly you need to write, the technique is architecture-independent.
#prog #article
The Alkyne GC
Статья описывает устройство сборщика мусора для скриптового языка программирования. Этот сборщик мусора относительно простой (однопоточный, stop-the-world, mark-and-sweep, без поддержки финализаторов), но не примитивный. На его примере демонстрируются техники оптимизации, которые используются в реальных сборщиках мусора.
The Alkyne GC
Статья описывает устройство сборщика мусора для скриптового языка программирования. Этот сборщик мусора относительно простой (однопоточный, stop-the-world, mark-and-sweep, без поддержки финализаторов), но не примитивный. На его примере демонстрируются техники оптимизации, которые используются в реальных сборщиках мусора.
👍10
Forwarded from ☕️ Мерлин заваривает τσάι 🐌
Так интересно слушать споры "разумна ли модель X или нет"
Люди, я не уверен что вы обладаете разумом.
Что уж говорить, не уверен что у меня самого есть разум.
Люди, я не уверен что вы обладаете разумом.
Что уж говорить, не уверен что у меня самого есть разум.
🤔11👍3😁2👎1
#prog #rust #rustasync #suckassstory
Ask not what the compiler can do for you
TL;DR: из-за того, что
Ask not what the compiler can do for you
TL;DR: из-за того, что
async_trait
боксит футуры и стирает типы, в асинхронном коде, использующем этот крейт, можно организовать безусловную рекурсию, и ни компилятор, ни clippy этого не отловят.GitHub
Ask not what the compiler can do for you
An Open Source Financial Switch to make Payments fast, reliable and affordable - juspay/hyperswitch
👍1
Окей, пусть требуется из кода поднять сетевой интерфейс на Linux. Не вопрос, получаем имя интерфейса через getifaddrs, заполняем
и вызываем ioctl с нужными флагами:
Есть только маааленький вопрос: какой именно файловый дескриптор нужен в качестве первого аргумента? Это обязательно должен быть сокет? Если да, то какой? AF_INET с SOCK_DGRAM, как это сделано в убогой interfaces? Или, может, как в одной из реализаций busybox, последовательно пробовать разные варианты сокетов? Почему в манах нигде об этом не написано? Почему, блин, в этих ваших интернетах нигде об этом не написано (а если и написано, то про работу через совсем другой способ, по протоколу netlink)?
И ещё. Какого хрена это идиотское сокращение IFNAMSZ? Буков жалко было?
struct ifreq req;
strncpy(&if_req, name, IFNAMSZ);
req.flags = IFF_UP;
и вызываем ioctl с нужными флагами:
ioctl(sock, SIOCSIFFLAGS, &req);
Есть только маааленький вопрос: какой именно файловый дескриптор нужен в качестве первого аргумента? Это обязательно должен быть сокет? Если да, то какой? AF_INET с SOCK_DGRAM, как это сделано в убогой interfaces? Или, может, как в одной из реализаций busybox, последовательно пробовать разные варианты сокетов? Почему в манах нигде об этом не написано? Почему, блин, в этих ваших интернетах нигде об этом не написано (а если и написано, то про работу через совсем другой способ, по протоколу netlink)?
И ещё. Какого хрена это идиотское сокращение IFNAMSZ? Буков жалко было?
GitHub
interfaces-rs/src/lib.rs at master · andrew-d/interfaces-rs
Library to work with network interfaces in Rust. Contribute to andrew-d/interfaces-rs development by creating an account on GitHub.
🤔4❤1👍1🤬1
#prog #tip
Встроенное в VS Code расширение для работы с Git очень помогает с ребейзами: показывает сообщение коммита, которое можно тут же и отредактировать, показывает отдельно списки staged changes и unstaged changes, одной кнопкой позволяет перевести отдельный файл из второе в первое, а также предупреждает, если вы пытаетесь застейджить файл с маркерами конфликта слияния (и да, конкретно этот пункт мне уже разок помог).
UPD: предупреждает при попытке застейджить файл с несохранёнными изменениями.
Встроенное в VS Code расширение для работы с Git очень помогает с ребейзами: показывает сообщение коммита, которое можно тут же и отредактировать, показывает отдельно списки staged changes и unstaged changes, одной кнопкой позволяет перевести отдельный файл из второе в первое, а также предупреждает, если вы пытаетесь застейджить файл с маркерами конфликта слияния (и да, конкретно этот пункт мне уже разок помог).
UPD: предупреждает при попытке застейджить файл с несохранёнными изменениями.
👌11