当前位置: 移动技术网 > IT编程>开发语言>.net > Pipelines - .NET中的新IO API指引(三) 边看边记

Pipelines - .NET中的新IO API指引(三) 边看边记

2018年11月09日  | 移动技术网IT编程  | 我要评论

经典幽默笑话,师德反思,谁有网站你懂的

pipelines - .net中的新io api指引 作者 marcgravell 

此系列前两篇网上已有的译文

pipelines - .net中的新io api指引(一)

pipelines - .net中的新io api指引(二)

关于system.io.pipelines的一篇说明

system.io.pipelines: .net高性能io

本篇不是翻译,边看边译边记而已。

system.io.pipelines 是对io的统一抽象,文件、com口、网络等等,重点在于让调用者注意力集中在读、写缓冲区上,典型的就是 iduplexpipe中的input output。

可以理解为将io类抽象为读、写两个缓冲区。

目前官方实现还处于preview状态,作者使用socket和networkstream 实现了一个 pipelines.sockets.unofficial

作者在前两篇中提到使用system.io.pipelines 改造stackexchange.redis,在本篇中作者采用了改造现有的simplsockets库来说明system.io.pipelines的使用。

 

simplpipelines,kestrelserver

## simplsockets说明

+ 可以单纯的发送(send),也可以完成请求/响应处理(sendrecieve)
+ 同步api
+ 提供简单的帧协议封装消息数据
+ 使用byte[]
+ 服务端可以向所有客户端广播消息
+ 有心跳检测等等
    属于非常典型的传统socket库。

## 作者的改造说明

### 对缓冲区数据进行处理的一些方案及选型

   1. 使用byte[]拷贝出来,作为独立的数据副本使用,简单易用但成本高(分配和复制)
   2. 使用 readonlysequence<byte> ,零拷贝,快速但有限制。一旦在管道上执行advance操作,数据将被回收。在有严格控制的服务端处理场景(数据不会逃离请求上下文)下可以使用,言下之意使用要求比较高。
   3. 作为2的扩展方案,将数据载荷的解析处理代码移至类库中(处理readonlysequence<byte>),只需将解构完成的数据发布出来,也许需要一些自定义的structs 映射(map)一下。这里说的应该是直接将内存映射为struct?
   4. 通过返回memory<byte> 获取一份数据拷贝,也许需要从arraypool<byte>.share 池中返回一个大数组;但是这样对调用者要求较高,需要返回池。并且从memory<t> 获取一个t[]属于高级和不安全的操作。不安全,有风险。( not all memory<t> is based on t[])
   5. 一个妥协方案,返回一个提供memory<t>(span<t>)的东西,并且使用一些明确的显而易见的api给用户,这样用户就知道应该如何处理返回结果。比如idisposable/using这种,在dispose()被调用时将资源归还给池。
  
   作者认为,设计一个通用的消息传递api时,方案5更为合理,调用方可以保存一段时间的数据并且不会干扰到管道的正常工作,也可以很好的利用arraypool。如果调用者没有使用using也不会有什么大麻烦,只是效率会降低一些,就像使用方案1一样。
     但是方案的选择需要充分考虑你的实际场景,比如在stackexchange.redis 客户端中使用的是方案3;在不允许数据离开请求上下文时使用方案2.。
  一旦选定方案,以后基本不可能再更改。
   针对效率最高的方案2,作者提出的专业建议是 **使用ref struct** 。
   此处选择的是方案5,与方案4的区别就是对memory<t> 的处理,作者使用 system.buffers.imemoryowner<t>接口
 

 public interface imemoryowner<t> : idisposable
 {
  memory<t> memory { get; }
 }

 

   以下为实现代码,dispose时归还借出的数组,并考虑线程安全,避免多次归还(very bad)。
  
