Using socket2 with hyper - sockets

I am writing a http server that works with it's host machine via a unix domain sockets. The server is written using hyper and I am connecting to UDS via socket2.
This is my code:
let socket = Socket::new(Domain::UNIX, Type::STREAM, None)?;
let socket_address = SockAddr::unix("unix://tmp/test.sock")?;
socket.bind(&socket_address)?;
socket.listen(128)?;
let server = hyper::server::Server::builder(socket.into()).serve(service);
What is the right way to do this? I am getting an error saying cannot infer type for type parameter I
error[E0698]: type inside `async fn` body must be known in this context
--> src/server.rs:65:64
|
65 | let server = hyper::server::Server::builder(socket.into()).serve(service);
| ^^^^^ cannot infer type for type parameter `I`
|
note: the type is part of the `async fn` body because of this `await`
--> src/server.rs:66:13
|
66 | let _ = server.await?;
| ^^^^^^^^^^^^
I is the generic parameter to hyper::server::Server. While I am aware what is causing the issue: compiler not able to determine what does socket.into() get cast to, I don't know to solve it.
Please correct if my understanding is wrong. Can I get some help in this?

You need to convert the socket into a type such as tokio::net::UnixListener. Once you have done this, you need an implementation of the Accept trait. You can implement that trait in the following manner:
use hyper::server::accept::Accept;
use tokio::net::UnixListener;
use std::pin::Pin;
use std::task::{Context, Poll};
pub struct UDSAccept {
inner: UnixListener,
}
impl Accept for UDSAccept {
type Conn = tokio::net::UnixStream;
type Error = std::io::Error;
fn poll_accept(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Conn, Self::Error>>> {
match self.inner.poll_accept(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok((socket, _addr))) => Poll::Ready(Some(Ok(socket))),
Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
}
}
}
The above type will be usable as the argument to Server::builder.
If the constructor that comes with the Tokio type does not provide all the options you need and you still wish to use socket2 to construct it, you can do so by first converting it to the std UnixListener and then calling Tokio's from_std method. Be aware that you must set the socket in non-blocking mode yourself when doing this!

Related

NDepend: Find fields that are either a given type or use a given type in their generic parameters

How would I go about using NDepend to not only identify JustMyCode.Fields that are exactly a given type, but also indirectly, i.e. fields like IList<MyType>, IDictionary<int, MyType>, Lazy<T> and all those "nice" generic variants/usages?
Is there any helper method similar to .UsedBy(...) available by any chance that provides such a functionality?
Here is a query to get field typed with String or Int32:
let types = Types.WithFullNameIn(
"System.String",
"System.Int32").ToArray()
from f in Application.Fields
where !f.ParentType.IsEnumeration &&
f.FieldType != null &&
types.Contains(f.FieldType)
select new { f, type =f.FieldType }
For now you cannot detect when a type is used in a generic parameter.

Using Rust libraries reqwest and select in conjunction

