Stateful Future Transformation

时间:2022-12-23 10:10:31

As an async programming pattern, Future has been popular with many of our programmers across a wide range of languages. Loosely speaking, Future is a wrapper around a value which will be available at some point in the future. Strictly speaking, Future is a monad which supports the following 3 operations:

unit :: T -> Future<T>
map :: (T -> R) -> (Future<T> -> Future<R>)
flatMap :: (T -> Future<R>) -> (Future<T> -> Future<R>)

When holding a future, we know the type of the value, we can register callbacks which will be called when the future is done. But callbacks are not the recommended way to deal with futures, the point of Future pattern is to avoid callbacks and in favor of future transformation. By properly using future transformation, we can make our async code look like sequential code, the callbacks are hidden from us by the futures.

Here is an example, say there are 2 async RPCs. One takes a user ID and returns a future of a list of the user's new message header (ID and title), the other takes a message ID and returns its body.

// RPC 1: Gets a list of new message (headers) of a user.
Future<NewMessagesResponse> getNewMessages(UserId userId); // RPC 2: Gets the full message for a message ID.
Future<Message> getMessage(MessageId messageId); // Data structures.
class Message {
class Header {
MessageId id;
String title;
}
class Body {
...
} Header header;
Body body;
} class NewMessagesResponse {
List<MessageHeaders> headers;
}

Your task is that, given a user ID and a keyword, get the user's new messages whose title contains the keyword. With future transformation, the code may look like:

// Gets the future of a list of messages for a user, whose titles contains a given keyword.
Future<List<Message>> getNewMessages(UserId userId, String keyword) {
Future<NewMessagesResponse> newMessagesFuture = getNewMessages(userId);
Future<List<MessageId>> interestingIdsFuture = filter(newMessagesFuture, keyword);
Future<List<Message>> messagesFuture = getMessages(interestingIdsFuture);
Return messages;
}

The structure of the code is similar to what we do with synchronous code:

List<Message> getNewMessages(UserId userId, String keyword) {
NewMessagesResponse newMessages = getNewMessages(userId);
List<MessageId> interestingIds = filter(newMessages, keyword);
List<Message> messages = getMessages(interestingIds);
Return messages;
}

The async and sync functions are isomorphic, there is a correspondence in their code structure. But their runtime behaviors are different, one happens asynchronously, one happens synchronously.

Now here comes the real challenge. What if we change the RPC a bit, say there may be too many new messages that it has to return messages page by page, each response may contain an optional next page token indicating there are more pages.

// RPC 1: Gets one page of the new message (headers) of a user. The page number is denoted by a pageToken.
Future<NewMessagesResponse> getNewMessageHeaders(UserId userId, String pageToken) class NewMessagesResponse {
List<MessageHeaders> messageHeaders;
String nextPageToken; // Non-empty nextPageToken indicates there are more pages.
}

Your task remains the same, write a function which takes a user ID and a keyword, return a list of the user's new messages whose titles contain the keyword.

Future<List<Message>> getNewMessages(UserId userId, String keyword) {
//TODO
}

The difficulty lies with that in regular future transformations we have fixed number of steps, we can simply chain them together sequentially, then we get one future of the final result; but now because of pagination, the number of steps is not nondeterministic, how can we chain them together?

For synchronous code, we may use a loop like:

List<Message> getNewMessages(UserId userId, String keyword) {
List<MessageId> interestingMessages = new ArrayList<>();
String pageToken = "";
do {
NewMessagesResponse newMessages = getNewMessages(userId, pageToken);
List<MessageId> interestingIds = filter(newMessages, keyword);
allNewMessages.addAll(newMessages.headers);
pageToken = newMessages.nextPageToken;
} while (!isEmpty(pageToken));
}

But unfortunately loop is applicable to futures. How can we get one future for all the pages? Recursion comes to rescue. This is what I call *Stateful Future Transformation*.

class State {
UserId userId;
String keyword;
int pageIndex;
String pageToken;
List<MessageId> buffer;
} Future<State> getInterestingMessages(Future<State> stateFuture) {
return Future.transform(
stateFuture, (State state) -> {
if (state.pageIndex == 0 || !isEmpty(state.pageToken)) {
// Final state.
return Future.immediate(state);
} else {
// Intermediate state.
Future<NewMessagesResponse> newMessagesFuture =
getNewMessages(state.userId, state.pageToken);
return Future.transform(newMessagesFuture, newMessages -> {
state.pageIndex++;
state.pageToken = newMessages.nextPageToken;
state.buffer.addAll(filter(newMessages, state.keyword);
});
}
});
} Future<State> getInterestingMessages(UserId userId, String keyword) {
State initialState = new State(userId, keyword, 0, "", new ArrayList());
Future<State> initialStateFuture = Future.immediate(initialState);
return getInterestingMessages(initialStateFuture);
}

The code above can be refactored into a general stateful future transformation function:

// Transforms the future of an initial state future into the future of its final state.
Future<StateT> transform(
Future<StateT> stateFuture,
Function<StateT, Boolean> isFinalState,
Function<StateT, Future<StateT>> getNextState) {
return Future.transform(
stateFuture,
(StateT state) -> {
return isFinalState.apply(state)
? Future.immediate(state)
: transform(getNextState.appy(state));
}
});
}

