顯示具有 web 標籤的文章。 顯示所有文章
顯示具有 web 標籤的文章。 顯示所有文章

2025/09/08

Open Street Map Local Server

Switch2OSM

https://switch2osm.org/

因為 Open Street Map 的免費公用特性,所以我們可以複製這些地圖資料到自己的地圖 server,Switch2OSM 是一個推廣 OSM 的專案,我們可以透過這個專案,建置自己的 Map Server

PBF format

.pbf空間數據詳解

PBF 就是 Protocolbuffer Binary Format 這是基於 ProtoBuffer 的一種 binary data format,這是一種比 XML, GeoJSON 等等地圖格式還要精簡的檔案格式。

在 OSM 通常是以 *.osm.pbf 這個 file extension 代表 OSM PBF file

Open Street Map 在 PBF Format - OpenStreetMap Wiki 有說明該檔案格式的定義。

Taiwan OSM

Geofabrik Download Server Taiwan 這個網站,有固定更新從 Open Street Map 下載的 Taiwan 離線地圖,我們可以到這個網站下載 taiwan-latest.osm.pbf

取得 osm PBF 檔案以後,就可以匯入 switch2osm local map server

docker

參考 Using a Docker container – Switch2OSM 的說明,最簡單的方式就是透過 container 建置 switch2osm

以下以 Redhat 系列的 podman 進行測試

匯入 osm.pbf 檔案

podman volume create osm-data

podman run  --name osmtile-import -v /root/download/osm/taiwan-latest.osm.pbf:/data/region.osm.pbf  -v osm-data:/data/database/  overv/openstreetmap-tile-server  import

tile server

podman volume create osm-tiles
# 啟動 tile server
podman run --name osmtile -p 8081:80 -v osm-data:/data/database/ -v osm-tiles:/data/tiles -d overv/openstreetmap-tile-server run

啟動後就可以在 http://localhost:8081/tile/ 看到透過 Leaflet 取得的 OSM 地圖

2024/07/29

CORS

同源政策 Same-origin policy 是在Web瀏覽器中,允許某個網頁指令碼也就是 javascript 訪問另一個網頁的資料的前提是,這兩個網頁必須有相同的URI、主機名和埠號,一旦兩個網站滿足上述條件,這兩個網站就被認定為具有相同來源。在 same origin policy 的限制下,能限制瀏覽器防止某個網頁上的惡意指令碼通過該頁面的文件物件模型存取另一網頁上的敏感資料。

滿足同源的條件有三個

  1. 使用相同的通訊協定 http/https

  2. 有相同的網域 domain

  3. 有相同的 port

跨來源請求 cross-origin http request,就是在非同源的情況下,發生的 http request,在發生這種狀況時,必須要遵守 CORS (Cross-Origin Resource Sharing) 的規範

定義

CORS 就是針對非同源的 http request 制定的規範,當 javascript 存取非同源的資源時, server 必須明確告知瀏覽器,是否允許這樣的 request,只有 server 允許的 request 能夠被瀏覽器發送,否則就會失敗

CORS 的跨來源請求有兩種:「簡單」與「非簡單」

跨來源請求

「簡單」跨來源請求有兩個條件

  1. 只能使用 GET, POST, HEAD method

  2. http reques header 只能有 AcceptAccept-LanguageContent-Language 或 Content-Type,且 Content-Type 只能是 application/x-www-form-urlencodedmultipart/form-data 或 text/plain

只要不是「簡單」跨來源請求,就是「非簡單」跨來源請求

簡單請求 simple requests 不會觸發 CORS 預檢 preflighted

sample

以下是一個 cross-origin request/response,可發現在 request 裡面,會有一個 Origin http header

Origin 標記,這是來自 http://foo.example 的 cross-orign request

GET /resources/public-data/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Referer: http://foo.example/examples/access-control/simpleXSInvocation.html
Origin: http://foo.example


HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 00:23:53 GMT
Server: Apache/2.0.61
Access-Control-Allow-Origin: *
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/xml

[XML Data]

下面的 response 有 Access-Control-Allow-Origin 這個 header,* 表示server 允許來自任意 origin 的 http request

預檢 preflighted request

「非簡單」request,在瀏覽器真正發送 request 之前,會先發送一個 preflight request,用途是詢問 server 是否允許這樣的 request