private sealed class arraypoolowner<t>:imemoryowner<t>{
 private readonly int _length;
 private t[] _oversized;
 internal arraypoolowner(t[] oversized,int length){
  _length=length;
  _oversized=oversized;
 }
 public memory<t> memory=>new memory<t>(getarray(),0,_length);
 private t[] getarray()=>interlocked.compareexchange(ref _oversized,null,null)
  ?? throw new objectdisposedexception(tostring());
 public void dispose(){
  var arr=interlocked.exchange(ref _oversized,null);
  if(arr!=null) arraypool<t>.shared.return(arr);
 }
}

 

  dispose后如果再次调用memory将会失败,即 使用时 using,不要再次使用。
**对arraypool的一些说明**
+ 从arraypool借出的数组比你需要的要大,你给定的大小在arraypool看来属于下限(不可小于你给定的大小),见:arraypool<t>.shared.rent(int minimumlength);
+ 归还时数组默认不清空,因此你借出的数组内可能会有垃圾数据;如果需要清空,在归还时使用 arraypool<t>.shared.return(arr,true) ;
  作者对arraypool的一些建议: 
增加 imemoryowner<t> rentowned(int length),t[] rent(int minimumlength) 及借出时清空数组,归还时清空数组的选项。

 这里的想法是通过imemoryowner<t>实现一种所有权的转移,典型调用方法如下
 
 void dosomething(imemoryowner<byte> data){
  using(data){
       // ... other things here ...
                dothething(data.memory);
  }
  // ... more things here ...
 }

 

 通过arraypool的借、还机制避免频繁分配。
 
 **作者的警告:**
 + 不要把data.memory 单独取出乱用,using完了就不要再操作它了(这种错误比较基础)
 + 有人会用memorymarshal搞出数组使用,作者认为可以实现一个 memorymanager<t>(arraypoolowner<t> : memorymanager<t>, since memorymanager<t> : imemoryowner<t>)让.span如同.memory一样失败。
 ---- 作者也挺纠结(周道)的 :)。
使用  readonlysequence<t> 填充arraypoolowner(构造,实例化)
 
public static imemoryowner<t> lease<t>(this readonlysequence<t> source)
    {
        if (source.isempty) return empty<t>();
        int len = checked((int)source.length);
        var arr = arraypool<t>.shared.rent(len);//借出
        source.copyto(arr);
        return new arraypoolowner<t>(arr, len);//dispose时归还
    }

 

### 基本api

  服务端和客户端虽然不同但代码有许多重叠的地方,比如都需要某种线程安全机制的写入,需要某种读循环来处理接收的数据,因此可以共用一个基类。
基类中使用iduplexpipe(包括input,output两个管道)作为管道。
public abstract class simplpipeline : idisposable
    {
        private iduplexpipe _pipe;
        protected simplpipeline(iduplexpipe pipe)
            => _pipe = pipe;
        public void dispose() => close();
        public void close() {/* burn the pipe*/}
    }

 

首先,需要一种线程安全的写入机制并且不会过度阻塞调用方。在原simplsockets(包括stackexchange.redis v1)中使用消息队列来处理。调用方send时同步的将消息入队,在将来的某刻,消息出队并写入到socket中。此方式存在的问题
+ 有许多移动的部分
+ 与“pipelines”有些重复
管道本身即是队列,本身具备输出(写、发送)缓冲区,没必要再增加一个队列,直接把数据写入管道即可。取消原有队列只有一些小的影响,在stackexchange.redis v1 中使用队列完成优先级排序处理(队列跳转),作者表示不担心这一点。
**写入api设计**
 + 不一定时同步的
 + 调用方可以单纯的传入一段内存数据(readonlymember<byte>),或者是一个(imemoryowner<byte>)由api写入后进行清理。
  + 先假设读、写分开(暂不考虑响应)

protected async valuetask writeasync(imemoryowner<byte> payload, int messageid)//调用方不再使用payload,需要我们清理
    {
        using (payload)
  {
   await writeasync(payload.memory, messageid);
  }
 }