I am trying to follow the example here:
https://rust-lang-nursery.github.io/rust-cookbook/web/scraping.html, which utilizes both Reqwest and Select in order to get an html response then parse the data.
I am using Reqwest version 0.10.4 and Select version 0.4.3 which are the versions it shows in the example. However, I am getting an error:
error[E0277]: the trait bound `reqwest::Response: std::io::Read` is not satisfied
--> src/main.rs:19:25
|
19 | Document::from_read(res)?
| ^^^ the trait `std::io::Read` is not implemented for `reqwest::Response`
|
::: /root/.cargo/registry/src/github.com-1ecc6299db9ec823/select-0.4.3/src/document.rs:31:25
|
31 | pub fn from_read<R: io::Read>(mut readable: R) -> io::Result<Document> {
| -------- required by this bound in `select::document::Document::from_read`
It seems like the from_read method takes in a Read type but the reqwest::get method returns a different type. Is there some sort of conversion that must be done first before the response is passed to the from_read method?
This is the example:
#[macro_use]
extern crate error_chain;
extern crate reqwest;
extern crate select;
use select::document::Document;
use select::predicate::Name;
error_chain! {
foreign_links {
ReqError(reqwest::Error);
IoError(std::io::Error);
}
}
fn main() -> Result<()> {
let res = reqwest::get("https://www.rust-lang.org/en-US/").await?;
Document::from_read(res)?
.find(Name("a"))
.filter_map(|n| n.attr("href"))
.for_each(|x| println!("{}", x));
Ok(())
}
reqwest::get returns a Result<Response>, then with the ? you are unwrapping the Result, meaning you now have a Response object as documented here. And because a web call can successfully occur but still fail (see HTTP non 200 codes) you should check the response code, but since this is to learn we'll ignore it. What you want is a struct that implements the std::io::Read trait, reading up on that shows that String implements that trait. Going back to reqwest::Response shows that we can get the string returned using the method text(). So your code now becomes
let res = reqwest::get("https://www.rust-lang.org/en-US/")
.await?
.text()
.await?;
Update from the comments: Now the problem is that Document::from_read only accepts std::io::Read as parameters, and std::string::String does not implement that trait, and instead of using a crate like stringreader we can simply use Document::from as document implements the From<&'a str> trait.
And, as with almost everything, there are multiple ways of solving this. You could either
Create the Document from the string directly with Document::from(res), or
Convert the string to a byte slice, which implements Read, and create the document from that with Document::from_read(res.as_bytes())

Casting Protobuf Messages to their Extended type

Im learning about protobuf and am playing with alexeyxo/protobuf-swift.
Is there a way to cast protobuf Messages into the type they extend?
proto file:
message Command_Login {
extend SessionCommand {
optional Command_Login ext = 1001;
}
optional string user_name = 1;
optional string password = 2;
}
Here is the swiftcode:
let commandContainerBuilder = CommandContainer.Builder()
commandContainerBuilder.sessionCommand.append(commandLogin)
// sessionCommand is an array of SessionCommand (of which Command_Login extends)
Error:
Cannot convert value of type CommandLogin? to expected argument type SessionCommand
Sorry, you've misinterpreted extensions. I say "sorry" because this is probably my fault -- I designed the "extensions" feature, and unfortunately by using the word "extend" I confused a lot of people.
You see, extensions have nothing to do with inheritance. In your example, you are not declaring that Command_Login is any kind of subclass of SessionCommand. This is easier to understand if we shift the declarations around a bit:
message Command_Login {
optional string user_name = 1;
optional string password = 2;
}
extend SessionCommand {
optional Command_Login ext = 1001;
}
The above is completely valid and exactly equivalent to your code except for one difference: In your version, the extension's name is Command_Login.ext (because you declared it nested inside Command_Login), but in my version the name is just ext (in the global scope). Other than namespacing, they function the same.
What the extend clause actually does is declare a new field on SessionContext, where the type of that field is Command_Login. If you happen to place an extend clause inside of a message block, this only matters for namespacing purposes, much like declaring static members of a class in C++ or Java.

initialize systemverilog (ovm) parameterized class array

I want to monitor several analysis ports, and "publish" the item through one analysis port.
It works for predefined item type, but fail to be parameterized.
The code:
class ovm_analysis_sink #(int NUM_PORTS = 1, type T = ovm_object ) extends ovm_component;
// .......................................
`ovm_component_param_utils(ovm_analysis_sink#(NUM_PORTS,T))
// .......................................
ovm_analysis_imp #(T,ovm_analysis_sink) mon_analysis_imp[NUM_PORTS-1:0];
ovm_analysis_port #(T) mon_analysis_port = new("mon_analysis_port", this);
virtual function void build() ;
string inst;
for(int i=0 ;i < NUM_PORTS ;i++ )
begin
$sformat(inst,"mon_analysis_imp_%0d",i);
mon_analysis_imp[i] = new(inst,this);
end
super.build() ;
endfunction : build
The usage of the analysis_sink:
ovm_analysis_sink #(3,a_type) a_item_sink;
And the error message:
Error-[ICTTFC] Incompatible complex type usage ovm_tb.sv, 42
Incompatible complex type usage in task or function call.
The following expression is incompatible with the formal parameter of the function.
The type of the actual is 'class $unit::ovm_analysis_sink#(3,class $unit::a_type)',
while the type of the formal is 'class $unit::ovm_analysis_sink#(1,class ovm_pkg::ovm_object)'.
Expression: this Source info: ovm_analysis_imp::new(inst, this)
The error says type incompatibility. That means the actual (run-time) and formal (compile-time) arguments/types of implementation port is not the same.
There is an error while declaration of analysis port. Declaring the port as shown above creates a handle of analysis imp port of type uvm_analysis_sink #(1,uvm_object) while, you want it to be of type uvm_analysis_sink #(3,a_type).
So, declare it as follows:
ovm_analysis_imp #(T,ovm_analysis_sink#(NUM_PORTS,T)) mon_analysis_imp[NUM_PORTS-1:0];
This shall remove the type conflict and make it type assignment compatible. Now any parameter overriding shall work.
I have created a sample UVM code on EDAPlayground for reference. Similar applies to your OVM testbench. For further information refer to this forum question.

How do I cast to an interface an object may implement?

I have the following classes & interfaces:
export interface IBody {
body : ListBody;
}
export class Element {
// ...
}
export class Paragraph extends Element implements IBody {
// ...
}
export class Character extends Element {
// ...
}
I have code where I will get an array of Element derived objects (there are more than just Paragraph & Character). In the case of those that implement IBody, I need to take action on the elements in the body.
What is the best way to see if it implements IBody? Is it "if (element.body !== undefined)"?
And then how do I access it? "var bodyElement = <IBody> element;" gives me an error.
C:/src/jenova/Dev/Merge/AutoTagWeb/client/layout/document/elements/factory.ts(34,27): error TS2012: Cannot convert 'Element' to 'IBody':
Type 'Element' is missing property 'body' from type 'IBody'.
Type 'IBody' is missing property 'type' from type 'Element'.
thanks - dave
An interface in TypeScript is a compile-time only construct, with no run-time representation. You might find section 7 of the TypeScript specification interesting to read as it has the complete details.
So, you can't "test" for an interface specifically. Done correctly and completely, you generally shouldn't need to test for it as the compiler should have caught the cases where an object didn't implement the necessary interface. If you were to try using a type assertion:
// // where e has been typed as any, not an Element
var body = <IBody> e;
The compiler will allow it without warning as you've asserted that the type is an IBody. If however, e were an Element in scope, the compiler as you've shown will check the signature of the Element and confirm that it has the properties/methods declared by IBody. It's important to note that it's checking the signature -- it doesn't matter that it may not implement IBody as long as the signature matches up.
Assuming that Element has a signature that matches IBody, it will work. If it does not, you'll get the compiler error you're receiving. But, again, if it's declared as any, the assertion will pass and at run-time, unless the type has the methods defined on IBody, the script will fail.
As your Element is the base class, you cannot check for IBody. You could declare an argument as any:
function someFeature(e: any) {
}
And then assert that the IBody is present:
function someFeature(e: any) {
var body :IBody = <IBody> e;
// do something
}
However, if you do need a run-time check, you'd need to look for the function on the prototype or as a property before using it. While that could be misleading in some cases, the interface in TypeScript also may not have caught the mismatch either. Here's an example of how you could check for the existence of a specific function.
It might look like this:
function someFeature(e: any) {
var body = <IBody> e;
if (typeof (body.someFunctionOnBodyInterface) === "undefined") {
// not safe to use the function
throw new Error("Yikes!");
}
body.someFunctionOnBodyInterface();
}