preflighted request 是用 http OPTIONS method 產生的

在 request 會有這兩個 header

  1. Access-Control-Request-Method:該 request 是哪一個 http method

  2. Access-Control-Request-Headers:該 request 裡面待有哪些非簡單的 http header

OPTIONS /resources/post-here/ HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3pre) Gecko/20081130 Minefield/3.1b3pre
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Connection: keep-alive
Origin: http://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type


HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Vary: Accept-Encoding, Origin
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

response 有以下重點

  1. Access-Control-Allow-Origin:允許的 origin

  2. Access-Control-Allow-Methods:允許的跨 origin http method

  3. Access-Control-Allow-Headers:允許使用的 http header

  4. Access-Control-Max-Age:本次預檢請求回應所可以快取的秒數,代表 browser 可 cache 這個 response 多久

cookie

通常 CORS 不允許使用 cookie,也不支援 redirect

如果真的還是要使用 cookie

fetch API 要加上 credentials

fetch('https://othersite.com/data', {
  credentials: 'include'
})

XMLHttpRequest 要加上 withCredentials = true

const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('POST', 'https://othersite.com/data');

server 端也要增加一個 response header

Access-Control-Allow-Credentials: true

使用 cookie 時,Access-Control-Allow-Origin 不能直接填寫 *

必須明確標示哪些 origin 可以使用 cookie

References

跨來源資源共用(CORS) - HTTP | MDN

[教學] 深入了解 CORS (跨來源資源共用): 如何正確設定 CORS?

2024/07/01

WebAuthn

WebAuthn 是 Web 與 Authentication 結合的縮寫,也就是 Web Authentication,用在網頁身份認證。這個規格是由 W3C 與 FIDO (Fast IDentity Online) 提出,該正式API 規格,透過瀏覽器的支援,可透過 Public Key Cryptography 機制註冊並認證使用者,取代傳統密碼形式的認證方式。

最傳統的身份認證機制是用密碼,但因為密碼太多了,又因為資安政策需要常常修改密碼,正常人應該已經沒辦法記得很清楚,哪個網站是用哪一個密碼。

WebAuthn 是  FIDO2 framework 的部分,透過 server, browser, authenticator 的搭配,提供一種 passwordless 無密碼的認證方式。

Demo

webauthn.io 是一個單純的網頁 demo。demo 時分兩個步驟,Register 與 Authenticate。

Register 就是註冊帳號,使用者向 browser 要求要註冊一個新帳號,browser 透過 authenticator 的搭配輔助,產生一組 public key,然後完成註冊的步驟。 authenticator 可能是本機的指紋 scanner,也可以是 USB key,或是目前最容易取得的每一個人的手機,並搭配手機的 FaceID 或是指紋 scanner 輔助做身份認證。

註冊完成後,會取得註冊的 id,然後在透過認證 API,進行使用者身份認證。

Javascript demo

註冊

// should generate from server
const challenge = new Uint8Array(32);
window.crypto.getRandomValues(challenge);

const userID = '5d157c55-ea8b-45ca-870a-da877a9c9916';

const utf8EncodeText = new TextEncoder();
const id = utf8EncodeText.encode(userID);

const publicKeyCredentialCreationOptions = {
    challenge,
    rp: {
        name: "Maxkit RP",
        // 這邊只是 demo,沒有放到某個 https 網站測試,如果是網站,就要改成該網站的 domain name
        //id: "maxkit.com.tw",
    },
    user: {
        id,
        name: "test",
        displayName: "Test",
    },
    pubKeyCredParams: [{alg: -7, type: "public-key"}],
    authenticatorSelection: {
        authenticatorAttachment: "cross-platform",
    },
    timeout: 60000,
    attestation: "direct"
};

const credential = await navigator.credentials.create({
    publicKey: publicKeyCredentialCreationOptions
});

把上面這一部分的 js code 直接貼到 chrome console 執行。主要就是透過 navigator.credentials.create 註冊產生 public key

challenge 欄位是由 server 產生,最終會由 authenticator 以私鑰簽章後,在 credential response 裡面傳回來,讓 server 能夠檢查確認 authenticator

rp.id 應該要填網域 domain name,這邊只是本機測試,不填寫

authenticatorAttachment: "cross-platform" 的意思是,可搭配使用外部認證工具,例如在 NB 瀏覽認證網頁時,可使用手機作為認證工具進行認證。