protected valuetask writeasync(readonlymemory<byte> payload, int messageid);//调用方自己清理

 

 messageid标识一条消息,写入消息头部, 用于之后处理响应回复信息。
   返回值使用valuetask因为写入管道通常是同步的,只有管道执行flush时才可能是异步的(大多数情况下也是同步的,除非在管道被备份时)。

### 写入与错误

首先需要保证单次写操作,lock在此不合适,因为它不能与异步操作很好的协同。考虑flush有可能是异步的,导致后续(continuation )部分可能会在另外的线程上。这里使用与异步兼容的semaphoreslim。
下面是一条指南:**一般来说, 应用程序代码应针对可读性进行优化;库代码应针对性能进行优化。**
以下为机翻原文
> 您可能同意也可能不同意这一点, 但这是我编写代码的一般指南。我的意思是,类库代码往往有一个单一的重点目的, 往往由一个人的经验可能是 "深刻的, 但不一定是    广泛的" 维护;你的大脑专注于那个领域, 用奇怪的长度来优化代码是可以的。相反,应用程序代码往往涉及更多不同概念的管道-"宽但不一定深" (深度隐藏在各种库      中)。应用程序代码通常具有更复杂和不可预知的交互, 因此重点应放在可维护和 "明显正确" 上。
  基本上, 我在这里的观点是, 我倾向于把很多注意力集中在通常不会放入应用程序代码中的优化上, 因为我从经验和广泛的基准测试中知道它们真的很重要。所以。。。我要做一些看起来很奇怪的事情, 我希望你和我一起踏上这段旅程。
 
“明显正确”的代码
private readonly semaphoreslim _singlewriter= new semaphoreslim(1);
protected async valuetask writeasync(readonlymemory<byte> payload, int messageid)
{
    await _singlewriter.waitasync();
    try
    {
        writeframeheader(writer, payload.length, messageid);
        await writer.writeasync(payload);
    }
    finally
    {
        _singlewriter.release();
    }
}

 

这段代码没有任何问题,但是即便所有部分都是同步完成的,就会产生多余的状态机-------大概是 不是所有地方都需要异步处理 的意思。
通过两个问题进行重构
- 单次写入是否没有竞争?(无人争用)
- flush是否为同步
重构,将原writeasync 更名为 writeasyncslowpath,增加新的writeasync
作者的“一些看起来很奇怪的” 实现
 
protected valuetask writeasync(readonlymemory<byte> payload, int messageid)
{
    // try to get the conch; if not, switch to async
//writer已经被占用,异步
    if (!_singlewriter.wait(0))
        return writeasyncslowpath(payload, messageid);
    bool release = true;
    try
    {
        writeframeheader(writer, payload.length, messageid);
        var write = writer.writeasync(payload);
        if (write.iscompletedsuccessfully) return default;
        release = false;
        return awaitflushandrelease(write);
    }
    finally
    {
        if (release) _singlewriter.release();
    }
}
async valuetask awaitflushandrelease(valuetask<flushresult> flush)
{
    try { await flush; }
    finally { _singlewriter.release(); }
}

 

三个地方
1. _singlewriter.wait(0) 意味着writer处于空闲状态,没有其他人在调用
2. write.iscompletedsuccessfully 意味着writer同步flush
3. 辅助方法 awaitflushandrelease 处理异步flush情况
-------------------------------------------------------------------------------------

### 协议头处理

协议头由两个int组成,小端,第一个是长度,第二个是messageid,共8字节。
void writeframeheader(pipewriter writer, int length, int messageid)
{
    var span = writer.getspan(8);
    binaryprimitives.writeint32littleendian(
        span, length);
    binaryprimitives.writeint32littleendian(
        span.slice(4), messageid);
    writer.advance(8);
}

 

### 管道客户端实现 发送
 
