分类目录归档:未分类

自己来写个co

昨天被问到实现co()(tj/co) 这个很经典的函数,花了几分钟写了下。后来回想下发现有个地方处理得不是很好,故在此小小地总结下。

首先说下co(gen)这个函数

简单点说,这个函数能够执行传入的生成器函数gen,最后返回一个Promise,当gen一切都顺利进行的时候这个 Promise 应该被以起返回值 resolved, 而当有任何异常发生的时候,这个Promise应该被相应地 rejected.比如正常情况下:
const res = await co(function*(){a = yield 1b = yield 2return 3})
那么期望的结果则是a === 1,b === 2res === 3.此外,co(gen)还有个特点,就是当yield一个Promise的时候,co应该等待这个Promise被 resolved 的时候再把 resolved 的值传回gen,而当其被 rejected 的时候应该要把 rejected 的异常在这个gen函数中抛出。当然真正的co库还会处理 thunk, 基于数组或对象的并行Promise, 还有嵌套的 generator.

最初的版本

function co(gen) {return new Promise((resolve, reject) => {try {const generator = gen()const execute = (generator, value) => {const x = generator.next(value)if (x.done) {resolve(x.value)return}const nextValue = x.valueif (isPromiseLike(nextValue)) {nextValue.then(v => execute(generator, v),e => {generator.throw(e) // 出错了,在generator内部抛出异常execute(generator) // 处理被catch的情况})} else {execute(generator, nextValue)}}execute(generator)} catch (e) {reject(e)}})}
现在来看,这个版本能够处理基本的 yield 一个普通值流程,也能处理 yield 一个 Promise 的情况,甚至即使在 gen 函数刚开始被调用的时候抛出了异常的场景下也能如期返回一个被 rejected 的 Promise.但是,有两个问题:1.generator.throw()的返回值没有处理2.generator.next()以及generator.throw()抛出的异常没有处理首先,先来看下generator.throw()说明
语法gen.throw(exception参数 exception - 用于抛出的异常。 使用 Error 的实例对调试非常有...
阅读全文

一个关于systemd私有目录的奇怪问题

今天遇到一个奇怪的问题 -- PHP里面访问不了/tmp/xhprof-data目录,可是这个目录明明是存在的!今天要使用xhprof进行性能分析,但是打开性能分析开关然后访问页面后却发现没有任何性能数据,很奇怪。检查了下httpd的日志,发现有个fatal error:PHP Fatal error: Uncaught exception 'ErrorException' with message 'fopen(/tmp/xhprof-data/57ad36118dcf0.default.xhprof): failed to open stream: No such file or directory'而对应的PHP代码是类似这样:$file = fopen($filePath, 'w');一般来说这个错误应该是目录不存在或权限不足导致的。那么就检查下对应的目录:
➜  /tmp$ ll -d xhprof-datadrwxrwxrwx. 2 apache apache 41 Aug 12 10:34 xhprof-data
目录是存在的呀,而且为了让PHP能访问,特意设置了全部可以读写,并且所属的用户和组都是apache。然后在代码里面测试下这个目录是否可以访问:
// 简单粗暴点,直接加一行打印看看var_dump(is_dir(dirname($filePath)));die;
结果令人吃惊 -- 居然打印出来是false。难道路径错了吗?把路径也重新打印出来核对下:
// 简单粗暴点,直接加一行打印看看var_dump(dirname($filePath));die;
路径打印出来就是/tmp/xhprof-data,没有错!奇葩问题呀!最后尝试删除掉这个目录,然后在PHP里面加一行自动创建目录:
is_dir(dirname($filePath)) or mkdir(dirname($filePath), 0777, true);
结果,居然通了!到tmp目录下看看跟之前创建的有啥区别:
➜  /tmp$ ll xhprof-datals: cannot access xhprof-data: No such file or directory
奇怪了,目录呢? 使用find找下试试:
➜  /tmp$ find . -type d -name xhprof-datafind: ‘./systemd-private-bd5ddddffb9240cdad836fe13ccb096d-httpd.service-kCEghE’: Permission denied➜  /tmp$ sudo !!➜  /tmp$ sudo find . -type d -name xhprof-data./systemd-private-bd5ddddffb9240cdad836fe13ccb096d-httpd.service-kCEghE/tmp/xhprof-data
原来是放到了systemd-private-bd5ddddffb9240cdad836fe13ccb096d-httpd.service-kCEghE下面。这个是个什么鬼? 据google一下的结果,原来是systemd可以配置/tmp目录为私有目录,以防冲突而创建的。检查下配置:
➜  /tmp$ cat /usr/lib/systemd/system/httpd.service | grep PrivateTmpPrivateTmp=true
果然是有对应的这个配置。涨姿势了。特此记录。阅读全文

PlantUML的实例参考

Alice -> Bob: Authentication RequestBob --> Alice: Authentication ResponseAlice -> Bob: Another authentication RequestAlice <-- Bob: another authentication Response

actor Foo1boundary Foo2control Foo3entity Foo4database Foo5Foo1 -> Foo2 : To boundaryFoo1 -> Foo3 : To controlFoo1 -> Foo4 : To entityFoo1 -> Foo5 : To database

actor Bob #red' The only difference between actor'and participant is the drawingparticipant Aliceparticipant "I have a really\nlong name" as L #99FF99/' You can also declare:participant L as "I have a really\nlong name"  #99FF99'/Alice->Bob: Authentication RequestBob->Alice: Authentication ResponseBob->L: Log transaction

Alice -> "Bob()" : Hello"Bob()" -> "This is very\nlong" as Long' You can also declare:' "Bob()" -> Long as "This is very\nlong"Long --> "Bob()" : ok

Alice->Alice: This is a signal to self.\nIt also demonstrates\nmultiline \ntext

Bob ->x AliceBob -> AliceBob ->> AliceBob -\ AliceBob \\- AliceBob //-- AliceBob ->o AliceBob o\\-- AliceBob <-> AliceBob <->o Alice

Bob -[#red]> Alice : helloAlice -[#0000FF]->Bob : okautonumberBob -> Alice : Authentication RequestBob <- Alice : Authentication Responseautonumber 15Bob -> Alice : Another authentication RequestBob <- Alice : Another authentication Responseautonumber 40 10Bob -> Alice : Yet another authentication RequestBob <- Alice : Yet another authentication Responseautonumber "<b>[000]"Bob -> Alice : Authentication RequestBob <- Alice : Authentication Responseautonumber 15 "<b>(<u>##</u>)"Bob -> Alice : Another authentication RequestBob <- Alice : Another authentication Responseautonumber 40 10 "<font color=red><b>Message 0  "Bob -> Alice : Yet another authentication RequestBob <- Alice : Yet another authentication Response

title Simple communication exampleAlice -> Bob: Authentication RequestBob --> Alice: Authentication ResponseAlice -> Bob : Hellolegend rightShortlegendendlegend

Alice -> Bob : message 1Alice -> Bob : message 2newpageAlice -> Bob : message 3Alice -> Bob : message 4newpage A title for the\nlast pageAlice -> Bob : message 5Alice -> Bob : message 6

Alice -> Bob: Authentication Requestalt successful caseBob -> Alice: Authentication Acceptedelse some kind of failureBob -> Alice: Authentication Failuregroup My own labelAlice -> Log : Log attack startloop 1000 timesAlice -> Bob: DNS AttackendAlice -> Log : Log attack endendelse Another type of failureBob -> Alice: Please repeatend

Alice->Bob : hellonote left: this is a first noteBob->Alice : oknote right: this is another noteBob->Bob : I am thinkingnote lefta notecan also be definedon several linesend note

participant Aliceparticipant Bobnote left of Alice #aquaThis is displayedleft of Alice.end notenote right of Alice: This is displayed right of Alice.note over Alice: This is displayed over Alice.note over Alice, Bob #FFAAAA: This is displayed\n over Bob and Alice.note over Bob, AliceThis is yet anotherexample ofa long note.end note

caller -> server : conReqhnote over caller : idlecaller <- server : conConfrnote over server"r" as rectangle"h" as hexagonendrnote

participant Aliceparticipant "The **Famous** Bob" as BobAlice -> Bob : hello --there--... Some ~~long delay~~ ...Bob -> Alice : oknote leftThis is **bold**This is //italics//This is ""monospaced""This is --stroked--This is __underlined__This is ~~waved~~end noteAlice -> Bob : A //well formatted// messagenote right of AliceThis is <back:cadetblue><size:18>displayed</size></back>__left of__ Alice.end notenote left of Bob<u:red>This</u> is <color #118888>displayed</color>**<color purple>left of</color> <s:red>Alice</strike> Bob**.end notenote over Alice, Bob<w:#FF33FF>This is hosted</w> by <img sourceforge.jpg>end note

== Initialization ==Alice -> Bob: Authentication RequestBob --> Alice: Authentication Response== Repetition ==Alice -> Bob: Another authentication RequestAlice <-- Bob: another authentication Response

participant Aliceactor Bobref over Alice, Bob : initAlice -> Bob : helloref over BobThis can be onseveral linesend ref

Alice -> Bob: Authentication Request...Bob --> Alice: Authentication Response...5 minutes latter...Bob --> Alice: Bye !

Alice -> Bob: message 1Bob --> Alice: ok|||Alice -> Bob: message 2Bob --> Alice: ok||45||Alice -> Bob: message 3Bob --> Alice: ok

participant UserUser -> A: DoWorkactivate AA -> B: << createRequest >>activate BB -> C: DoWorkactivate CC --> B: WorkDonedestroy CB --> A: RequestCreateddeactivate BA -> User: Donedeactivate A

participant UserUser -> A: DoWorkactivate A #FFBBBBA -> A: Internal callactivate A #DarkSalmonA -> B: << createRequest >>activate BB --> A: RequestCreateddeactivate Bdeactivate AA -> User: Donedeactivate A

Bob -> Alice : hellocreate OtherAlice -> Other : newcreate control StringAlice -> Stringnote right : You can also put notes!Alice --> Bob : ok

[-> A: DoWorkactivate AA -> A: Internal callactivate AA ->] : << createRequest >>A<--] : RequestCreateddeactivate A[<- A: Donedeactivate A

[-> Bob[o-> Bob[o->o Bob[x-> Bob[<- Bob[x<- BobBob ->]Bob ->o]Bob o->o]Bob ->x]Bob <-]Bob x<-]

@startuml/'This is an example Sequence diagramShowing a fictional web feature flowIt is easy to see roles & responsibilities for each componentand easy to change them too...'/title "Story Feature Example - Sequence Diagram"'This is a single line comment/'This is a multi-line commentOne another line'/actor User'boundary Proxyparticipant UIServer as UIparticipant APIUser -> UI: LINK: goto /account pageactivate UIUI -> User:deactivate UIactivate Usernote over UserRequirments:UI: Setting PageClick delete buttonend note' user requests account/delete pageUser -> UI: /account/deletedeactivate Useractivate UIUI -> User:deactivate UI' confirmation formactivate Usernote over UserUI: FormAre you sure?end noteUser -> UI: POST /account/deletedeactivate Useractivate UInote over UI: Verify: user has confirmedUI -> API: /account/deleteactivate APIAPI -> API: deleteAPI -> UI: donedeactivate APIUI -> User: successdeactivate UI@enduml

阅读全文

一个短信中最多可以容纳多少中英文混合的字符?

今天遇到一个问题——一个短信里面最多可以容纳多少个中英文混编的字符?顺手google了以下,发现这个事情跟我的直觉还是不太一样的,特此记录,以备后查。直觉是
  1. 一条短信最多70个中文字符...
阅读全文