在 NB 提示認證時,會看到這個畫面

這時候,就用自己的手機相機,拍 QR code,手機上會出現以下畫面

確認後,會在手機的密碼部分,儲存一個專屬的密碼。iOS 手機選單在 "設定 -> 密碼"

在 console 列印 credential 的內容

// print credential
console.log(credential)
PublicKeyCredential {rawId: ArrayBuffer(20), response: AuthenticatorAttestationResponse, authenticatorAttachment: 'cross-platform', id: 'ku22CGGrZdYlkr9cCXL4IWtyYLc', type: 'public-key'}

正常狀況應該把 credential 傳送到 server,檢查並 decode 得到使用者的 id, public key。這邊僅是測試 demo,不做處理。

response.attestationObject 裡面有 public key 跟其他 metadata,是用 CBOR Concise Binary Object Representation 編碼後的 binary data。

認證

以下是認證的 demo code,從剛剛的 credential.id 欄位取得 id,通常應該是儲存在 server,從 server 傳到網頁得到這個資料

const credentialIdStr = credential.id;
const credentialId = Uint8Array.from(window.atob(credentialIdStr), c=>c.charCodeAt(0));

const challenge2 = new Uint8Array(32);
window.crypto.getRandomValues(challenge2);

const publicKeyCredentialRequestOptions = {
    challenge: challenge2,
    //rpId: "maxkit.com.tw",
    allowCredentials: [{
        id: credentialId, // from registration
        type: 'public-key',
        transports: ['usb', 'ble', 'nfc', 'hybrid'],
    }],
    timeout: 60000,
}

const assertion = await navigator.credentials.get({
    publicKey: publicKeyCredentialRequestOptions
});

transports 是可以認證的方式

網頁同樣會出現 QR code,等待 authenticator,這邊我們用剛剛註冊的手機掃描

手機掃描時,會出現一個提示

點"使用通行密鑰登入"

繼續透過 FaceID 認證,認證完成,同樣可取得 response

console.log(assertion)

CTAP

Client-to-Authenticator Protocol,這是在瀏覽器打開註冊/認證網頁後,authnticator 跟瀏覽器之間傳輸的協定,也就是 WebAuthn API 跟外部硬體認證機制溝通的規格

References

WebAuthn guide

什么是WebAuthn:在Web上使用Touch ID和Windows Hello登录_webauthn 网站登录-CSDN博客

你可能不知道的WebAuthN(FIDO) | 又LAG隨性筆記

初探 WebAuthn UAF 的無密碼 Passwordless 登入技術 – 要改的地方太多了,那就改天吧

一起來了解 Web Authentication

CredentialsContainer - Web APIs | MDN

2024/02/26

Well-known URI

well-known URI 是網站上以 /.well-known/ 開始的網頁路徑,例如 https://www.example.com/.well-known/ 這樣的路徑。Well-known URI 是在 RFC 8615 定義,目的是在不同 http server 之間,提供該 http server 相關的一些資訊。

目前最常見的使用方式有兩種,第一種是在申請 http server SSL 憑證的時候,憑證中心會發送一個檔案給申請者,請申請者將該檔案放到 .well-known 的某個路徑下,讓憑證中心可以檢查確認憑證申請者確實有服務該網域的 http server 的所有權。

例如 Let's Encrypt 就是將驗證的檔案放在這個路徑下面 /.well-known/acme-challenge/,這是給 ACME (Automatic Certificate Management Environment) 使用的

第二種是給 Android iOS 手機使用的

  • /.well-known/assetlinks.json 是 Digital Asset Links,可告訴Android browser,要使用什麼 APP 打開

  • /.well-known/apple-app-site-association Universal Links,是 iOS 使用的

GitHub - moul/awesome-well-known: A curated list of well-known URIs, resources, guides and tools (RFC 5785) 這個網頁提供了 .well-known 網址的使用列表

References

Well-known URI - Wikipedia

2024/01/15

webcam 即時影像

有一種特殊的 MIME 類型,稱為 multipart/x-mixed-replace,這是由 Netscape 在1995年引入的。當伺服器想向客戶端持續發送資料時,瀏覽器可以在一個 http 通道中,持續接收這些改變的資料。它可以用於串流傳輸圖像的 webcam。