Stateful Future Transformation的更多相关文章

  1. Isomorphic JavaScript&colon; The Future of Web Apps

    Isomorphic JavaScript: The Future of Web Apps At Airbnb, we’ve learned a lot over the past few years ...

  2. Spark Streaming揭秘 Day24 Transformation和action图解

    Spark Streaming揭秘 Day24 Transformation和action图解 今天我们进入SparkStreaming的数据处理,谈一下两个重要的操作Transfromation和a ...

  3. Future Works on P4

    Future Works on P4 P4 and NV: MPvisor, Hyper4, HyperV, Flex4 P4 and NFV P4 and Network Cache P4 and ...

  4. explain the past and guide the future 好的代码的标准:解释过去,指引未来;

    好的代码的标准:解释过去,指引未来: Design philosophies | Django documentation | Django https://docs.djangoproject.co ...

  5. &period;Netcore 2&period;0 Ocelot Api网关教程(10)- Headers Transformation

    本文介绍Ocelot中的请求头传递(Headers Transformation),其可以改变上游request传递给下游/下游response传递给上游的header. 1.修改ValuesCont ...

  6. 面向未来的友好设计:Future Friendly

    一年前翻译了本文的一部分,最近终于翻译完成.虽然此设计思想的提出已经好几年了,但是还是觉得应该在国内推广一下,让大家知道“内容策略”,“移动优先”,“响应式设计”,“原子设计”等设计思想和技术的根源. ...

  7. 线程笔记:Future模式

    线程技术可以让我们的程序同时做多件事情,线程的工作模式有很多,常见的一种模式就是处理网站的并发,今天我来说说线程另一种很常见的模式,这个模式和前端里的ajax类似:浏览器一个主线程执行javascri ...

  8. 第二篇 Entity Framework Plus 之 Query Future

    从性能的角度出发,能够减少 增,删,改,查,跟数据库打交道次数,肯定是对性能会有所提升的(这里单纯是数据库部分). 今天主要怎样减少Entity Framework查询跟数据库打交道的次数,来提高查询 ...

  9. (七)Transformation和action详解-Java&amp&semi;Python版Spark

    Transformation和action详解 视频教程: 1.优酷 2.YouTube 什么是算子 算子是RDD中定义的函数,可以对RDD中的数据进行转换和操作. 算子分类: 具体: 1.Value ...

随机推荐

  1. Range Sum Query 2D - Immutable

    https://leetcode.com/problems/range-sum-query-2d-immutable/ 条件说sumRegion 会调很多次,如果每次都用双for 循环去累加的话就有太 ...

  2. Asp&period;NET利用ClientScript&period;RegisterStartupScript&lpar;&quot&semi;&quot&semi;&rpar;的同学,请注意!

    如果你想要在aspx.cs 文件用利用 ClientScript.RegisterStartupScript(""); 方法动态在DOM中执行脚本(比如想要将后置代码中的验证结果信 ...

  3. 那些盒模型在IE6中的BUG们,工程狮的你可曾遇到过?

    HTML5学堂 那些盒模型在IE6中的BUG们,工程狮的你可曾遇到过? IE6已经渐渐的开始退出浏览器的历史舞台.虽然当年IE6作为微软的一款利器击败网景,但之后也因为版本的持续不更新而被火狐和谷歌三 ...

  4. 对武汉-and-IT软件开发的看法

    本编是一个武汉农村娃子,2015年毕业到现在算上实习 差不多*年的时间了.在软件行业混的也就一般水平,从开心在学校学习的winform+DBHelper 的开发模式,到现在MVC+EF 的开发模式. ...

  5. IOS7学习之路九(ios7自定义UIAlertView)

    IOS7的UIAlertView 不支持自定义,无法添加subview . 不过可以用第三方库git上的下载链接    https://github.com/wimagguc/ios-custom-a ...

  6. linux上执行 xhost unable to open display

    linux下执行xhost命令报错:unable to open display,解决方法,linux 下通过xhost进入图形界面,经常会出现报错"unable to  open disp ...

  7. Python之旅&period;第三章&period;函数4&period;01&sol;4&period;02

    一.三元表达式 #普通的判断大小函数def max2(x,y): if x > y: return x else: return yres=max2(10,11)print(res)x=12y= ...

  8. Linux文件检索

    title: Linux文件检索 date: 2017-12-11 19:03:01 tags: linux categories: linux whereis 只要执行 whereis ls 就可以 ...

  9. SQL Server 事务与隔离级别实例讲解

    上班途中,你在一处ATM机前停了下来.正当你在敲入密码的时候,你的一位家人也正在镇上的另一处TAM机上输入密码.你打算从某个还有500元余额的账户上转出400元,而你的家人想从同一账户取走300元.倘 ...

  10. &lbrack;EffectiveC&plus;&plus;&rsqb;item07:declare destructors virtual in polymorphic base class