public class simplpipelineclient : simplpipeline
{
    public async task<imemoryowner<byte>> sendreceiveasync(readonlymemory<byte> message)
    {
        var tcs = new taskcompletionsource<imemoryowner<byte>>();
        int messageid;
        lock (_awaitingresponses)
        {
            messageid = ++_nextmessageid;
            if (messageid == 0) messageid = 1;
            _awaitingresponses.add(messageid, tcs);
        }
        await writeasync(message, messageid);
        return await tcs.task;
    }
    public async task<imemoryowner<byte>> sendreceiveasync(imemoryowner<byte> message)
    {
        using (message)
        {
            return await sendreceiveasync(message.memory);
        }
    }
}

 

- _awaitingresponses 是个字典,保存已经发送的消息,用于将来处理对某条(messageid)消息的回复。
### 接收循环
 
protected async task startreceiveloopasync(cancellationtoken cancellationtoken = default)
{
   try
   {
       while (!cancellationtoken.iscancellationrequested)
       {
           var readresult = await reader.readasync(cancellationtoken);
           if (readresult.iscanceled) break;
           var buffer = readresult.buffer;
           var makingprogress = false;
           while (tryparseframe(ref buffer, out var payload, out var messageid))
           {
               makingprogress = true;
               await onreceiveasync(payload, messageid);
           }
           reader.advanceto(buffer.start, buffer.end);
           if (!makingprogress && readresult.iscompleted) break;
       }
       try { reader.complete(); } catch { }
   }
   catch (exception ex)
   {
       try { reader.complete(ex); } catch { }
   }
}
protected abstract valuetask onreceiveasync(readonlysequence<byte> payload, int messageid);

 

接收缓冲区里什么时间会有什么东西由发送方和系统环境决定,因此延迟是必然的,所以这里全部按异步处理就好。
- tryparseframe 读出缓冲区数据,根据帧格式解析出实际数据、id等
- onrecieveasync 处理数据,比如对于回复/响应的处理等
- reader中的数据读出后尽快advance一下,通知管道你的读取进度;
解析帧
 
private bool tryparseframe(
    ref readonlysequence<byte> input,
    out readonlysequence<byte> payload, out int messageid)
{
    if (input.length < 8)
    {   // not enough data for the header
        payload = default;
        messageid = default;
        return false;
    }
    int length;
    if (input.first.length >= 8)
    {   // already 8 bytes in the first segment
        length = parseframeheader(
            input.first.span, out messageid);
    }
    else
    {   // copy 8 bytes into a local span
        span<byte> local = stackalloc byte[8];
        input.slice(0, 8).copyto(local);
        length = parseframeheader(
            local, out messageid);
    }
    // do we have the "length" bytes?
    if (input.length < length + 8)
    {
        payload = default;
        return false;
    }
    // success!
    payload = input.slice(8, length);
    input = input.slice(payload.end);
    return true;
}

 

缓冲区是不连续的,一段一段的,像链表一样,第一段就是input.first。
代码很简单,主要演示一些用法;
辅助方法
static int parseframeheader(
    readonlyspan<byte> input, out int messageid)
{
    var length = binaryprimitives
            .readint32littleendian(input);
    messageid = binaryprimitives
            .readint32littleendian(input.slice(4));
    return length;
}

 


onreceiveasync
 
protected override valuetask onreceiveasync(
    readonlysequence<byte> payload, int messageid)
{
    if (messageid != 0)
    {   // request/response
        taskcompletionsource<imemoryowner<byte>> tcs;
        lock (_awaitingresponses)
        {
            if (_awaitingresponses.trygetvalue(messageid, out tcs))
            {
                _awaitingresponses.remove(messageid);
            }
        }
        tcs?.trysetresult(payload.lease());
    }
    else
    {   // unsolicited
        messagereceived?.invoke(payload.lease());
    }
    return default;
}

 


到此为止,其余部分主要是一些服务端和其他功能实现及benchmark。。。
 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网