通常 http protocol 會需要 content-length 這個 header,讓接收資料的一端,明確知道這個 http 封包的資料有多少,但 multipart/x-mixed-replace 刻意在 client 打開一個 http 連線後,不回傳 response 的 content length,反而是直接用 multipart 的格式,持續對 client 發送資料。browser 在收到這些 content 時,可用來持續更新畫面。

最常見的應用是 webcam,在高速公路、氣象局的網頁,有即時影像的區塊,就是用這種方式實作的。

response 的資料可以是這種格式,這是持續發送圖片

HTTP/1.1 200 OK
Content-Type: multipart/x-mixed-replace; boundary=frame

--frame
Content-Type: image/jpeg

<1.jpg>

--frame
Content-Type: image/jpeg

<2.jpg>

--frame
Content-Type: image/jpeg

<3.jpg>

也可以是這種格式

HTTP/1.1 200 OK
Content-Type: multipart/x-mixed-replace; boundary=frame

--frame
Content-Type: text/html

<html><body>0</body></html>

--frame
Content-Type: text/html

<html><body>1</body></html>

--frame
Content-Type: text/html

<html><body>2</body></html>

每個 multipart 區塊,可以定義告知 content-type

在氣象局的即時影像網頁,每一次取得影像,都會在 30s 以後,關閉這個連線,使用者必須要重新點一次,才會再取得一次 webcam 資料。

References

使用 multipart/x-mixed-replace 实现 http 实时视频流

Albert 的筆記本: 高速公路路況即時影像的作法

iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天

推播技術 - 維基百科,自由的百科全書

2022/02/07

JSON Web Token

JSON Web Token (JWT) 提供一種方法,可在 client 跟 server 之間使用,client 儲存的 JWT,可傳送到 server 進行身份驗證。因為 JWT 是以 base64 編碼原始資料,故 JWT 裡面儲存的資料,並不適合存放真實的使用者相關資料,而是要存放一份可讓 client 存取 server 資源的 token,JWT 透過內建的憑證簽章機制,驗證 JWT 是否有被竄改。

JWT 內容

JWT 就是一個單純的字串,內容有三個部分,header, payload, signature,三個部分用 . 句號連接起來。

{"typ":"JWT","alg":"HS256"}

有兩個欄位

  • typ

    是用 MIME type 定義的 "JWT" 說明這是一個 Json Web Token

  • alg

    簽章演算法,在 JWT 列出來有這些演算法

    HS256, HS384, HS512

    PS256, PS384, PS512

    RS256, RS384, RS512

    ES256, ES256K, ES384, ES512

    EdDSA

以 base64 編碼後得到

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload

除了一些標準定義的欄位外,也可以放自訂的欄位

{"sub":"1234567890","name":"John Doe","iat":1516239022}
  • iss

    issuer

    核發此 JWT 的單位

  • sub

    subject

    此 JWT 使用的目標對象

  • aud

    audience

    誰會使用這個 JWT

  • exp

    expiration

    JWT 逾時時間,定義為 UNIX timestamp 數字

  • nbf

    Not Before

    JWT 啟用時間,定義為 UNIX timestamp 數字

  • jat

    Issued At

    核發此 JWT 的時間 timestamp

  • jti

    JWT ID

    unique identifier for the JWT

用 base64 編碼

eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

Signature

把前兩個部分合併在一起

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

然後用 HS256 簽章

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  "your-secret" 
)

再把三個部分合併成 JWT

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SARsBE5x_ua2ye823r2zKpQNaew3Daq8riKz5A4h3o4

HS256 裡面的密碼,是存放在 server,故可讓 server 驗證此 JWT 是否正確,沒有被竄改。

傳送/存放 JWT

Cookie

可直接透過 Cookie 方式,傳給 client。但設定時,必須加上 HttpOnly,防止 Cookie 被 javascript 讀取,避免遇到 XSS 攻擊

Set-Cookie: jwt=xxx; HttpOnly; max-age=....

接下來每次 request 都會夾帶 jwt cookie 到 server 進行驗證

Sesssion

存放在 Server 的 Session Store 裡面。

JWT 的規格,就是為了把 access token 發送給 client 存放,並在後續的溝通中,使用 JWT 進行身份驗證。透過 JWT,也可以實現 stateless 的 Server。

References

JSON Web Token (JWT) draft-ietf-oauth-json-web-token-32

