<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chia Yu Pai on Medium]]></title>
        <description><![CDATA[Stories by Chia Yu Pai on Medium]]></description>
        <link>https://medium.com/@chiayupai?source=rss-a6549dbaae8b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xPMHvyYkrBikkEjg.jpg</url>
            <title>Stories by Chia Yu Pai on Medium</title>
            <link>https://medium.com/@chiayupai?source=rss-a6549dbaae8b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:26:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiayupai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[在 NestJS 中使用 TypeOrm 的一些注意事項，以及 Nx Monorepo 中的 Best Practice]]></title>
            <link>https://chiayupai.medium.com/%E5%9C%A8-nestjs-%E4%B8%AD%E4%BD%BF%E7%94%A8-typeorm-%E7%9A%84%E4%B8%80%E4%BA%9B%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A0%85-%E4%BB%A5%E5%8F%8A-nx-monorepo-%E4%B8%AD%E7%9A%84-best-practice-9e846238bc3b?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e846238bc3b</guid>
            <category><![CDATA[nx]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 08:00:23 GMT</pubDate>
            <atom:updated>2023-07-02T08:00:23.085Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7SdKRO8uMvMC2A-rIxBmg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/ja/@jankolar?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jan Antonin Kolar</a></figcaption></figure><p>TypeORM 和 NestJS 目前已經是我的後端主要開發工具，除此之外因為我們會使用 Nx Monorepo 的方式來管理服務，並盡力做到 DDD 的架構讓關注點分離。在經過多專案的嘗試，想來分享一下目前找到最適合的整合方法。</p><p>首先，有幾個令人困擾的限制要解決</p><ol><li>因為我們使用 ESModule 作為 TypeScript 打包的目標，在使用 TypeORM 引用 Entites 時會有 Circular Dependencies 的問題。</li><li>目前 TypeORM 的 Entity 不能動態指定 Schema，因此需要確認部署環境的 Schema 是不是可控，並且可以 hard-coded。</li><li>新的 DataSource 機制，引入 Repository 沒辦法再像過去直接使用 InjectRepository 來解決。</li><li>另外一個很容易忽略的 ManyToMany 絕對不能兩邊都寫 JoinTable 這會導致 Join Table 的時候一直找到錯誤的 Foreign Key。</li></ol><p>第一題，我們採用 string table name 的形式來解決</p><pre>// libs/models/src/product.entity.ts<br>import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, ManyToMany } from &#39;typeorm&#39;;<br>import type { CategoryEntity } from &#39;./category.entity&#39;;<br>import type { TagEntity } from &#39;./tag.entity&#39;;<br><br>export const ProductRepo = Symbol(&#39;ProductRepo&#39;);<br><br>@Entity(&#39;products&#39;)<br>export class ProductEntity {<br>  @PrimaryGeneratedColumn(&#39;uuid&#39;)<br>  id: string;<br><br>  @Column()<br>  name: string;<br><br>  @ManyToOne(&#39;categories&#39;, (category: CategoryEntity) =&gt; category.products)<br>  @JoinColumn({<br>    name: &#39;categoryId&#39;,<br>    referencedColumnName: &#39;id&#39;,<br>  })<br>  category: CategoryEntity;<br><br>  @ManyToMany(&#39;tags&#39;, (tag: TagEntity) =&gt; tags.products)<br>  tags: TagEntity[];<br>}<br><br>// libs/models/src/category.entity.ts<br>import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from &#39;typeorm&#39;;<br>import type { ProductEntity } from &#39;./product.entity&#39;;<br><br>export const CategoryRepo = Symbol(&#39;CategoryRepo&#39;);<br><br>@Entity(&#39;categories&#39;)<br>export class CategoryEntity {<br>  @PrimaryGeneratedColumn(&#39;uuid&#39;)<br>  id: string;<br><br>  @Column()<br>  name: string;<br><br>  @OneToMany(&#39;products&#39;, (product: ProductEntity) =&gt; product.category)<br>  products: ProductEntity[];<br>}<br><br>// libs/models/src/tag.entity.ts<br>import { Entity, PrimaryColumn, Column, ManyToMany, JoinTable } from &#39;typeorm&#39;;<br>import type { ProductEntity } from &#39;./product.entity&#39;;<br><br>export const TagRepo = Symbol(&#39;TagRepo&#39;);<br><br>@Entity(&#39;tags&#39;)<br>export class TagEntity {<br>  @PrimaryColumn()<br>  tag: string;<br><br>  @ManyToMany(&#39;products&#39;, (product: ProductEntity) =&gt; product.tags)<br>  @JoinTable({<br>    name: &#39;product_tags&#39;,<br>    joinColumn: {<br>      name: &#39;tag&#39;,<br>      referencedColumnName: &#39;tag&#39;,<br>    },<br>    inverseJoinColumn: {<br>      name: &#39;productId&#39;,<br>      referencedColumnName: &#39;id&#39;,<br>    },<br>  })<br>  products: ProductEntity[];<br>}</pre><p>透過 table name 來直接 reference entities 避免直接 import 即可閃過 Circular dependencies 的問題，而 import type 的方式因為 typescript 並不會在 runtime 時執行，實際上編譯後就不存在了，所以不會有 dependency 的問題需要處理。</p><p>多對多的部分 JoinTable 我只在其中一邊的 Entity 寫，目前 typeorm 如果兩邊都寫，就算 joinColumn/inverseJoinColumn 有正確的反過來，一樣會造成使用 relations/innerJoin 的時候找錯名稱，這應該是 typeorm 原始碼的設計缺陷，可能等之後有空去發 PR 看能不能徹底解決這件事了。</p><p>除此之外，我在每個 Entity 都會另外 Export 一個 Symbol 作為 NestJS 的標記之用，為了解決 DataSource 引用的問題，我目前將 Model Module 改寫成這樣</p><pre>// libs/models/src/models.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { DataSource } from &#39;typeorm&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { ProductRepo, ProductEntity } from &#39;./product.entity&#39;;<br>import { TagRepo, TagEntity } from &#39;./tag.entity&#39;;<br>import { CategoryRepo, CategoryEntity } from &#39;./category.entity&#39;;<br><br>const models = [<br>  [ProductRepo, ProductEntity],<br>  [TagRepo, TagEntity],<br>  [CategoryRepo, CategoryEntity],<br>] as [symbol, typeof ProductEntity][];<br><br>@Module({<br>  imports: [TypeOrmModule.forFeature(models.map((model) =&gt; model[1]))],<br>  providers: models.map(([symbol, entity]) =&gt; ({<br>    provide: symbol,<br>    useFactory: (dataSource: DataSource) =&gt; dataSource.getRepository(entity),<br>    inject: [DataSource],<br>  })),<br>  exports: models.map((model) =&gt; model[0]),<br>})<br>export class ModelsModule {}<br><br>// libs/models/src/index.ts<br><br>export * from &#39;./models.module&#39;;<br>export * from &#39;./product.entity&#39;;<br>export * from &#39;./tag.entity&#39;;<br>export * from &#39;./category.entity&#39;;</pre><p>這邊我們使用 Factory 模式把所有 Entity 都注入這個 ModelsModule 中，並且讓他可以被其他模組引用，實際上引用的情況是這樣</p><p>另外，為了 nx monorepo 機制，我們把所有需要可以外部存取的模組透過 lib/models/index.js 這個單一對外出口導出</p><pre>// libs/products/src/products.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ModelsModule } from &#39;@sample/models&#39;; // annotation: libs/models/models.module.ts<br>import { ProductsService } from &#39;./products.service&#39;;<br>import { ProductsController } from &#39;./products.controller&#39;;<br><br>@Module({<br>  imports: [ModelsModule],<br>  providers: [ProductService],<br>  controllers: [ProductController],<br>})<br>export class ProductsModule {}<br><br>// libs/products/src/products.service.ts<br><br>import { Injectable, Inject } from &#39;@nestjs/common&#39;;<br>import { Repository } from &#39;typeorm&#39;;<br>import { ProductRepo, ProductEntity } from &#39;@sample/models&#39;; // annotation: export from libs/models/index.ts<br><br>@Injectable()<br>export class ProductsService {<br>  constructor(<br>    @Inject(ProductRepo)<br>    private readonly productRepo: Repository&lt;ProductEntity&gt;,<br>  ) {}<br><br>  getProducts(): Promise&lt;ProductEntity[]&gt; {<br>    const qb = this.productRepo.createQueryBuilder(&#39;products&#39;);<br><br>    qb.innerJoinAndSelect(&#39;products.category&#39;, &#39;category&#39;);<br>    qb.leftJoinAndSelect(&#39;products.tags&#39;, &#39;tags&#39;);<br><br>    return qb.getMany();<br>  }<br>}<br><br>// libs/products/src/products.controller.ts<br><br>import { Controller, Get, Post } from &#39;@nestjs/common&#39;;<br>import type { ProductEntity } from &#39;@sample/models&#39;;<br>import type { ProductsService } from &#39;./products.service&#39;;<br><br>@Controller(&#39;/products&#39;)<br>export class ProductsController {<br>  constructor(private readonly productsService: ProductsService) {}<br><br>  @Get(&#39;/&#39;)<br>  getProducts(): Promise&lt;ProductEntity[]&gt; {<br>    return this.productsService.getProducts();<br>  }<br><br>  @Post(&#39;/)<br>  createProduct() {<br>    // implement create<br>  }<br>}</pre><p>如同上面的案例，有需要存取資料庫的 module 只需要引用 ModelModules 就可以透過 Inject 該 Entity 的 Symbol 即可獲得 DataSource 綁定的 Repository，比較複雜點的情境還可以用 alias 來區分多個 DataSource，並在 Factory Initialize 的時候去插入不同的環境。</p><p>上面的範例中還有一件事希望大家多推廣的，TypeScript 並不會強迫定義每個 method/function 的 response type，但我習慣都會全部定義清楚，這樣只要任何一層有改變，才能獲得 typescript check 的好處，否則都會被視為 any 沒有錯誤。</p><p>而依據關注點分離的概念，我們目前的主要開發商業邏輯都會放在 libs 中作為 domain scoped packages 而 nx applications 主要作為定義 endpoints feature 之用，也就是他只會負責做全局的 initialize，像是 TypeORM/GraphQL/Config 等工作，餘下的便是去引用需要的模組，各模組依據其引用點來提供模組下的差異服務。</p><p>例如上面的 ProductsModule 可以提供完全服務，但如果我只需要提供一個只能取不能修改的模組，我便會把 Controller 拆成 ProductsReadController/ProductManageController，並且建立一個只讀的 ProductsReadOnlyModule 來讓該 Endpoint 引用，原本的模組 ProductsModule 同時引用兩個，會依據 NestJS 的機制自動合併</p><pre>// ModelsModule -&gt; ProductsService -&gt; ProductsReadOnlyController -&gt; ProductsReadOnlyModule -&gt; ReadOnlyApplication<br>//                                                               -&gt; ProductsModule<br>//                                 -&gt; ProductsManageController   -&gt; ProductsModule         -&gt; FullFeaturedApplication<br><br>// libs/products/src/read-only.products.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ProductsService } from &#39;./products.service&#39;;<br>import { ProductsReadOnlyController } from &#39;./products-read-only.controller&#39;;<br><br>@Module({<br>  imports: [ModelsModule],<br>  providers: [ProductService],<br>  controllers: [ProductReadOnlyController],<br>})<br>export class ProductsReadOnlyModule {}<br><br>// libs/products/src/products.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { ProductsService } from &#39;./products.service&#39;;<br>import { ProductsReadOnlyController } from &#39;./products-read-only.controller&#39;;<br>import { ProductsManageController } from &#39;./products-manage.controller&#39;;<br><br>@Module({<br>  imports: [ModelsModule],<br>  providers: [ProductService],<br>  controllers: [ProductsManageController, ProductReadOnlyController],<br>})<br>export class ProductsModule {}<br><br>// libs/products/src/products-read-only.controller.ts<br><br>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import type { ProductEntity } from &#39;@sample/models&#39;;<br>import type { ProductsService } from &#39;./products.service&#39;;<br><br>@Controller(&#39;/products&#39;)<br>export class ProductsReadOnlyController {<br>  constructor(private readonly productsService: ProductsService) {}<br><br>  @Get(&#39;/&#39;)<br>  getProducts(): Promise&lt;ProductEntity[]&gt; {<br>    return this.productsService.getProducts();<br>  }<br>}<br><br>// libs/products/src/products-manage.controller.ts<br><br>import { Controller, Get } from &#39;@nestjs/common&#39;;<br>import type { ProductEntity } from &#39;@sample/models&#39;;<br>import type { ProductsService } from &#39;./products.service&#39;;<br><br>@Controller(&#39;/products&#39;)<br>export class ProductsManageController {<br>  constructor(private readonly productsService: ProductsService) {}<br><br>  @Post(&#39;/)<br>  createProduct() {<br>    // implement create<br>  }<br>}</pre><p>如此便能輕易的以模組來進行工作的分工，並根據部署需求來建立功能相異的進入點。</p><p>最後來看一下 Nx Applications 的實作方式</p><pre>// apps/api/src/app/app.module.ts<br><br>import { Module } from &#39;@nestjs/common&#39;;<br>import { TypeOrmModule } from &#39;@nestjs/typeorm&#39;;<br>import { VaultModule, VaultService } from &#39;@rytass/secret-adapter-vault-nestjs&#39;;<br>import { ProductsReadOnlyModule } from &#39;@sample/products&#39;;<br><br>@Module({<br>  imports: [<br>    VaultModule.forRoot({ path: process.env.VAULT_PATH || &#39;sample-application&#39; }),<br>    TypeOrmModule.forRootAsync({<br>      inject: [VaultService],<br>      useFactory: async (vault: VaultService) =&gt; ({<br>        type: &#39;postgres&#39;,<br>        port: 5432,<br>        host: await vault.get&lt;string&gt;(&#39;DB_HOST&#39;),<br>        database: await vault.get&lt;string&gt;(&#39;DB_NAME&#39;),<br>        username: await vault.get&lt;string&gt;(&#39;DB_USER&#39;),<br>        password: await vault.get&lt;string&gt;(&#39;DB_PASS&#39;),<br>        schema: await vault.get&lt;string&gt;(&#39;DB_SCHEMA&#39;),<br>        synchronize: (await vault.get&lt;string&gt;(&#39;NODE_ENV&#39;)) !== &#39;production&#39;,<br>        autoLoadEntities: true,<br>        migrationsRun: true,<br>        migrations: [resolve(process.cwd(), &#39;migrations&#39;)],<br>        migrationsTableName: &#39;migrations&#39;,<br>        migrationsTransactionMode: &#39;each&#39;,<br>        uuidExtension: &#39;uuid-ossp&#39;,<br>        installExtensions: true,<br>        logger: &#39;advanced-console&#39;,<br>        logging:<br>          (await vault.get&lt;string&gt;(&#39;NODE_ENV&#39;)) === &#39;production&#39; ? [&#39;schema&#39;, &#39;error&#39;, &#39;warn&#39;, &#39;migration&#39;] : &#39;all&#39;,<br>      }),<br>    }),<br>    ProductsReadOnlyModule,<br>  ],<br>})<br>export class AppModule {}<br></pre><p>整個 AppModule 中只需要決定他需要載入什麼樣的模組，並且完成 TypeOrmModule 的 initialize 即可，這邊的連線字串我們使用 Vault 來管理，也可以依據自己的需要採用 ConfigModule (.env) 的方式來注入。</p><p>最後，還有一件事要解決，如果我們需要動態指定 schema，如上方透過 vault 的方式注入時，目前 TypeORM ViewEntity 使用 Expression 自動 Sync 建立時沒辦法吃到 initialize 提供的 schema 值。所以目前我們的解法是仰賴 Postgres default <a href="https://www.postgresql.org/docs/current/ddl-schemas.html#DDL-SCHEMAS-PATH">search_path</a> 會先找當下登入的 user 名稱的特點，讓部署的<strong>資料庫帳號跟 schema 名稱一樣</strong>，這樣他在建立的 view 的時候就會自己找到正確的表格。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e846238bc3b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service adapters 把第三方服務 API 標準化，應對善變多樣的業主]]></title>
            <link>https://chiayupai.medium.com/service-adapters-%E6%8A%8A%E7%AC%AC%E4%B8%89%E6%96%B9%E6%9C%8D%E5%8B%99-api-%E6%A8%99%E6%BA%96%E5%8C%96-%E6%87%89%E5%B0%8D%E5%96%84%E8%AE%8A%E5%A4%9A%E6%A8%A3%E7%9A%84%E6%A5%AD%E4%B8%BB-6b14d5e9ab14?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b14d5e9ab14</guid>
            <category><![CDATA[api-utils]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[service-adapters]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[payments]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 06:51:33 GMT</pubDate>
            <atom:updated>2023-07-02T06:52:02.785Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9t-awWukNn-QYNggHDz1tg.jpeg" /></figure><p>作為客製化軟體開發團隊，我們必須因應業主的各種商業/策略需求來介接不同的服務提供商，現時因為使用情境的固定，提供 SaaS 服務的類型常見有下列幾種：</p><ul><li>金流服務 — 算是最常見的服務供應商，除了紅藍綠三大傳統支付商外，各間銀行也都有提供自身的金流串接服務，近年又加入 LinePay 等社群導向的支付平台。各間實作上大同小異，但把每間服務商的文件都看完弄清楚其中細微差異著實會浪費開發者不少時間，尤其超級難以理解的 URL Params Hash Check 指定排序這件事更是眾多開發者們卡關熱點。</li><li>發票服務 — 目前政府的發票電子化推行成功，所有有提供線上金流的服務基本上都會另外串接發票開立服務，很多人不知道的是金流與發票是分開的，收錢並沒有一定要開發票，根據業務類型與規模才是要不要開發票的標準。另外，二聯與三聯式發票跟有沒有統編沒有關係，也是很多非財會背景的開發者們很容易搞不清楚的地方。</li><li>雲代管服務 — Infrastructure 的部分就交給 <a href="https://www.terraform.io/">TerraForm</a>，但部署之外，我們很常會遇到我們開發使用 GCP 但正式環境須改用 AWS 這樣的情境，VM 的部分因為 Containerize 的關係沒有影響，但使用的 File Storage Service 要重新介接是個麻煩的大問題。</li></ul><p>除了上述三個比較大宗的問題外，物流、設定檔代管等等也會是我們眾多專案會遇到的實踐需求。為了這些問題，團隊決定將所有的外部 API 介接以服務為單位，盡量的去統一化 API 介面，並以 Adapter 的形式發佈到 npm。當今天業主改變不同的服務供應商選項時，我們只需要改安裝另一個 node module 即可以直接完成調整，不需要再去檢查所有跟應用介接的地方。</p><p>這些 Adapters 目前也已公開源碼的方式開放給大眾使用</p><p><a href="https://github.com/rytass/utils">GitHub - Rytass/Utils</a></p><p>目前已經完成的項目如下：</p><ul><li>File Converter (Resize/Transcode/Watermark) — 提供 pipeline 的影像處理工具</li><li>Invoice (ECPay/EZPay) — 發票開立/查詢服務</li><li>Logistics (TCat) — 物流狀態查詢</li><li>Order Builder — 電商訂單建立，可以設定複雜的折扣規則、Coupon 應用條件等，根據條件建立實體後，把商品丟進去即可自動計算可以套用的折扣金額，電商最痛苦的部分抽象神器</li><li>Payments — 金流介接/訂單狀態</li><li>Quadrats — 內容管理服務的 API NestJS Module</li><li>Secret (Vault) — 環境變數管理工具</li><li>SMS (Every8d) — 簡訊發送服務</li><li>Storages (AzureBlob/GCS/R2/S3/Local) — 檔案管理服務</li></ul><p>我們會持續更新這些套件以因應開發需求，也歡迎任何有用到的開發者提供 PRs/Issue Reports。後續我也會再把每個套件的實作寫文章介紹，這篇就先作為 Index 留存更新。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b14d5e9ab14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeORM orderBy NULLS LAST w/ MySQL]]></title>
            <link>https://chiayupai.medium.com/typeorm-orderby-nulls-last-w-mysql-4e35af85fe2?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e35af85fe2</guid>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[nulls-first]]></category>
            <category><![CDATA[orderby]]></category>
            <category><![CDATA[nulls-last]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Mon, 07 Mar 2022 09:10:10 GMT</pubDate>
            <atom:updated>2022-03-07T09:10:10.729Z</atom:updated>
            <content:encoded><![CDATA[<p>Because MySQL doesn’t support nulls last/first, you can use built-in function on orderBy statement to implement it.</p><pre>const response = SomeRepository<br>  .createQueryBuilder(&#39;records&#39;)<br>  .orderBy(&#39;IF(records.sortIndex IS NULL, 99999999999, records.sortIndex)&#39;, &#39;ASC&#39;)<br>  .getMany();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e35af85fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloudera docker exited code 139]]></title>
            <link>https://insights.rytass.com/cloudera-docker-exited-code-139-2433f1cc0af0?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2433f1cc0af0</guid>
            <category><![CDATA[exited-code-139]]></category>
            <category><![CDATA[cloudera]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[debian-11]]></category>
            <category><![CDATA[vsyscall]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Wed, 02 Mar 2022 16:16:00 GMT</pubDate>
            <atom:updated>2022-03-02T16:16:17.656Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Because cloudera official docker image updated 6 years ago, its latest version 5.7.0.0-beta need linux kernel before 4.4 system call named “vsyscall”. If your linux kernel is newer then 4.4 (like debian 11), vsyscall isn’t enable by default.</p><p>You can check this system call status by following command:</p><pre>cat /proc/self/maps | grep &#39;vsyscall&#39;</pre><p>If no response, you can update your grub to enable it. Please update <strong>/etc/default/grub</strong> and add args:</p><pre>GRUB_CMDLINE_LINUX_DEFAULT=&quot;vsyscall=emulate&quot;</pre><p>After configuration updated, remember to reload grub and reboot your system:</p><pre>sudo update-grub<br>sudo reboot</pre><p>Rebooted, you can grep <strong>/proc/self/maps </strong>again, if enable successfully, you will see the memory address like:</p><pre>ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]</pre><p>Then, try again to docker run image 😇</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2433f1cc0af0" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/cloudera-docker-exited-code-139-2433f1cc0af0">Cloudera docker exited code 139</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 React 中動態引入第三方 JS Library]]></title>
            <link>https://insights.rytass.com/%E5%9C%A8-react-%E4%B8%AD%E5%8B%95%E6%85%8B%E5%BC%95%E5%85%A5%E7%AC%AC%E4%B8%89%E6%96%B9-js-library-707b0415b815?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/707b0415b815</guid>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[youtube-iframe-api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dynamic-import]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Fri, 13 Aug 2021 10:41:35 GMT</pubDate>
            <atom:updated>2021-08-13T10:41:35.220Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vzy8WixmKeGmMJMl" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>在寫 React App 時，我們大部分使用到的第三方套件會透過 npm 的套件管理庫來進行安裝，並透過 webpack/rollup 等工具進行打包，使用上很少關注其引用的問題（Split Chunk 我們之後談）。但許多第三方套件的引入方式因其發布者需求，並無法透過 npm 進行安裝，舉凡 YouTube Player API/Facebook Embed API/Twitter API 等這類以嵌入為主要功能的套件，因其主要目標對象不一定是 JavaScript 開發者，涵蓋大量的 HTML Editor 使用者；故他們會將引入的程式碼以 &lt;script&gt; 的方式進行釋出。</p><p>這樣的釋出方式對於 React 的 lifecycle 來說滿難掌控的，一來是因為通常我們不會在 JSX 中直接寫 script tag 來引用程式碼，二來是這類套件大多數需要處理其 onload 事件來進行其他操作，直接引入 script tag 的方式並沒有辦法將 onload 事件與 React lifecycle 進行結合，也就是說他們會脫離 React 的 render tick 之中。</p><p>這裡我們就以 YouTube Player API 為例，在 React 以 custom hook 的方式做到隨需引入，並綁定 onload 事件</p><pre>// useYouTubePlayerLoad.ts</pre><pre>let isLoading = false;<br>let isLoaded = false;<br>let onloadTasks = [];</pre><pre>function loadYouTubePlayerAPI() {<br>  const tag = document.createElement(&#39;script&#39;);<br>  <br>  tag.src = &#39;https://www.youtube.com/iframe_api&#39;;</pre><pre>  window.onYouTubeIframeAPIReady = () =&gt; {<br>    isLoading = false;<br>    isLoaded = true;<br>    <br>    onloadTasks.forEach((task) =&gt; {<br>      task();<br>    });<br>  };</pre><pre>  isLoading = true;</pre><pre>  document.body.appendChild(tag);<br>}</pre><pre>export default function useYouTubePlayerLoad() {<br>  ... execute on render<br>}</pre><p>首先我們先針對狀態定義 isLoading/isLoaded 兩個 boolean 去表示全域而言 YouTube API 的讀取狀態，並訂一個 task array 去進行 onload callbacks 的暫存工作。因為這些東西整個網站載入後僅需要一份，也就是在 singleton 之中，所以不需要也不可以將他們定義在 hook 的函式中哦！再來我們需要實作 hook 在每次被 React Component 引入時的工作：</p><pre>// useYouTubePlayerLoad.ts<br>import { useEffect } from &#39;react&#39;;</pre><pre>// ...上略</pre><pre>export default function useYouTubePlayerLoad(callback: () =&gt; void) {<br>  useEffect(() =&gt; {<br>    if (isLoaded) {<br>      callback();<br>    <br>      return;<br>    }</pre><pre>    onloadTasks.push(callback);</pre><pre>    if (!isLoading) {<br>      loadYouTubePlayerAPI();<br>    }</pre><pre>    return () =&gt; {<br>      const taskIndex = onloadTasks.findIndex(task =&gt; task === callback);</pre><pre>      if (~taskIndex) {<br>        onloadTasks = [<br>          ...onloadTasks.slice(0, taskIndex),<br>          ...onloadTasks.slice(taskIndex + 1),<br>        ];<br>      }  <br>    };<br>  }, [callback]);<br>}</pre><p>基本上這邊的實作很簡單，就是吃一個 callback 函式，然後判斷 hook 被 render 時，是否已經載入完成，如已經載入完成就直接立刻執行 callback；未載入完成時將 callback 推入 onloadTasks 中，並判斷是否曾經有其他 hook 去執行過 script load 的動作，如果沒有就自己執行。</p><p>當然不能忘記當這個 callback 改變或是還未載入完就被 unmount 的時候，要把自己的痕跡清除掉，避免 ghost callback 的出現。</p><p>上面已經完成載入 API 的工作，大部分這類型的 API 都是使用這樣的方式進行載入即可完美的與 React lifecycle 結合。但實際使用上我們通常會希望更高階的 API 提供給前端使用，所以可以再進行下面的嵌套包裝：</p><pre>// useYouTubePlayer.ts</pre><pre>import { useRef, useState, useCallback } from &#39;react&#39;;<br>import useYouTubePlayerLoad from &#39;./useYouTubePlayerLoad&#39;;</pre><pre>export default useYouTubePlayer(videoId: string) {<br>  const [player, setPlayer] = useState(null);<br>  const containerRef = useRef&lt;HTMLDivElement&gt;(null);</pre><pre>  const onAPILoad = useCallback(() =&gt; {<br>    if (!containerRef.current) return;</pre><pre>    const ytPlayer = new YT.Player(containerRef.current, {<br>      videoId,<br>    });</pre><pre>    setPlayer(ytPlayer);<br>  }, [videoId]);</pre><pre>  useYouTubePlayerLoad(onAPILoad);</pre><pre>  return [containerRef, player];<br>}</pre><p>上面針對常用的情境：「將某個 YouTube Video ID 放置到固定元素上」做成一個 custom hook 並提供 player 的 API 給使用的 component，實際上使用就可以像是下例：</p><pre>// SomeComponent.ts</pre><pre>import React, { useEffect } from &#39;react&#39;;<br>import useYouTubePlayer from &#39;./useYouTubePlayer&#39;;</pre><pre>function SomeComponent() {<br>  const [ref, player] = useYouTubePlayer(&#39;dNH4CihWJhw&#39;);</pre><pre>  useEffect(() =&gt; {<br>    // use player to play/pause...<br>  }, [player]);</pre><pre>  return (  <br>    &lt;div ref={ref} /&gt;<br>  );<br>}</pre><p>可以看到經過這樣的包裝，使用 YouTube Player API 就變得簡單方便，善用 custom hook 多層包裝抽象對於終端使用的工程師真的非常友善啊 🥰</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707b0415b815" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/%E5%9C%A8-react-%E4%B8%AD%E5%8B%95%E6%85%8B%E5%BC%95%E5%85%A5%E7%AC%AC%E4%B8%89%E6%96%B9-js-library-707b0415b815">在 React 中動態引入第三方 JS Library</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fastrack℠ 數位轉型系統資料分析模型介紹]]></title>
            <link>https://insights.rytass.com/fastrack-%E6%95%B8%E4%BD%8D%E8%BD%89%E5%9E%8B%E7%B3%BB%E7%B5%B1%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90%E6%A8%A1%E5%9E%8B%E4%BB%8B%E7%B4%B9-4abb1e0b5d8?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4abb1e0b5d8</guid>
            <category><![CDATA[digital-transformation]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[資料分析模型]]></category>
            <category><![CDATA[數位轉型]]></category>
            <category><![CDATA[fastrack]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 00:03:35 GMT</pubDate>
            <atom:updated>2021-07-22T00:03:35.053Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*dfrSxrJ03HI59EaUPvAMcg.png" /><figcaption>Fastrack℠ Data Analysis Modal</figcaption></figure><p>Fastrack℠ 是 Rytass™ 在經過多年協助各式組織進行數位轉型規劃時，歸納並快速統整組織現有資料與資源的分析架構，整合起資料和商業模式的關係，讓後端開發的工程團隊可以清楚理解組織的商業模型。</p><p>大部分組織開啟數位轉型這樣的翻天覆地舉動時，通常都是由於某個特定系統的使用者，無法接受過時的系統結構或操作行為造成的工作效率低落；或是現行的系統不足以在數位時代下達到獲客與服務的效果。因此，在開始規劃組織數位轉型的專案時，我們通常會瞄定該組織已經運行多年但明確不浮現用需求的系統進行翻修與開發工作；藉由新的使用者流程設計與資料整合讓組織可以接受數位轉型帶來的好處，減少內部政治壓力時常是轉型是否可以成功的最關鍵因素。</p><p>因為需要進行數位轉型的組織通常歷史深遠，內部盤根錯節的商業邏輯是不可能一次進行根本的打掉重練，但數位轉型的終極目的就是資料流的去人為化、商業邏輯的制度化來達到可預測性，並滿足因應未來商業需求的變動，資料可以延續性的使用。</p><p>Fastrack℠ 的核心工作在於，快速透過系統分析工作拆分資料的狀態與階段，也就是找出一份資料、訂單、申請案從建立到封存的過程的切分點，將資料狀態切分為仍會大量變動與修改的 <strong>Processing Data</strong> 以及幾乎不會修改僅做為分析與留底的 <strong>Persistent &amp; Analysis Data</strong>，並透過這樣資料分流的過程中，理解每份資料的 Usage Scope 與組織中各式子系統的資料交換規劃。</p><p>舉個例子來說，對於訂單管理的數位化來說：收到一張訂單，經歷製造排程、檢貨、驗貨、出貨到完成訂單中間的過程都會作為 <strong>Processing Data </strong>的形式被規劃儲存，完成的訂單資料因為僅會於少見的客服需求與總體分析使用，便可歸類到冷資料的 <strong>Persistent &amp; Analysis Data </strong>去儲存。</p><p>很多人看到此，認為行業很固定的流程，應該不需要使用模型進行歸檔啊？但實務上，因為每個不同的組織其商業行為的差異還是存在不小的落差。例如，比較偏向工廠的製造業來說，他們的訂單到出貨後就幾乎不需要做更多的後續處理，因此可以在出貨時就放入冷資料中。但對於現在常見的小型工廠透過網路販售商品或是自有品牌的工廠來說，必須直接面對一線消費者，加上台灣特有的網購 7 天退貨條款，他們需要於出貨後 9–14 天才能將訂單列為冷資料，也就是已出貨後還會再新增一個已無法退貨的狀態來紀錄。</p><p>這樣的資料釐清流程，方便 Rytass™ 後續經驗豐富的工程架構團隊能藉著業務與需求分析師帶回的資料，迅速理解組織實際商業行為，並架構出合理彈性高的系統。此外，在軟體開發的角度來說熱資料的 <strong>Processing Data </strong>需要因應大量日常工作需求而進行變動，且變動時的過程通常會以資料本身（訂單）為單位；因此此類的資料通常採用講求 Transaction Save 的 RDBMS 來進行資料的處理與開發。</p><p>而作為大數據分析專用的資料，為了可以輕鬆地對數以千萬計的紀錄有效率的進行彙總分析計算，我們通常會將封存的 <strong>Persistent &amp; Analysis Data </strong>抄寫至 Elastic Search™ 等可適應大量拓墣維度的資料儲存工具儲存，來應付大量而隨機的分析與查詢需求。</p><p>而系統中主流程的資料外，大部分系統的開發同時會有不適合歸類於主資料的 <strong>Outside Resource </strong>以及因應業主需求順便一起開發的小型系統 (<strong>Edge System</strong>)。例如開發訂單系統時，通常也會為了現場管理的方便，同時開發可以與熱感印表機串接的列印工具；但可預期的是這樣的工具未來並不會單獨屬於訂單系統使用，進貨管理與庫存管理系統開發時也可以共用這樣的工具，那麼我們就會將其列入<strong> Edge System </strong>的規劃之中，並將其產生或需要的部分資料記錄為 <strong>Outside Resource</strong>，主要目的也是讓後端系統設計師快速理解整包專案開發上的 Scope 切分狀態。</p><p>在完成中間的本案內容後，對於所有規劃師與架構師最需要知道但也最常被忽略的就是這個系統的對外關係了。據前述，所有的數位轉型都不可能一次到位的情況，勢必會有大量的中介層去處理跟其他新舊系統間的串接；因此我們會將於本系統流程有關的所有 <strong>Inbound &amp; Outbound System </strong>都列入追蹤並向辦法釐清接口的型態，是否可以使用 HTTP API 進行介接，或是只能透過 CSV/Microsoft Excel™ 等半同步的方式介接，系統連線的權限在業主端的控制權等等狀態。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLGvzrNEP4a8cbbhekeC5Q.jpeg" /><figcaption>角色權限表</figcaption></figure><p>而最最重要的就是 <strong>Handlers </strong>的釐清了，整個系統中所有利害關係人有多少，可以細分為多少的角色 (Roles)，每個角色之下又可以分為多少不同的行為 (Actions)，行為又會受限於什麼樣的條件 (Conditions)。透過這樣 Role-Action-Condition 三層式的權限劃分，未來系統的管理面可以依據組織職權變動而任意重組三層間的對應關係，系統不需要做任何修改即可滿足新的權責架構，來避免每次的組織改造或商業模式轉換就重新開發系統的輪迴。</p><p>透過 Fastrack℠ 完成分析的數位轉型系統，工程團隊就可以迅速地知道整體系統的面貌，降低大量溝通詢問的時間；以資料為主軸的觀點，著重在該組織在數位時代下的資產到底有什麼，而不優先關注這些資料的交織應用方式。當我們確立有多少的基礎資料後，便可依據組織的商業行爲設計出高效率的操作流程，避免由業主自行敘述想要的操作流程，造成最終結果不如預期地提高效率（因為大多數業主並無軟體工程與使用者體驗相關知識，有時候業主想要的特定流程，只是因為他並不知道可以怎麼做，只能就自身經驗做推敲）。</p><p>以資料為基底的討論，也大大提高未來商業行為改變與市場環境變化時，系統對於其應變的能力，工程團隊僅需要依據新的使用行為重新調整接起這些資料的邏輯即可；正因為數位時代下，組織擁有的資產即是資料，使用者行為與資料互動模式只是當下時空背景下，最適合的作法與應用，於底層資料庫儲存時並不該受到使用者行為模式的束縛。</p><p>最後，希望這樣以資料為主體的分析與思維方式能幫助到正在煩惱如何數位轉型的各位囉 😳</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4abb1e0b5d8" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/fastrack-%E6%95%B8%E4%BD%8D%E8%BD%89%E5%9E%8B%E7%B3%BB%E7%B5%B1%E8%B3%87%E6%96%99%E5%88%86%E6%9E%90%E6%A8%A1%E5%9E%8B%E4%BB%8B%E7%B4%B9-4abb1e0b5d8">Fastrack℠ 數位轉型系統資料分析模型介紹</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Surge 讓你的 VPN 服務像是 Unix Pipeline 般的串接]]></title>
            <link>https://insights.rytass.com/surge-%E8%AE%93%E4%BD%A0%E7%9A%84-vpn-%E6%9C%8D%E5%8B%99%E5%83%8F%E6%98%AF-unix-pipeline-%E8%88%AC%E7%9A%84%E4%B8%B2%E6%8E%A5-2be86745230b?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be86745230b</guid>
            <category><![CDATA[mitm]]></category>
            <category><![CDATA[sre]]></category>
            <category><![CDATA[surge]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[macos]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 19:36:00 GMT</pubDate>
            <atom:updated>2021-07-15T19:36:00.011Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qb8s4lAd9mrdDu6G" /><figcaption>Photo by <a href="https://unsplash.com/@jordanharrison?utm_source=medium&amp;utm_medium=referral">Jordan Harrison</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://nssurge.com/">Surge</a> 這個 MacOS/iOS 上非常方便的網路配置工具，對於常常需要各種跳板的 SRE 是節省時間，提高效率的利器。或許是因為台灣網路的自由，Surge 這個關鍵字在 Google 搜尋結果中找了幾頁都找不到正確的官網 🥲</p><p>這次大慨介紹一下他對於開發者或是維運工程師來說好用的點是什麼好了，相信大多數的前、後端工程師都有遇過不管怎麼試，從 Browser Network 看起來沒有任何錯誤的 Request 就是無法正確的送到本機的後端 Server，或是有時候使用第三方 SDK 只聞其表頭不聞其內容，但卻無法正常使用時，各種通靈王大賽開催。</p><p>Surge 提供完整的 System Global Proxy 機制，簡單的建立 Socks5 Proxy 於 Local 並且把系統 Proxy 導過去後，就可以透過其附帶的 Dashboard 抓到所有通過 Proxy 出去的 Request，並透過自簽憑證跑 MITM 的方式解出 HTTPS 的封包內容。對於頑強不聽系統 Proxy 設定的應用程式，Surge 也可以透過虛擬一個網卡，並且強制將所有流量 Loop 過去的方式來一把抓所有電腦對外的流量。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5bXIV5X4HZRv2dklPt6Zg.png" /><figcaption>Surge Dashboard</figcaption></figure><p>除了 HTTP Capture 的功能方便開發者外，因為本身處理大量後端開發時，許多企業組織的網管都會將核心資料庫或 API Service 放在其 Private Network 中，需存取的人需要先透過 SSH 等連線到其跳板機中後，再行中轉到正確的內網 IP 存取資料。因為很多 UI 非常好用的 DB 客戶端無法直接透過 SSH Tunnel 來連線，開發時我也不想每次開發前都先在本機開好 SSH Tunnel 才開始工作，忘記開關反而留了一堆漏洞在外面。又或是現在因為 WFH 的關係，我人都不在公司工作，但因為很多合作廠商都是僅針對公司的固定 IP 開啟防火牆通道；雖然公司提供 IPSec VPN 可以直接隨時掛在上面開發，但一來是 VPN 就算是國內還是無法完全避免拉升 Ping 影響我平常網路的使用，加上平常開發等待 Bundle/Build 的時候我會去逛逛各種不同的文章或資源網站，有時候會需要透過 VPN 繞去國外突破 IP 限制。</p><p>這樣的需求下，系統內建的 VPN 工具一次只能進行一個 VPN 綁定的情況下，我需要一直不斷地切換不同的 VPN Channel 切到我常常不知道自己現在是飛到哪個國家去了。因應這些需求，我通常會依據資安等級要求的不同，我通常會選擇在跳板機器上建立 Snell 或是 Shadowsocks 的 VPN 服務，並且透過 Surge 設定特定 IP Range 或是 Domain 自動透過該 VPN 通道進行連線。常用的網域或 Domain 就讓一般坊間的 VPN Service 掛在本機某個端口的 Socks5 提供服務。</p><p>設定完成後，Surge 就會自動依據設定好的條件決定 Request 要走哪條通道，來達到我工作多工進行的時候，開發該走的 API Gateway 會正確通過公司 VPN 連線，查詢 DB 的 GUI 工具會透過 SSH Tunnel 進行連線，一般網頁瀏覽透過 Cloudflare Warp+ 私密連線，大流量需要高 Ping 的需求走原生網路出去。</p><p>Surge v4 後更提供了 Proxy Chain 的功能，可以讓你所有的 Proxy 通道使用 Pipeline 的方式先經過 A -&gt; B -&gt; C -&gt; WWW 這樣的順序進行跳板連接。以前在那邊開一堆 SSH Reverse Tunnel 的血淚一掃而空 🥰</p><p>Mac 的版本大致上算是一次購買並且不斷的更新，我自己是從 v3 買了，後來出了 v4 後雖然要重新收費，但有根據距離 v4 出的時間（也就是 v3 你用了多久）來換算相應的折扣，對於 M1 Chip 的支援也算是滿快速的，個人覺得是很有誠意的開發者。在此推薦給所有被 Routing 搞得很煩躁的 SRE 們 👏🏼</p><p>另外，他還有依據各種 HTTP Headers/URL 條件的 Rewrite 機制，或是可以透過 JavaScript 寫 Custom Script 把 MITM 拆出來的 Body 進行一些內容改寫，弄 Middleware 的方便功能。可以弄的滿花俏的，只是我大部分使用都是 Routing Rules 為主就先不獻醜哩。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be86745230b" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/surge-%E8%AE%93%E4%BD%A0%E7%9A%84-vpn-%E6%9C%8D%E5%8B%99%E5%83%8F%E6%98%AF-unix-pipeline-%E8%88%AC%E7%9A%84%E4%B8%B2%E6%8E%A5-2be86745230b">Surge 讓你的 VPN 服務像是 Unix Pipeline 般的串接</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Actions 初探]]></title>
            <link>https://insights.rytass.com/github-actions-%E5%88%9D%E6%8E%A2-6ede4c4176f4?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ede4c4176f4</guid>
            <category><![CDATA[continuous-deployment]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[workflow-automation]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 14:17:43 GMT</pubDate>
            <atom:updated>2021-07-15T14:17:43.677Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7awAGYIf68dX7Kix" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>GitHub 在微軟爸爸買走後開始大量出現新功能，Actions 算是終於離開了 <a href="https://travis-ci.org/">Travis CI</a> 的生態系的一步。過去因為自行架設 <a href="https://www.jenkins.io/">Jenkins</a> 需要維護其版本與各種漏洞修復，對沒有專職 SRE 的小團隊來說是個不小的負擔，尋找一個可用的 SaaS 服務一直都是比較簡單的解決方案。</p><p>有段時間我大量使用 <a href="https://circleci.com/">CircleCI</a> 作為主要的解決方案，不過其免費版本實在太慢，相關的生態系不足，很多腳本得自己寫出來或是翻大量的文件（但這是他剛出來那一兩年，現在不確定是否有改善）。自從 Actions 這個 Tab 出現在我們 Repo 的上方，一直想找時間來試試看是否能作為主要的 Continuous Deployment 方案。</p><p>背景介紹一下，我們團隊已經大量採用 Containerize 的方式進行各種前、後端模組的包裝，並且透過 Google Cloud Artifact Registry 作為主要與 Production/Staging Server 的溝通中介，以 Node.js 作為基礎的專案，我們採用 npm script 來完成 webpack/typescript 的 compile 與 docker build 的 pipeline 工作。</p><p>這樣的背景下距離完全自動化 Deployment 其實只差在每次完成新版本需要手動執行 yarn release 後 ssh 到 server 上跑一個已經寫好的 shell script 來完成 rolling update 的工作。身兼 SRE 的我，近期因為有些專案大量測試修改並部署到 Staging Server 時，開發團隊修的速度太快專案又有上線壓力，讓我每三四個小時就得跑一次上述的流程，無腦但無趣 Boring。</p><p><strong>以上廢話 TL;DR;</strong></p><p>打開 GitHub Actions，會看到以 Workflow 作為 Actions 的 Group 機制，單一 Repo 下可以建立多組 Workflow 設定不同的 Trigger 條件來進行不同的工作，有點類似 iOS Shortcuts 的邏輯。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*5SYaJp_S4ygIUN5OGfOFKA.png" /><figcaption>GitHub actions workflow logs</figcaption></figure><p>如同多數 CD 工具，GitHub Actions 也是採用 yaml 作為主要的描述檔案格式（這個格式不嚴謹的很討厭）透過內建的範例打開會有幾個 Sections:</p><ul><li>on: 作為此 Workflow 的觸發條件，可以設定為通送至某個 branch 、推上符合規則名字的 tag 、建立 PR 於特定 branch 或是直接設定 cronjob 定時。支援的條件還滿豐富的，大部分情況我們會使用某些特定的 branch name 作為推上不同環境的切分 (e.g. staging/production/release)</li><li>env: 如其名，就是可以設定環境變數，我們專案上大部分可變參數都會使用 .env 來帶入，但因為通常他都是 .gitignore 的對象，所以這裡必需手動補回去。另外有些敏感的金鑰，GitHub 有提供 Secrets 作為存放的地方，稍後會介紹到。</li><li>jobs: 這邊就是重點了，所有要執行的項目都從這邊依序進行，每個 Job 下面可以有多個 steps，並且每個 step <strong>必須</strong>給他名字才能正常運行，我第一次使用的時候因為放了一堆 steps 但少給一個名字就格式錯誤卡死。</li></ul><p>對於 Job/Step 兩個層級都可以給 if 的條件，透過當下 environment variables 決定要不要跳過該段工作，類似於這樣：</p><pre>- name: Log into register ${{ env.REGISTRY_URL }}<br>  if: github.event_name != &#39;pull_request&#39;<br>  uses: docker/login-action<br>  with:          <br>    registry: asia-east1-docker.pkg.dev          <br>    username: _json_key          <br>    password: ${{ secrets.GAR_JSON_KEY }}</pre><p>因為我的 on 條件設定了 PR 到 release 時要跑 ci 的工作，但我並不希望把跑完的 docker image 丟到正式環境的 registry 中，便可以用 if 的方式讓同一個 workflow 可以完成大部分一樣小地方有差異的工作，其中的 secrets 便是上面提到的存放金鑰的地方。另外，這裡也用了 with 關鍵字，其用法就像是在 shell 中使用 dash 開頭的 args 執行參數。</p><p>GitHub Actions 有個很符合他的用法，uses 關鍵字，後面可以直接接上 GitHub Repo 的名字，使用別人為你開發好特 steps 組合，這樣像是常用的 docker build/docker push 等等工作就不用自己從頭開始寫 shell script 了。官方針對這些套件也做了一個 Marketplace 來整理，常用的想像得到的應該都有了，就不需要重複造輪子。</p><p><a href="https://github.com/marketplace?type=actions">GitHub Action Template Marketplace</a></p><p>一些我常用的套件如下</p><ul><li><a href="https://github.com/actions/setup-node">actions/setup-node</a>: 設定要使用的 node 版本</li><li><a href="https://github.com/docker/login-action">docker/login-action</a>: 登入 Docker Registry</li><li>docker/build-push-action: 打包並推上 Docker Registry（可用 with 指定 context/dockerfile）</li><li><a href="https://github.com/appleboy/ssh-action">appleboy/ssh-action</a>: 執行 ssh 到遠端機器並執行 shell 指令</li><li><a href="https://github.com/cloudflare/wrangler-action">cloudflare/wrangler-action</a>: 把 script 送到 Cloudflare 的 workers</li><li><a href="https://github.com/slackapi/slack-github-action">slackapi/slack-github-action</a>: 發送一條訊息到 Slack Channel</li></ul><p>效率上，因為我們專案上微服務的需求切分的滿細的，單一個站體通常平均有十個左右的 docker image 需要進行打包，在涵蓋慢慢的 webpack 及肥肥的 yarn install node_modules 後加以 docker build 的時間，跑一個 14 個微服務的 CD 流程平均只要 13 分鐘，算是效能很好的選擇了。同樣的內容在我自己的 Macbook Pro (i9-8950HK) 下都需要跑 8 分多鐘的時間，感謝 Azure 微軟爸爸的贊助。</p><p>最後提一下差點忘記的 Secrets，你可以從個人的設定 (Settings) 中找到 Secrets 標籤，去新增純文字內容的 Secrets，因為 Workflow 會去建立者的 Secrets 載入字串並且讓其作為 Key-Values 的環境變數讓你的 Job/Step 存取，如果你的組織有付費的話，可以建立 Organization 層級的 Secrets 會更方便。</p><p>需要特別注意的是因為所有的 workflow logs 會開放給 Repo Writer 看，所以千萬不要把 Secrets 的內容 echo/print 出來啊，不然 Secrets 就不 Secrets 了。且不用擔心有心人去修改 workflow 把你的 secrets 印出來，因為改過以後只會印出改的人的 🤡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ede4c4176f4" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/github-actions-%E5%88%9D%E6%8E%A2-6ede4c4176f4">GitHub Actions 初探</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Private Relay, yet another VPN service?]]></title>
            <link>https://insights.rytass.com/private-relay-yet-another-vpn-service-9d89276801fd?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d89276801fd</guid>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[private-relay]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[wwdc-2021]]></category>
            <category><![CDATA[edge-networking]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Thu, 17 Jun 2021 18:06:09 GMT</pubDate>
            <atom:updated>2021-06-17T18:06:09.985Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*ZYMfqYl_6FfhJ0nptXl1yw.jpeg" /><figcaption>2021 WWDC, Apple announced Private Relay service in iCloud+</figcaption></figure><p>在 2021 WWDC 中，除了大量對於 macOS/iPadOS/iOS 的微調小更新外，對於技術人員來說 Private Relay 算是少數讓我半夜精神一振的項目了。因為我手邊的 iPad 升級後看起來無法正常透過 Private Relay 中介，所以只能透過網路上各種科技媒體的報導、WWDC 官方說明影片與先行者實測的結果來看看這個名詞背後使用的技術到底是什麼了。</p><p>首先，根據目前流出的技術文件，他不是像傳統 VPN 一樣藉由 Apple 架設中繼站，讓使用者將自己對外的連線透過這個中繼站 bypass 轉送封包，來達到終端伺服器沒辦法得知真正的使用者是誰，而只能看到中繼站的 IP 這樣的做法，Private Relay 利用了現在已經被大量建置在全世界的 Edge Network 來實作隱私瀏覽機制。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*7Afg7Z5up6uxxTCJbrxBNA.png" /><figcaption>iCloud Private Relay Working Flow</figcaption></figure><p>當使用者透過 Private Relay 瀏覽的時候，使用者端設備會先將目標網站的 Server Name 進行加密後，將整包內容送給 Apple 的中繼伺服器，但是將不由 Apple 的伺服器直接轉送給終端伺服器，而會先在 Apple 的伺服器中先進行來源封包的地址轉換（類似 Hide Email 的實作，把使用者的 IP 位置對應成一個新的虛擬位置，對應表只在 Apple 的伺服器中可以解回原本的 IP 位置）。此外，因為該包內容是經過加密且無法由 Apple 的伺服器進行解密，所以 Apple 的伺服器實際上只掌握了該密文的源頭。</p><p>當位置轉換紀錄完成後，Apple 會透過各大 CDN 服務商於全世界建立的 Edge Network 節點網路進行封包轉送的工作。這些與 Apple 合作的服務商具有解密的私鑰，可以解開來自於 Apple 中繼伺服器的連線需求，找到使用者真正想訪問的網站位置 (Server Name) 來與終端伺服器進行連線，並將伺服器回覆的內容送回 Apple 的中繼伺服器，由其透過位置轉換回傳給使用者手中。</p><p>這樣的機制會造成兩個片段資料分別儲存於不同的營運商手中，Apple 的伺服器只知道需求的來源位置卻不知道需求的內容，CDN 服務商只知道需求的目標位置但不知道來自於哪個源頭 IP，而終端網站的開發者只能知道使用者來源是大型 CDN 服務，無法得知真正的 IP 位置。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PNCiGEQcfuyq9b3P" /><figcaption>Photo by <a href="https://unsplash.com/@picsaf?utm_source=medium&amp;utm_medium=referral">Azamat E</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>這可以看作 Apple 對於隱私權的保護在 iOS 14 砍掉第三方 Cookies 的權限後，又一個新的高牆建立在所有廣告服務商之前，過去 ISP/網站建立者/CDN 業者都可以藉由其在整個網路的位置中，去推斷某個 IP 位置的特定時段內使用者的使用習慣，並可以進行跨站連結。既使 iOS 14 禁掉第三方 Cookies 的追蹤，大型廣告服務商仍然可以藉由其追蹤碼與機制的廣布，來獲得使用者的圖譜分析（現在應該很少人一次只開一個分頁瀏覽網站吧？），現在因為透過 Private Relay 進行瀏覽時，每個分頁、甚至同個分頁中的不同 Request 都會來源於不同的 IP，而實際的造成分析上的困難。</p><p>未來，對於使用者資料的分析，我認為會更加的朝向邊緣化進展，也就是透過 Ad Blocks 這類的本地 Extensions 或是瀏覽器本身進行使用者資料的追蹤，畢竟還沒出去你的電腦資料當然都有囉～</p><p>Google 也於去年提出 FLoC 作為本地的解決方案，詳細運作機制可以參考之前的文章：<a href="https://medium.com/rytass/google-floc-2021-on-digital-advertising-based-on-privacy-d25234804df2">FLoC 是什麼，隱私時代的廣告投放</a>。</p><p>關於邊緣網路的發展，有興趣的人我滿建議可以試著理解 Cloudflare Warp/Argo 的野望，透過公私網混合架構，弄出一個像是 Onion Network 的基於公網的私人網路是很有趣的技術，透過 Warp/Argo 的線路也是相當不錯的國際路由優化與跳板機制，瀏覽非 Cloudflare 網路的網站就跟透過 VPN 有一樣的隱藏效果，電腦可以免費使用來跨區🤭。</p><p>後注：目前 Private Relay 只會轉發 Safari 的連線，所以如果使用 Google Chrome/Microsoft Edge/Mozilla Firefox 等瀏覽器是不會經過 Private Relay 的。不過蘋果官方有提供相關的 API 就等各家業者接上就可以了，這個歷程歷史上來看應該會需要一到兩年的時間。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d89276801fd" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/private-relay-yet-another-vpn-service-9d89276801fd">Private Relay, yet another VPN service?</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[台灣社交距離運作機制詳解，究竟有沒有資安疑慮？]]></title>
            <link>https://insights.rytass.com/%E5%8F%B0%E7%81%A3%E7%A4%BE%E4%BA%A4%E8%B7%9D%E9%9B%A2%E9%81%8B%E4%BD%9C%E6%A9%9F%E5%88%B6%E8%A9%B3%E8%A7%A3-%E7%A9%B6%E7%AB%9F%E6%9C%89%E6%B2%92%E6%9C%89%E8%B3%87%E5%AE%89%E7%96%91%E6%85%AE-311e4ab78cc1?source=rss-a6549dbaae8b------2</link>
            <guid isPermaLink="false">https://medium.com/p/311e4ab78cc1</guid>
            <category><![CDATA[社交距離]]></category>
            <category><![CDATA[隱私]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[資安]]></category>
            <category><![CDATA[exposure-notification]]></category>
            <dc:creator><![CDATA[Chia Yu Pai]]></dc:creator>
            <pubDate>Tue, 11 May 2021 13:38:44 GMT</pubDate>
            <atom:updated>2021-05-14T06:16:22.629Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DwHefx9orCYeLMJav_4v7Q.png" /></figure><p>近日台灣疫情再度陷入高危險之中，社群間開始大量推廣「<a href="https://apps.apple.com/tw/app/%E8%87%BA%E7%81%A3%E7%A4%BE%E4%BA%A4%E8%B7%9D%E9%9B%A2/id1554431836?l=en">台灣社交距離</a>」這個 App，希望大家多多下載。那麼在隱私越來越注重的時代下，這樣的追蹤行動應用究竟會不會成為政府追蹤人民動態的利器呢？</p><p>答案是：不太有可能。</p><p>首先，我們來看看這個應用的背後運作機制，這個 App 其實是建基於去年 Apple 與 Google 因應國外疫情的爆發，而共同<a href="https://covid19.apple.com/contacttracing">提出</a>的一種兼顧隱私權與流行病學上的疫調需求的解決方案，有興趣了解實作機制的人可以參考下面連結：<a href="https://covid19.apple.com/contacttracing">https://covid19.apple.com/contacttracing</a>。</p><p>他是種十分聰明的機制，這個機制利用現代人手機不離身的特點，開啟手機的藍牙功能。當手機藍牙功能開啟時，可以透過廣播給周邊的裝置自己的晶片代號，這樣的機制跟你購買新藍牙裝置需要經過配對才能使用是一樣的道理。台灣社交距離 App 會在你啟用時，結合手機系統的內建功能「暴露通知」產生一組隨機編碼，這組編碼只會存在你的手機之中，並且不斷的從背景廣播給周邊的裝置。</p><p>也就是說，裝了這個 App 後，你的手機會週期性的跟周邊所有裝置大喊：「我是 FC52C439BB194AC1290….」這樣的識別碼（題外話，這個跟最新的 AirTag 機制很像 🤭）。</p><p>而所有裝載這個 App 的使用者，都會打開耳朵監聽附近所有裝置的大喊，並且記錄在自己的手機上，保留 28 天（更新：目前改為 14 天而已）的時間，超過就跟錄音帶洗掉一樣會永遠只保留最新的 28 天資料（超過基本上就不是潛伏期，會有症狀的）。</p><p>到目前為止，這些動作都只在自己的手機上紀錄，沒有經過任何網路傳輸功能，也就是說，你手機就算沒有買 4G/5G 上網，也完全沒有透過 WiFi 連線到網路，上述的功能都還是可以正常運作哦！也就是說就算你都在沒訊號的地下室都還是會追蹤到周邊大喊的裝置。</p><p>最後，當你不幸確診時，你可以透過 App 中內建上傳確診者 ID 的機制，也就是你不斷大喊的 FC52C439BB194AC1290… 交給 Apple / Google 的伺服器，他們會透過 iOS / Android 內建的網路溝通機制發送給全體手機使用者。</p><p>當你的朋友手機收到這樣的確診廣播，就會迅速比對手機中紀錄的 28 天接觸資料是否有 FC52C439BB194AC1290… 這個裝置，如有，那麼他就會是可能的被傳染者，需要開始進行居家隔離或自主健康管理（這個疾管署甚至不會知道，除非他自己把通知交出去或是你供出他）。</p><p>因為，知道跟 FC52C439BB194AC1290… 有接觸的只有你朋友的手機，雖然你的手機理應會有一筆跟你朋友接觸的紀錄，知道有個接觸者是 CD1752039C5812ABF… 但不知道他是你的哪一位朋友 🥲。</p><p>這樣聰明簡單的機制確保就算你跟確診者曾共處一室，但他卻不會知道你是誰，只有你自己知道一切，政府是不可能追蹤你的。</p><p><a href="https://apps.apple.com/tw/app/%E8%87%BA%E7%81%A3%E7%A4%BE%E4%BA%A4%E8%B7%9D%E9%9B%A2/id1554431836">iOS 版本下載</a></p><p><a href="https://play.google.com/store/apps/details?id=tw.gov.cdc.exposurenotifications&amp;hl=en_US&amp;gl=US">Android 版本下載</a></p><p>P.S. 請不要任意裝設宣稱類似功能的 App，社交距離 App 因為沒有要求 GPS 定位位置，以及可以正常地被 Apple / Google 官方任何產生系統「暴露通知」隨機碼，所以可以達成近乎完美的隱私性。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=311e4ab78cc1" width="1" height="1" alt=""><hr><p><a href="https://insights.rytass.com/%E5%8F%B0%E7%81%A3%E7%A4%BE%E4%BA%A4%E8%B7%9D%E9%9B%A2%E9%81%8B%E4%BD%9C%E6%A9%9F%E5%88%B6%E8%A9%B3%E8%A7%A3-%E7%A9%B6%E7%AB%9F%E6%9C%89%E6%B2%92%E6%9C%89%E8%B3%87%E5%AE%89%E7%96%91%E6%85%AE-311e4ab78cc1">台灣社交距離運作機制詳解，究竟有沒有資安疑慮？</a> was originally published in <a href="https://insights.rytass.com/">Rytass Insights</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>