JSON Web Token - 在Web应用间安全地传递信息

以 JSON Web Token 替代傳統 Token

八幅漫画理解使用JSON Web Token设计单点登录系统

2015/07/13

Scalable Web Architecture

在網頁服務的運算環境中,通常得面對 scalable 的問題,其實在 J2EE 的標準裡,一開始就已經考慮到這個問題,架構上都是切割為三層:Web Layer,Application Layer(Business Logic) 跟 Backend Service Layer(DB 或其他系統)。然而複雜的 EJB container 與通訊問題,造成了這個技術式微,所有人的目光都轉向 light-weight,但在輕量化之後,我們還是得面對大量使用者同時使用的服務架構,技術人員總是得一直追求著,以越少的系統資源提供越多的使用者使用的技術架構。

Concurrent Programming for Scalable Web Architectures 是作者 Benjamin Erb 的畢業研究報告,目標是要找到一個適當的 concurrency model 能用在 multi-core processor,分散式 backend 環境,且能支援新的 web 技術。

在前言中,作者提到網頁將會取代更多桌面的應用程式。接下來十年內,將會專注在 multi-core 與 multiprocessor 的運算環境,而不會增加 CPU 的工作時脈。我們需要選擇適當的程式語言,並搭配合適的 framework,用以設計能夠支援更大規模的 concurrent user 的系統。

討論concurrency有三項重點,接下來的文章內容,會以這三個部份,討論增加系統使用者的策略。

  1. connection handling
    chap4:web server architectures for high concurrency
  2. application logic
    chap5:concurrency concepts for applications and business logic
  3. backend persistence
    chap6: concurrent and scalable storage backends

concurrency 與 scalability

Concurrency 就是系統可同時執行多個活動的一種特性。每個活動都是獨立的,可以發生在不同的運算環境中,例如 single-core processors, multi-core processors, multi-processors 或是分散式系統的多台機器。為保證系統的 consistency,必須有 coordination 與 synchronization 的機制。

有三個方法可改善 concurrency 的效能:

  1. reduce latency
    將工作切割可同時執行的子任務
  2. hide latency
    因為等待 network 或 disk IO 會造成延遲,可同時執行多個外部系統的工作。
  3. increase throughput
    藉由同時執行多個 task 可增加系統 throughput,也可增加 sequential task 的執行速度。

Concurrency vs. Parallelism

簡單地說,paralleism 是由硬體架構支援的平行處理,這是執行的狀態,可用 multi-core 或是 multiprocessor 實現,而 concurrency 是程式語言支援的模式。single core 的機器也可以支援 concurrency 但不能支援真正的 paralleism。

Models for Programming Concurrency

有四種 programming concurrency

  1. sequential
    沒有 concurrency
  2. declarative
    implicit control flow of computation
  3. message-passing
    activities 透過傳遞 message 互動,訊息傳遞有 synchonous 與 asynchronous 兩種。
  4. shared-state
    可競爭存取資源與狀態

Horizontal and Vertical Scalability

通常是採用 horizontal scalability,就是用很多低成本的機器進行水平擴充。然而採用 vertical scalability 的考量點,就是使用更好的機器,更快的 CPU,在於成本效益、或是專用的硬體,application 也不需要特別進行客製化。

scalability requirements

  1. high availability
    通常用 percentiles of uptime 來計量
  2. reliability
    以 meantime between failures 計算
  3. performance
    short response times (low latencies)

Scalable Web Architecture

tiers architecture

通常 web architecture 可分為三個不同的 tiers

  1. presentation tier
    html user interface
  2. application logic tier
    business logic
  3. persistence tier
    database

load balancing strategies

  1. round robin
  2. least connections
    以連線數量決定
  3. least response time
    以最小的 response time 決定
  4. randomized
  5. resource-aware
    搭配 connection 數量與 response time 計算出適當的 loading 分配比率

sticky session

雖然 http 是 stateless,但 web application 常常需要讓 user 在同一個 session 中,存取同一個 web server,這時候可透過 cookie 來決定分配的機器。

在 scalable web architecture 中,我們不應該試著將 user 導向到同一台機器,而是要找到一個方法,讓後端的多個機器,可以同時取得使用者的 session data。

Web Server Architecture for High Concurrency

目標是更多的 concurrent http requests,server 的 performance 可用以下的 metrics

  1. request throughput (#/sec)
  2. raw data throughput (Mbps)
  3. response time (ms)
  4. number of concurrent connections (#)

在機器上可取得的 metrics

  1. CPU utilication
  2. memory usage
  3. number of open socket/file handles
  4. number of threads/processes

C10K

理論上, 500 MHz, 1 GB of RAM, 6 x 100Mbit/s 的硬體,同時有 10000 個客戶連線完全是可行的,目前已經有公司提出 C500K 的 concurrent model。

I/O Operation Models

  • blocking vs. non-blocking
    application 可告訴 OS 該如何存取 device。
    blocking mode 的 IO operation 會一直等待,等到該 operation 完成才會 return。non-blocking mode 中,所有 operation 都會立刻 return,並提供 call status 或是 error。

  • synchronous vs. asynchronous
    說明在 IO Operation 過程中的 control flow,synchronous call 會一直等待 operation 的結果,而 asynchronous call 會立刻 return,然後可繼續執行其他 operations。

Server Architecture

  • Thread-based
  1. multi-process architecture
    傳統的 unix-based network server 就是每一個 connection 產生一個 process

  2. multi-threaded architecture
    在一個 process 裡面,多個 thread 共用相同的 memory,共用 global variables 與 state,建立 thread 比建立 process 消耗的系統資源少。

    系統可用一個 thread 接受 request,然後 dipatch 到 worker thread pool 中,取得一個有空閒的 worker thread 處理該 request。

  • Event-driven
    利用一個 thread 執行 event loop,每一次處理一個從 event queue 取得的 event。

對於大規模的 concurrent connection,目前比較流行的作法是使用 asynchronous/non-blocking I/O operations 的 event-driven server architectures。

Concurrency Concepts for Applications and Business Logic

將 application logic 區分為兩種類型

  1. CPU-bound activities
    需要 CPU 在記憶體進行大量的計算,通常在 web application 中,input validation, template rendering, on-the-fly encoding/decoding 就屬於這類型的 task

  2. I/O-bound activities
    受 network or file I/O 限制的 activities,包含了 storage backend, background services, external services

concurrency based on thread, locks, and shared state

thred 控制了 application flow,當兩個以上的 thread 同時 access ctritical 資料時,需要一個locking mechanism,來控制 threads 之間的狀態變化。

Java 語言就是使用這種機制

concurrency via software transactional memory (STM)

由 programming language 直接提供 locking 與 shared state 機制。

Clojure 使用這個機制

Actor-based Concurrency

利用 actors 進行 concurrent processing,actor 可透過以下方式取得需要進行處理的 message

  1. Send a finite number of messages to other actors.
  2. Spawn a finite number of new actors.
  3. Change its own internal behavior, taking effect when the next incoming message is handled.

scala 使用這個機制,actor 的實作有兩種方式

  • Thread-based Actors
    使用 receive

  • Event-driven Actors
    使用 react

Event-driven Concurrency

node.js 使用這個機制

Concurrent and Scalable Storage Backends

CAP Theorem

一個分散式系統不可能同時滿足以下三點,最多只能滿足其中兩項,例如 CA: high-availability consistency, CP: enforced consistency, AP: eventual consistency

  • consistency 一致性
  • availability 可用性
  • partition tolerance 容忍網絡分區

Consistency Models

  • ACID: 具有 transaction 的行為
    atomicity: 交易細項,是全有或是全無
    consistency: 執行交易時,保證從一個狀態過渡到另一個狀態
    isolation: 保證 transaction 不受其他交易影響
    durability: 一旦 transaction 成立,交易的結果一定會保存,即使系統 crash 也是一樣

  • BASE: 簡單而快速,盡力而為
    basically available
    soft state: 客戶端要接受,某些狀況下會失效
    eventually consistent: 盡可能地提供一致性

Replication strategies

  • Master-Slave
    單一 Master node 提供寫入,多個nodes 以 load balancer 提供讀取的功能

  • Multi-Master
    允許多個 node 同時讀寫

Distributed DB System 的類型

  • Relational DBMS

  • Non-Relational DBMS

  1. Key/Value Stores
    ex: Dynamo from Amazon, Redis
  2. Document Stores
    ex: CouchDB
  3. Wide Column Stores
    ex: BigTable, Cassandra
  4. Graph Database
    ex: neo4j