PICORUBY × CLOUDFLARE WORKERS — REFERENCE
Bindings referenceバインディング
リファレンス
Everything you need to use D1, KV, R2, Workers AI, Vectorize, Queues, Durable Objects, Access, fetch, and Web Crypto from PicoRuby: how to configure each binding, working code, method signatures, and the exact limits of the current runtime. PicoRuby から D1、KV、R2、Workers AI、Vectorize、Queues、Durable Objects、Access、fetch、Web Crypto を使うためのリファレンスです。バインディングごとの設定方法、動くコード例、メソッドのシグネチャ、現行ランタイムの制約をまとめています。
FOUNDATIONS
How bindings reach Rubyバインディングが Ruby に届くまで
Cloudflare bindings stay inside the Worker's JavaScript env object; PicoRuby never holds a pointer to them. Each Rack request instead receives a Cloudflare::Environment proxy at env["cloudflare.env"], which turns a binding name into a small Ruby wrapper. Calling a method on the wrapper serializes the arguments, awaits the Worker API in JavaScript, and resumes Ruby with the result.
Cloudflare のバインディングは Worker(JavaScript)側の env オブジェクトに置かれたままで、PicoRuby がそのポインタを持つことはありません。各 Rack リクエストには env["cloudflare.env"] に Cloudflare::Environment プロキシが渡され、バインディング名を小さな Ruby ラッパーに変換します。ラッパーのメソッドを呼ぶと引数がシリアライズされ、JavaScript 側で Worker API を待ち、その結果を持って Ruby の実行が再開します。
wrangler.jsoncDeclare the binding and its name.バインディングと名前を宣言する。npm run buildA binding-type registry is generated from the config.設定から型のレジストリが生成される。env["cloudflare.env"].NAMEThe proxy returns a typed Ruby wrapper.プロキシが型付きの Ruby ラッパーを返す。JSPIRuby suspends while the Worker API runs, then resumes.Worker API の実行中は Ruby が中断し、完了後に再開する。
A complete example最小の完全な例
A Rack application that counts visits in KV. There is no require and no client to set up — the binding name in wrangler.jsonc is the only link between configuration and code.
KV で訪問回数を数える Rack アプリです。require もクライアントの初期化も不要で、wrangler.jsonc のバインディング名だけが設定とコードを結びつけます。
{
"kv_namespaces": [
{ "binding": "CACHE_KV", "id": "<namespace-id>" }
]
}class App
def self.call(env)
kv = env["cloudflare.env"].CACHE_KV
count = (kv.get("visits") || "0").to_i + 1
kv.put("visits", count.to_s)
[200, { "content-type" => "text/plain" }, ["visits: #{count}"]]
end
end
Rackup::Handler::CloudflareWorker.run(App)In Sinatra the same proxy is available as env["cloudflare.env"] inside routes and helpers:
Sinatra でも、ルートやヘルパーの中から同じく env["cloudflare.env"] で参照できます。
class App < Sinatra::Base
get "/visits" do
kv = env["cloudflare.env"].CACHE_KV
count = (kv.get("visits") || "0").to_i + 1
kv.put("visits", count.to_s)
content_type "text/plain"
"visits: #{count}"
end
end
Rackup::Handler::CloudflareWorker.run(App)KV is eventually consistent and has no atomic increment, so this counter can lose updates under concurrent traffic. It is fine for a demo; use D1 (UPDATE … SET n = n + 1) when the count must be exact.
KV は結果整合性でアトミックなインクリメントもないため、同時アクセスがあるとこのカウンタは更新を取りこぼします。デモには十分ですが、正確な値が必要なら D1(UPDATE … SET n = n + 1)を使ってください。
Three rules3 つの原則
Request-scopedリクエストスコープ
Wrappers resolve against the current request's Worker env and are cached only for that request. Resolve them from env each time instead of storing them globally.
ラッパーは現在のリクエストの Worker env に対して解決され、そのリクエストの間だけキャッシュされます。グローバルに保持せず、毎回 env から取得してください。
Typed by configuration型は設定で決まる
The build maps every binding name in wrangler.jsonc to its type. The runtime never guesses a type from an object's methods, so an unsupported binding can't be mistaken for KV.
ビルド時に wrangler.jsonc のバインディング名と型の対応表が作られます。ランタイムがメソッドから型を推測することはないので、未対応のバインディングを KV と取り違えることもありません。
Synchronous-looking RubyRuby からは同期的
Every call returns a value or raises. There are no callbacks or promises in Ruby: JSPI suspends the Wasm stack while JavaScript awaits, then resumes the same Ruby frame.
どの呼び出しも値を返すか例外を投げるだけです。Ruby 側にコールバックや Promise はなく、JavaScript が待っている間は JSPI が Wasm のスタックを中断し、同じ Ruby のフレームから再開します。
Binding catalogバインディング一覧
| Bindingバインディング | Ruby APIRuby API | wrangler.jsonc |
|---|---|---|
| Variables & secrets変数と secret | Cloudflare::Environment, ENV | vars, wrangler secret |
| D1 | Cloudflare::D1 | d1_databases |
| Workers KV | Cloudflare::KV | kv_namespaces |
| R2 | Cloudflare::R2 | r2_buckets |
| Workers AI | Cloudflare::AI | ai |
| Vectorize | Cloudflare::Vectorize | vectorize |
| Queues | Cloudflare::Queue, Cloudflare::QueueConsumer::Base | queues |
| Durable Objects | Cloudflare::DurableObject | durable_objects |
| Access | Rack::Cloudflare::Access | vars.CF_ACCESS_TEAM |
| Fetch | Cloudflare.fetch | — |
| Web Crypto | SecureRandom, Crypto | — |
FOUNDATIONS
Adding a bindingバインディングを追加する
Every resource binding is added the same way. The examples assume a project generated by picoruby-cloudflare new.
どのリソースバインディングも同じ手順で追加します。以下は picoruby-cloudflare new で生成したプロジェクトを前提にしています。
-
Create the resourceリソースを作成する
Use Wrangler for the resources that need to exist before deploy. Note the IDs it prints.
デプロイ前に存在している必要があるリソースを Wrangler で作成します。表示される ID を控えておきます。
Shell npx wrangler kv namespace create CACHE_KV npx wrangler d1 create my-database npx wrangler r2 bucket create my-bucket npx wrangler queues create events npx wrangler vectorize create documents --dimensions=768 --metric=cosine -
Declare it in wrangler.jsoncwrangler.jsonc に宣言する
The
bindingfield (namefor Durable Objects) is the identifier Ruby uses. Names must be unique across all sections.bindingフィールド(Durable Objects ではname)が Ruby から使う識別子です。名前はすべてのセクションを通して一意である必要があります。 -
Rebuildビルドし直す
npm run buildreadskv_namespaces,d1_databases,r2_buckets,ai,vectorize,queues.producers, anddurable_objects.bindings, and regenerates the binding-type registry.npm run devalone does not rebuild.npm run buildがkv_namespaces、d1_databases、r2_buckets、ai、vectorize、queues.producers、durable_objects.bindingsを読み取り、型のレジストリを生成し直します。npm run devだけではビルドされません。 -
Use it from RubyRuby から使う
app.rb db = env["cloudflare.env"].DB # quick access db = Cloudflare::D1.from_env(env, "DB") # raises BindingError unless DB is a D1 database
wrangler dev simulates KV, D1, R2, Queues, and Durable Objects locally. Workers AI and Vectorize have no local simulator; the RAG example sets "remote": true on both bindings so development uses the real services.
wrangler dev は KV、D1、R2、Queues、Durable Objects をローカルでシミュレートします。Workers AI と Vectorize にはローカル版がないため、RAG のサンプルでは両方のバインディングに "remote": true を指定して実サービスを使っています。
Bindings are not inherited by env.staging and other Wrangler environments. Declare them in each environment block.
env.staging などの Wrangler 環境にはバインディングが継承されません。環境ごとのブロックにそれぞれ宣言してください。
FOUNDATIONS
Environment proxy & ENV環境プロキシと ENV
Two doors into the same Worker env: env["cloudflare.env"] returns typed resources and JSON-typed values, while ENV returns variables and secrets as Strings.
同じ Worker env への入口が 2 つあります。env["cloudflare.env"] は型付きのリソースと JSON の型を保った値を返し、ENV は変数と secret を String で返します。
- Ruby
Cloudflare::Environment,ENV- Rack env
env["cloudflare.env"]- wrangler.jsonc
vars,wrangler secret put
Resolving names名前を解決する
cloudflare = env["cloudflare.env"]
db = cloudflare.DB # property syntax
db = cloudflare["DB"] # nil when undefined
db = cloudflare.fetch("DB") # KeyError when undefined
flags = cloudflare.fetch("FLAGS", {}) # default value (a block works too)
cloudflare.key?("DB") # => true
klass = cloudflare["class"] # names that clash with Ruby methodsThe forms differ only in how they treat a name that is not defined:
書き方による違いは、未定義の名前の扱いだけです。
| Form書き方 | Undefined name未定義のとき |
|---|---|
cloudflare.NAME | raises例外 NoMethodError |
cloudflare["NAME"] | returns戻り値 nil |
cloudflare.fetch("NAME") | raises KeyError unless a default or block is givenデフォルト値かブロックがなければ KeyError |
Cloudflare::KV.from_env(env, "NAME") | raises Cloudflare::BindingError — also when the binding has another typeCloudflare::BindingError(型が違う場合も同様) |
from_env exists on every wrapper class: KV, D1, R2, AI, Vectorize, Queue, and DurableObject. Each wrapper also exposes binding_name, a frozen copy of the name it was resolved with.
from_env はすべてのラッパークラス(KV、D1、R2、AI、Vectorize、Queue、DurableObject)にあります。各ラッパーは解決に使った名前の凍結済みコピーを binding_name で返します。
Variables and JSON values変数と JSON 値
{
"vars": {
"API_URL": "https://api.example.com",
"FEATURE_FLAGS": { "beta": true, "limit": 10 }
}
}cloudflare = env["cloudflare.env"]
cloudflare.API_URL # => "https://api.example.com"
cloudflare.FEATURE_FLAGS # => {"beta" => true, "limit" => 10}
ENV["API_URL"] # => "https://api.example.com"
ENV["FEATURE_FLAGS"] # => "{\"beta\":true,\"limit\":10}"
ENV["CACHE_KV"] # => nil — resources are not ENV valuesThrough the proxy, JSON variables keep their types: Hash, Array, true/false, numbers, and nil. A JSON null still counts as present — key? is true and fetch returns nil. Through ENV, the same values arrive as compact JSON Strings, so false becomes "false". Text variables and secrets are plain Strings either way.
プロキシ経由では JSON の変数は型を保ちます(Hash、Array、true/false、数値、nil)。JSON の null も「存在する」扱いで、key? は true、fetch は nil を返します。ENV 経由では同じ値がコンパクトな JSON 文字列になり、false は "false" になります。文字列の変数と secret はどちらでも String です。
SecretsSecret
npx wrangler secret put API_TOKEN # production
echo 'API_TOKEN=dev-token' >> .dev.vars # wrangler devtoken = ENV.fetch("API_TOKEN") # KeyError if the secret is not setSecrets are read exactly like text variables. Inspecting the proxy or ENV never prints values, so logging env["cloudflare.env"] or the whole Rack env cannot leak a secret.
secret は文字列の変数とまったく同じように読めます。プロキシや ENV を inspect しても値は表示されないので、env["cloudflare.env"] や Rack env 全体をログに出しても secret は漏れません。
Writing to ENVENV への書き込み
ENV["API_URL"] = "http://test.invalid" # warns on stderr (without the value)
ENV["API_URL"] # => "http://test.invalid" — this request only
ENV.delete("API_URL") # hides the Cloudflare value for this requestAssignment, delete, clear, update/merge!, and replace change only a request-local overlay that is discarded before the next request; Cloudflare's values are never modified. ENV is not a Hash and cannot be enumerated — to_h raises NotImplementedError. Lookups are synchronous and never suspend.
代入、delete、clear、update/merge!、replace はリクエストローカルな上書き層を変更するだけで、次のリクエストの前に破棄されます。Cloudflare 側の値は変わりません。ENV は Hash ではなく列挙もできません(to_h は NotImplementedError)。読み取りは同期的で、中断は発生しません。
API
Cloudflare::Environment
NAME→ wrapper | value- Property syntax. Raises
NoMethodErrorfor an undefined name. - プロパティ構文。未定義なら
NoMethodError。 [](name)→ wrapper | value | nil- Returns
nilfor an undefined name. - 未定義なら
nil。 fetch(name, default = nil) { |name| }→ wrapper | value- Like
Hash#fetch: default, block, orKeyError. Hash#fetchと同様。デフォルト値、ブロック、またはKeyError。key?(name),has_key?(name)→ true | false- Whether the name is defined.
respond_to?uses the same check. - 名前が定義されているか。
respond_to?も同じ判定を使います。
ENV
ENV[key]→ String | nil- Variable or secret; JSON values as compact JSON. Resources return
nil. - 変数または secret。JSON 値はコンパクトな JSON 文字列。リソースは
nil。 ENV.fetch(key, default = nil) { |key| }→ StringKeyErrorwhen missing and no default or block is given.- 存在せず、デフォルト値もブロックもなければ
KeyError。 ENV.key?(key)→ true | false- Aliases:
has_key?,include?,member?. - 別名:
has_key?、include?、member?。 ENV[key] = value,delete,clear,update,replace- Request-local overlay. Keys must be non-empty Strings (
TypeError/ArgumentError); values must be Strings ornil. - リクエストローカルな上書き。キーは空でない String(
TypeError/ArgumentError)、値は String かnil。
cloudflare-env.md ↗Cloudflare: environment variables ↗Cloudflare: secrets ↗
FOUNDATIONS
Errorsエラー
Integration failures share one hierarchy, so a single rescue separates platform problems from bugs in your own code.
連携まわりの失敗は共通の階層にまとまっているので、1 つの rescue でプラットフォーム側の問題とアプリのバグを切り分けられます。
Cloudflare::Error < StandardError
Cloudflare::BindingError # binding missing, or of another type
Cloudflare::HostError # the Worker API call failed
Cloudflare::ProtocolError # malformed data crossed the bridge| Exception例外 | Raised when発生する場面 |
|---|---|
ArgumentError, TypeError | Arguments are invalid. Checked in Ruby before anything reaches the host — for example a KV ttl below 60 or a Hash bound as a D1 parameter.引数が不正なとき。ホストに渡る前に Ruby 側で検査されます(KV の ttl が 60 未満、D1 のパラメータに Hash を渡した、など)。 |
NoMethodError | cloudflare.NAME for an undefined name.未定義の名前を cloudflare.NAME で参照したとき。 |
KeyError | fetch of an undefined name without default (proxy and ENV).デフォルト値なしで未定義の名前を fetch したとき(プロキシと ENV)。 |
Cloudflare::BindingError | from_env for a missing binding or one of another type.from_env で指定したバインディングが存在しない、または型が違うとき。 |
Cloudflare::HostError | The Worker API rejected: an SQL error, a failed inference, a network error, a fetch redirect, an oversized response…Worker API が失敗したとき。SQL エラー、推論の失敗、ネットワークエラー、fetch のリダイレクト、サイズ超過など。 |
Cloudflare::ProtocolError | A host result could not be decoded: invalid JSON, an unexpected result shape, invalid UTF-8.ホストからの結果を解釈できないとき。不正な JSON、想定外の結果の形、不正な UTF-8 など。 |
Cloudflare::Access::Unauthorized | Access answered 401/403 to get_identity. Inherits from StandardError, not Cloudflare::Error.get_identity に Access が 401/403 を返したとき。Cloudflare::Error ではなく StandardError を継承しています。 |
RuntimeError | AES-GCM decryption failed authentication.AES-GCM の復号で認証に失敗したとき。 |
Handling errorsエラーを処理する
class App < Sinatra::Base
error Cloudflare::Error do
status 502
content_type "application/json"
JSON.generate({ "error" => "upstream binding failed" })
end
endclass App
def self.call(env)
user = env["cloudflare.env"].DB.query("SELECT name FROM users WHERE id = ?1", 1).first
[200, { "content-type" => "text/plain" }, [user ? user[:name] : "nobody"]]
rescue Cloudflare::HostError
[503, { "content-type" => "text/plain" }, ["database unavailable"]]
end
endFOUNDATIONS
Streams & request bodiesストリームとリクエストボディ
Large bodies don't have to pass through Ruby. The request body is read on demand, and Workers AI or R2 responses can be handed to the client as host-owned streams.
大きなボディを Ruby に通す必要はありません。リクエストボディは必要な分だけ読み出され、Workers AI や R2 のレスポンスはホスト所有のストリームとしてそのままクライアントへ渡せます。
- Request bodyリクエストボディ
env["rack.input"]- Host streamホストストリーム
Cloudflare::StreamDescriptor- Stream responseストリーム応答
env["cloudflare.hijack"]
Reading the request bodyリクエストボディを読む
env["rack.input"] (also available as env["cloudflare.input"]) is a Cloudflare::InputStream. Bytes are pulled from the Worker request in 16 KiB chunks only when you read, and are binary-safe.
env["rack.input"](env["cloudflare.input"] でも同じ)は Cloudflare::InputStream です。読んだときにだけ Worker のリクエストから 16 KiB 単位でバイトを取り出し、バイナリセーフに扱います。
payload = JSON.parse(env["rack.input"].read) # the whole body
input = env["rack.input"]
chunk = input.read(1024) # up to 1024 bytes, nil at EOF
rest = input.read # everything left, "" at EOF
input.rewind # back to the first byte
input.each { |line| } # line by line (also: gets)The host accepts request bodies up to 1 MiB by default (its maxRequestBodyBytes option). A larger Content-Length is rejected with 413 before Ruby runs.
ホストが受け付けるリクエストボディはデフォルトで最大 1 MiB です(ホストの maxRequestBodyBytes オプション)。それより大きい Content-Length は Ruby が動く前に 413 で拒否されます。
Host streamsホストストリーム
Workers AI (with "stream" => true) and R2#get return a Cloudflare::StreamDescriptor: an opaque handle to a JavaScript ReadableStream. Applications cannot construct one. You can hand it to the response or read it in Ruby — not both.
Workers AI("stream" => true 指定時)と R2#get は Cloudflare::StreamDescriptor を返します。これは JavaScript の ReadableStream を指す不透明なハンドルで、アプリ側では生成できません。レスポンスとして返すか、Ruby で読むかのどちらか一方だけが可能です。
Send it as the responseレスポンスとして返す
env["cloudflare.hijack"] = descriptor
[200, { "content-type" => "text/event-stream", "cache-control" => "no-cache" }, []]- Status and headers still come from the Rack tuple. The body must respond to
each; it is closed but never iterated.ステータスとヘッダは Rack のタプルから取られます。ボディはeachに応答する必要があり、closeはされますが反復はされません。 - Do not set
content-lengthortransfer-encoding; Workers frames the stream.content-lengthやtransfer-encodingは設定しないでください。フレーミングは Workers が行います。 - Bytes flow from JavaScript to the client with backpressure and never enter Wasm. A client disconnect cancels the source.バイトはバックプレッシャー付きで JavaScript からクライアントへ流れ、Wasm には入りません。クライアントが切断するとソースもキャンセルされます。
- HEAD, 204, 205, and 304 responses cancel the source without sending a body.HEAD、204、205、304 のレスポンスではボディを送らずにソースをキャンセルします。
- Descriptors that are not selected are canceled when the request finishes. Middleware that replaces a response after the app set
cloudflare.hijackmust clear that key.選ばれなかったディスクリプタはリクエスト終了時にキャンセルされます。アプリがcloudflare.hijackを設定した後でレスポンスを差し替えるミドルウェアは、このキーをクリアする必要があります。 - Errors before the hand-off can still become an HTTP error; later upstream errors abort the stream and cannot change the status.
rack.response_finishedruns at hand-off, not when the client has received everything.受け渡し前のエラーは HTTP エラーにできますが、それ以降の上流のエラーはストリームを中断するだけでステータスは変えられません。rack.response_finishedは受け渡し時点で実行され、クライアントが受信し終えた時点ではありません。
Read it in RubyRuby で読む
bucket = env["cloudflare.env"].BUCKET
object = bucket.get("config/settings.json")
settings = JSON.parse(object.body.read_all(max_bytes: 64 * 1024)) if object
stream = bucket.get("images/logo.png").body
magic = stream.read_partial(8) # up to 8 bytes (nil at end of stream), e.g. to sniff the type
rest = stream.read_all # everything that is leftThe whole result lives in Wasm memory, so pass max_bytes: for data you don't control; exceeding it raises ArgumentError. Once you start reading, the descriptor can no longer be assigned to cloudflare.hijack.
読んだ結果はすべて Wasm のメモリに載るので、内容を管理できないデータには max_bytes: を指定してください。超えると ArgumentError になります。一度読み始めたディスクリプタは cloudflare.hijack に渡せません。
API
Cloudflare::InputStream (rack.input)
read(length = nil, buffer = nil)→ String | nil- Without
length, the rest of the body (""at EOF). Withlength, up to that many bytes (nilat EOF). lengthなしなら残り全部(EOF では"")。指定するとその長さまで(EOF ではnil)。gets(separator = "\n")→ String | nil- Next line including the separator.
- 区切り文字を含む次の行。
each { |line| }- Yields every line.
- 各行を順に渡します。
rewind→ 0,close→ nil- Rewind to the first byte; close the stream.
- 先頭に戻る / ストリームを閉じる。
Cloudflare::StreamDescriptor
read_partial(length)→ String | nil- Up to
lengthbytes;nilat end of stream. - 最大
lengthバイト。末尾に達したらnil。 read_all(max_bytes: nil)→ String- Reads to the end.
ArgumentErrorwhen the total would exceedmax_bytes. - 末尾まで読みます。合計が
max_bytesを超えるとArgumentError。 id→ Integer- Handle number, for diagnostics only.
- ハンドル番号。診断用です。
DATA
D1
Serverless SQLite through prepared statements. A Ruby statement holds only its SQL and scalar parameters; each terminal call sends them to D1 as JSON and waits for the result.
プリペアドステートメントで使うサーバーレスな SQLite です。Ruby の statement は SQL とスカラー値のパラメータだけを持ち、終端メソッドを呼んだ時点で JSON として D1 に送られ、結果を待ちます。
- Ruby
Cloudflare::D1- wrangler.jsonc
d1_databases[].binding- Resolve取得
env["cloudflare.env"].DB
Configure設定
{
"d1_databases": [
{
"binding": "DB",
"database_name": "my-database",
"database_id": "<database-id>"
}
]
}npx wrangler d1 execute my-database --local --file ./schema.sql # wrangler dev
npx wrangler d1 execute my-database --remote --file ./schema.sql # productionPrepare, bind, runprepare・bind・実行
db = env["cloudflare.env"].DB
find_user = db.prepare("SELECT id, name FROM users WHERE id = ?1")
alice = find_user.bind(1).first # Row or nil
bob = find_user.bind(2).first # the prepared statement is reusable
active = db.query("SELECT id, name FROM users WHERE active = ?1 ORDER BY id", true).rowsbind returns a new statement and leaves the original unchanged, so one prepared statement can serve many parameter sets. query(sql, *params) is shorthand for prepare(sql).bind(*params). Use ?1, ?2, … placeholders — never interpolate values into SQL.
bind は元の statement を変えずに新しい statement を返すので、1 つのプリペアドステートメントを複数のパラメータで使い回せます。query(sql, *params) は prepare(sql).bind(*params) の短縮形です。値は SQL に埋め込まず、?1、?2 などのプレースホルダを使ってください。
Choosing a result shape結果の受け取り方を選ぶ
stmt = db.query("SELECT id, name FROM users ORDER BY id")
stmt.rows # => [{"id" => 1, "name" => "Alice"}, ...]
stmt.first # => {"id" => 1, "name" => "Alice"} or nil
stmt.first(:name) # => "Alice" — one column of the first row
stmt.raw # => [[1, "Alice"], [2, "Bob"]]
stmt.raw(column_names: true) # => [["id", "name"], [1, "Alice"], [2, "Bob"]]
stmt.run # => Cloudflare::D1::Result (rows + metadata)Rows are Cloudflare::D1::Row, a Hash with String keys whose [] also accepts Symbols: row["name"] and row[:name] are equivalent. Only [] converts Symbols; fetch, dig, and other Hash methods need String keys.
行は Cloudflare::D1::Row で、String キーの Hash ですが [] だけは Symbol も受け付けます(row["name"] と row[:name] は同じ)。Symbol を変換するのは [] だけなので、fetch や dig などの Hash メソッドには String キーを使ってください。
Writes and metadata書き込みとメタデータ
result = db
.prepare("INSERT INTO todos (title, completed) VALUES (?1, ?2)")
.bind("Ship PicoRuby", false)
.run
result.success? # => true
result.last_row_id # => 42
result.changes # => 1
todo = db.query("SELECT * FROM todos WHERE id = ?1", result.last_row_id).first
todo[:completed] # => 0 — SQLite stores booleans as 1 and 0result = db.query("DELETE FROM todos WHERE id = ?1", id).run
return [404, { "content-type" => "text/plain" }, ["not found"]] if result.changes == 0Batches are transactionsバッチはトランザクション
results = db.batch([
db.query("UPDATE accounts SET balance = balance - ?1 WHERE name = ?2", 30, "alice"),
db.query("UPDATE accounts SET balance = balance + ?1 WHERE name = ?2", 30, "bob"),
db.query("INSERT INTO transfers (from_name, to_name, amount) VALUES (?1, ?2, ?3)", "alice", "bob", 30),
])
results.map { |result| result.changes } # one Result per statement, in orderD1 runs the statements sequentially and rolls all of them back if one fails (raising Cloudflare::HostError). Every statement must come from the same binding. There is no Ruby transaction block — batch is the transaction API.
D1 は statement を順に実行し、1 つでも失敗するとすべてロールバックします(Cloudflare::HostError が発生)。statement はすべて同じバインディングから作る必要があります。Ruby のトランザクションブロックはなく、batch がトランザクションの API です。
API
Cloudflare::D1
prepare(sql)→ Statement- A reusable statement without parameters.
- パラメータなしの、使い回せる statement。
query(sql, *params)→ Statement- Same as
prepare(sql).bind(*params). prepare(sql).bind(*params)と同じ。batch(statements)→ Array<Result>- Runs a non-empty Array of statements atomically.
- 空でない statement の配列をアトミックに実行します。
Cloudflare::D1::Statement
bind(*params)→ Statement- A new statement with these parameters.
- このパラメータを持つ新しい statement。
run→ Result- Rows plus D1 metadata. Use for writes.
- 行と D1 のメタデータ。書き込みに使います。
rows→ Array<Row>- Same as
run.rows. run.rowsと同じ。first(column = nil)→ Row | value | nil- First row, or one of its columns when
column(String or Symbol) is given. - 最初の行。
column(String か Symbol)を指定するとその列の値。 raw(column_names: false)→ Array<Array>- Rows as Arrays; with
column_names: truethe first element lists the column names. - 行を配列で返します。
column_names: trueなら先頭に列名の配列が入ります。 sql,params- The frozen SQL and parameters.
- 凍結済みの SQL とパラメータ。
Cloudflare::D1::Result
success?,rows,meta- Success flag, Array of Row, and the raw metadata Hash.
- 成功フラグ、Row の配列、生のメタデータ Hash。
changes,last_row_id,changed_db?- Rows changed, the last inserted rowid, and whether the database was modified.
- 変更行数、最後に挿入された rowid、データベースが変更されたか。
duration,rows_read,rows_written- Execution time in milliseconds and row counters from D1.
- 実行時間(ミリ秒)と D1 の行カウンタ。
Limits制約
- Parameters:
nil, String, Integer within ±253−1, finite Float,true,false. Hash, Array, Symbol, BLOB, and BigInt raiseArgumentError.パラメータ:nil、String、±253−1 以内の Integer、有限の Float、true、false。Hash、Array、Symbol、BLOB、BigInt はArgumentError。 - SQL must be a non-empty String without NUL bytes. Requests and responses are limited to 8 MiB of JSON.SQL は NUL バイトを含まない空でない String。リクエストとレスポンスは JSON で最大 8 MiB。
- Not available:
exec, query builders or models, D1 Sessions (read replication), BLOB parameters.未対応:exec、クエリビルダやモデル、D1 Sessions(リードレプリケーション)、BLOB パラメータ。
cloudflare-d1.md ↗examples/d1-todo ↗Cloudflare: D1 Worker API ↗
DATA
Workers KV
A global key-value store for data that is read often and written rarely. Values are binary-safe Strings and can expire after a TTL.
読み込みが多く書き込みが少ないデータ向けの、グローバルな Key-Value ストアです。値はバイナリセーフな String で、TTL を付けて期限切れにできます。
- Ruby
Cloudflare::KV- wrangler.jsonc
kv_namespaces[].binding- Resolve取得
env["cloudflare.env"].CACHE_KV
Configure設定
{
"kv_namespaces": [
{ "binding": "CACHE_KV", "id": "<namespace-id>" }
]
}wrangler dev uses a local namespace. Wrangler can also provision the remote namespace on the first deploy and record its id in the configuration.
wrangler dev ではローカルの namespace が使われます。Wrangler は初回デプロイ時にリモートの namespace を作成し、id を設定に書き込むこともできます。
Read and write読み書き
kv = env["cloudflare.env"].CACHE_KV
kv.put("greeting", "Hello from PicoRuby") # => nil once the write is accepted
kv.put("session:abc", token, ttl: 3600) # expires in one hour
kv.get("greeting") # => "Hello from PicoRuby"
kv.get("missing") # => nilPattern: cache an upstream APIパターン: 外部 API のキャッシュ
def self.weather(env)
kv = env["cloudflare.env"].CACHE_KV
key = "weather:tokyo"
cached = kv.get(key)
return cached if cached
response = Cloudflare.fetch("https://api.example.com/weather/tokyo")
kv.put(key, response.body, ttl: 600) if response.status == 200
response.body
endPattern: JSON valuesパターン: JSON を保存する
kv.put("user:1", JSON.generate({ "name" => "Alice", "plan" => "pro" }))
raw = kv.get("user:1")
user = raw && JSON.parse(raw)KV is eventually consistent: a write is visible at once where it was made, but can take a minute or more to reach other locations. Don't build counters or locks on it.
KV は結果整合性です。書き込みはその場所ではすぐ見えますが、他のロケーションに届くまで 1 分以上かかることがあります。カウンタやロックには使わないでください。
API
get(key)→ String | nil- The exact stored bytes, or
nil. - 保存されたバイト列そのまま、または
nil。 put(key, value, ttl: nil)→ nil- Writes
value.ttlis a relative expiration in seconds; omit it to keep the value forever. valueを書き込みます。ttlは秒単位の相対的な有効期限で、省略すると無期限です。
Limits制約
- Only
getandput. Delete, list, metadata, absolute expiration, and bulk operations are not available yet, and there is nosetalias.使えるのはgetとputだけです。削除、一覧、メタデータ、絶対時刻での期限、一括操作はまだなく、setという別名もありません。 ttlmust be an Integer of at least 60; anything else raisesArgumentErrorbefore the call is made.ttlは 60 以上の Integer でなければならず、それ以外は呼び出し前にArgumentErrorになります。- Keys: non-empty valid UTF-8, not
.or.., at most 512 bytes. Values: at most 8 MiB (lower than the KV platform maximum).キー: 空でない正しい UTF-8 で、.や..は不可、最大 512 バイト。値: 最大 8 MiB(KV プラットフォームの上限より小さい値です)。
DATA
R2
S3-compatible object storage. Upload Strings or the request stream, inspect metadata, list and delete keys, and serve object bodies without buffering them in Ruby.
S3 互換のオブジェクトストレージです。String やリクエストのストリームをアップロードし、メタデータの確認、キーの一覧・削除を行い、オブジェクトのボディを Ruby でバッファせずに配信できます。
- Ruby
Cloudflare::R2- wrangler.jsonc
r2_buckets[].binding- Resolve取得
env["cloudflare.env"].BUCKET
Configure設定
{
"r2_buckets": [
{ "binding": "BUCKET", "bucket_name": "my-bucket" }
]
}Uploadアップロード
bucket = env["cloudflare.env"].BUCKET
object = bucket.put(
"greetings/hello.txt",
"Hello from PicoRuby\n",
httpMetadata: { contentType: "text/plain; charset=utf-8" },
customMetadata: { source: "worker" }
)
object.key # => "greetings/hello.txt"
object.size # => 20
object.etag # => "a1b2c3..." (unquoted; http_etag is the quoted form)Strings are sent as raw bytes, so binary data is preserved. Options use R2's JavaScript names (httpMetadata, customMetadata, onlyIf, range, storageClass, …) and must be JSON-compatible; values that need a JavaScript Headers, Date, or ArrayBuffer are not supported.
String は生のバイト列として送られるので、バイナリも壊れません。オプションには R2 の JavaScript での名前(httpMetadata、customMetadata、onlyIf、range、storageClass など)を使い、JSON 互換である必要があります。JavaScript の Headers、Date、ArrayBuffer が必要な値には対応していません。
Stream the request body into R2リクエストボディをそのまま R2 へ
class App
def self.call(env)
return [405, { "content-type" => "text/plain" }, ["use PUT"]] unless env["REQUEST_METHOD"] == "PUT"
object = env["cloudflare.env"].BUCKET.put(
"uploads/latest.bin",
env["rack.input"],
httpMetadata: { contentType: env["CONTENT_TYPE"] || "application/octet-stream" }
)
[201, { "content-type" => "text/plain" }, [object.etag]]
end
endPassing an unread rack.input as the value hands the request stream to R2 without copying it through Wasm. It raises ArgumentError if the input was already read, and the input cannot be read afterwards. The request-body limit (1 MiB by default) still applies, and R2 needs to know the length, so clients should send Content-Length.
未読の rack.input を値に渡すと、リクエストのストリームを Wasm にコピーせずに R2 へ渡します。すでに読んだ入力を渡すと ArgumentError になり、渡した後の入力は読めません。リクエストボディの上限(デフォルト 1 MiB)はこの場合も適用されます。また R2 は長さを知る必要があるため、クライアントは Content-Length を送ってください。
Serve an objectオブジェクトを配信する
class App < Sinatra::Base
get "/files/:name" do
object = env["cloudflare.env"].BUCKET.get("files/#{params[:name]}")
halt 404, "not found" unless object
content_type object.http_metadata["contentType"] || "application/octet-stream"
headers "etag" => object.http_etag
env["cloudflare.hijack"] = object.body
body []
end
endobject.body is a StreamDescriptor, so the bytes flow from R2 to the client without entering Ruby. Read small objects in Ruby with object.body.read_all(max_bytes: …) instead.
object.body は StreamDescriptor なので、バイトは Ruby を経由せずに R2 からクライアントへ流れます。小さなオブジェクトを Ruby で読みたいときは object.body.read_all(max_bytes: …) を使います。
Ranges and preconditions範囲指定と条件付き取得
part = bucket.get("videos/intro.mp4", range: { offset: 0, length: 1_048_576 })
part.range # the range R2 returned
object = bucket.get("report.pdf", onlyIf: { etagDoesNotMatch: known_etag })
object.body # => nil when the precondition failed (metadata only)get returns nil when the key does not exist. When an onlyIf precondition fails it returns the object's metadata with body == nil.
キーが存在しなければ get は nil を返します。onlyIf の条件を満たさない場合は、body == nil のメタデータだけのオブジェクトを返します。
Metadata, listing, deletingメタデータ・一覧・削除
meta = bucket.head("greetings/hello.txt") # R2::Object without body, or nil
meta.custom_metadata # => {"source" => "worker"}
listing = bucket.list(prefix: "greetings/", limit: 100)
keys = listing.objects.map { |object| object.key }
listing = bucket.list(prefix: "greetings/", cursor: listing.cursor) if listing.truncated?
folders = bucket.list(prefix: "files/", delimiter: "/").delimited_prefixes
bucket.delete("greetings/hello.txt")
bucket.delete(["a.txt", "b.txt"]) # several keys in one callAPI
Cloudflare::R2
put(key, value, options = {})→ R2::Objectvalueis a String or an unreadrack.input.valueは String か未読のrack.input。get(key, options = {})→ R2::Object | nilbodyis a StreamDescriptor, ornilwhen a precondition failed.bodyは StreamDescriptor。条件を満たさなかった場合はnil。head(key)→ R2::Object | nil- Metadata only.
- メタデータのみ。
list(options = {})→ R2::Listing- Options such as
prefix,limit,cursor,delimiter,include. prefix、limit、cursor、delimiter、includeなどのオプション。delete(key_or_keys)→ nil- A String or a non-empty Array of Strings.
- String、または空でない String の配列。
Cloudflare::R2::Object
key,size,version,etag,http_etag- Identity and size.
http_etagis quoted, ready for anetagheader. - 識別情報とサイズ。
http_etagは引用符付きで、そのままetagヘッダに使えます。 http_metadata,custom_metadata→ Hash- Metadata with R2's camelCase keys, e.g.
"contentType". - R2 の camelCase キーのメタデータ(例:
"contentType")。 uploaded,range,storage_class,raw- Upload time as an ISO 8601 String, the returned range, the storage class, and the full metadata Hash.
- ISO 8601 文字列のアップロード日時、返された範囲、ストレージクラス、メタデータ全体の Hash。
body→ StreamDescriptor | nil- Only set on objects returned by
get. getが返したオブジェクトにだけ設定されます。
Cloudflare::R2::Listing
objects,truncated?,cursor,delimited_prefixes- Objects on this page, whether more pages exist, the cursor for the next page, and common prefixes when
delimiteris used. - このページのオブジェクト、続きがあるか、次ページ用のカーソル、
delimiter指定時の共通プレフィックス。
Limits制約
- Keys must be Strings and options JSON-compatible Hashes; otherwise
ArgumentError.キーは String、オプションは JSON 互換の Hash でなければArgumentError。 - Multipart uploads and
Headers/Date/ArrayBufferoption values are not available.マルチパートアップロードと、Headers/Date/ArrayBufferのオプション値には未対応。 - A body can be streamed to the client or read in Ruby, not both. When streaming, do not set
content-length.ボディはクライアントへ流すか Ruby で読むかのどちらか一方だけです。流す場合はcontent-lengthを設定しないでください。
AI
Workers AI
Run models on Cloudflare's GPUs with a JSON-in, JSON-out call. Typed helpers cover text generation and embeddings, and streaming output can go straight to the browser.
Cloudflare の GPU 上でモデルを実行します。入力も出力も JSON です。テキスト生成と埋め込みには型付きのヘルパーがあり、ストリーミング出力はそのままブラウザへ流せます。
- Ruby
Cloudflare::AI- wrangler.jsonc
ai.binding- Resolve取得
env["cloudflare.env"].AI
Configure設定
{
"ai": { "binding": "AI" }
}A Worker has at most one AI binding. Inference always runs on Cloudflare — also under wrangler dev — and counts toward your usage.
AI バインディングは 1 つの Worker に 1 つだけです。推論は wrangler dev でも常に Cloudflare 上で実行され、利用量に計上されます。
Generate textテキストを生成する
ai = env["cloudflare.env"].AI
result = ai.generate("@cf/meta/llama-3.1-8b-instruct", {
"messages" => [
{ "role" => "system", "content" => "You are a concise assistant." },
{ "role" => "user", "content" => "What is PicoRuby?" },
],
})
result.response # => "PicoRuby is ..."
result.usage # => {"prompt_tokens" => 24, "completion_tokens" => 60, ...} or nilA single "prompt" => "…" works too. Input keys follow each model's schema in the Workers AI catalog.
"prompt" => "…" だけでも使えます。入力のキーは Workers AI カタログにある各モデルのスキーマに従います。
Embeddings埋め込み
embedded = ai.embed("@cf/baai/bge-base-en-v1.5", { "text" => ["Ruby", "WebAssembly"] })
embedded.count # => 2
embedded.dimensions # => 768
embedded.first # => [0.0123, -0.0456, ...]
embedded.vectors # => every vector, in input orderAny model: run任意のモデル: run
result = ai.run("@cf/meta/llama-3.1-8b-instruct", { "prompt" => "Hello" })
result["response"]
# Per-call options, e.g. route the request through AI Gateway
result = ai.run(
"@cf/meta/llama-3.1-8b-instruct",
{ "prompt" => "Hello" },
{ "gateway" => { "id" => "my-gateway" } }
)run returns the model's JSON response as plain Hashes and Arrays, so it works for any model whose output is JSON. generate and embed call run and then check the response shape — they never guess the task from the model name. Only run accepts the options argument.
run はモデルの JSON レスポンスを普通の Hash と Array で返すので、出力が JSON のモデルなら何でも使えます。generate と embed は run を呼んだ後にレスポンスの形を検証するだけで、モデル名からタスクを推測することはありません。オプション引数を受け取るのは run だけです。
Stream to the browserブラウザへストリーミング
class App < Sinatra::Base
post "/chat" do
question = JSON.parse(env["rack.input"].read)["question"]
stream = env["cloudflare.env"].AI.generate("@cf/meta/llama-3.1-8b-instruct", {
"messages" => [{ "role" => "user", "content" => question }],
"stream" => true,
})
content_type "text/event-stream"
headers "cache-control" => "no-cache"
env["cloudflare.hijack"] = stream
body []
end
endWith "stream" => true, run and generate return a StreamDescriptor instead of a result. The original server-sent events — data: {"response":"…"} lines ending with data: [DONE] — flow from Workers AI to the client, and a client disconnect cancels the inference. The ai-stream example shows the browser side.
"stream" => true を指定すると、run と generate は結果の代わりに StreamDescriptor を返します。元の Server-Sent Events(data: {"response":"…"} の行が続き、data: [DONE] で終わる)が Workers AI からクライアントへ流れ、クライアントが切断すると推論もキャンセルされます。ブラウザ側の実装は ai-stream のサンプルを参照してください。
API
Cloudflare::AI
run(model, input = {}, options = {})→ Hash | Array | StreamDescriptor- The parsed JSON response, or a descriptor when
input["stream"]is true. - パース済みの JSON レスポンス。
input["stream"]が true ならディスクリプタ。 generate(model, input = {})→ TextGenerationResult | StreamDescriptor- Requires a
"response"key in the result. - 結果に
"response"キーが必要です。 embed(model, input = {})→ EmbeddingResult- Requires
"data"and a two-item"shape". Always buffered. "data"と 2 要素の"shape"が必要です。常にバッファされます。
TextGenerationResult · EmbeddingResult
response,usage,raw- Generated text, the token usage Hash (or
nil), and the full response. - 生成されたテキスト、トークン使用量の Hash(または
nil)、レスポンス全体。 vectors,first,count,dimensions,shape,pooling,raw- All vectors, the first vector,
shape[0],shape[1], the shape, the pooling method (ornil), and the full response. - 全ベクトル、最初のベクトル、
shape[0]、shape[1]、shape、プーリング方式(またはnil)、レスポンス全体。
Limits制約
modelmust be a non-empty String;inputandoptionsmust be JSON-serializable Hashes (ArgumentError).modelは空でない String、inputとoptionsは JSON にできる Hash(違えばArgumentError)。- A rejected inference raises
Cloudflare::HostError; a non-JSON result or one that doesn't match a helper's shape raisesCloudflare::ProtocolError.推論の失敗はCloudflare::HostError、JSON でない結果やヘルパーの想定と違う形の結果はCloudflare::ProtocolError。
cloudflare-ai.md ↗examples/ai-stream ↗Cloudflare: model catalog ↗
AI
Vectorize
A vector database for semantic search and retrieval-augmented generation. Store embeddings with metadata, then query by vector or by ID.
セマンティック検索や RAG(検索拡張生成)のためのベクトルデータベースです。埋め込みをメタデータと一緒に保存し、ベクトルや ID で検索します。
- Ruby
Cloudflare::Vectorize- wrangler.jsonc
vectorize[].binding- Resolve取得
env["cloudflare.env"].VECTOR_INDEX
Configure設定
npx wrangler vectorize create documents --dimensions=768 --metric=cosine
npx wrangler vectorize create-metadata-index documents --property-name=category --type=string{
"vectorize": [
{ "binding": "VECTOR_INDEX", "index_name": "documents", "remote": true }
]
}The index dimensions must match your embedding model (768 for @cf/baai/bge-base-en-v1.5). Filtering on a metadata property needs a metadata index for it. "remote": true lets wrangler dev use the real index, since Vectorize has no local simulator.
インデックスの次元数は埋め込みモデルと一致させます(@cf/baai/bge-base-en-v1.5 なら 768)。メタデータで絞り込むには、そのプロパティのメタデータインデックスが必要です。Vectorize にはローカル版がないため、"remote": true で wrangler dev から実際のインデックスを使います。
Store vectorsベクトルを保存する
cf = env["cloudflare.env"]
text = "PicoRuby is a small Ruby for microcontrollers and WebAssembly."
vector = cf.AI.embed("@cf/baai/bge-base-en-v1.5", { "text" => [text] }).first
cf.VECTOR_INDEX.upsert([{
"id" => "doc-1",
"values" => vector,
"metadata" => { "category" => "ruby", "text" => text },
"namespace" => "docs",
}]) # => {"mutationId" => "..."}insert leaves existing IDs untouched; upsert overwrites them. Both return Cloudflare's mutation response. Mutations are applied asynchronously, so a new vector may take a few seconds to show up in queries.
insert は既存の ID を変更せず、upsert は上書きします。どちらも Cloudflare の mutation レスポンスを返します。変更は非同期に反映されるため、追加したベクトルが検索に出るまで数秒かかることがあります。
Query検索する
result = cf.VECTOR_INDEX.query(
vector,
top_k: 5,
return_metadata: :all,
namespace: "docs",
filter: { "category" => "ruby" }
)
sources = result["matches"].map do |match|
{ "id" => match["id"], "score" => match["score"], "text" => match["metadata"]["text"] }
end
similar = cf.VECTOR_INDEX.query_by_id("doc-1", top_k: 3)Results are Cloudflare's JSON as a Hash with "count" and "matches". return_metadata is :none (default), :indexed, or :all; return_values: true also returns the vectors.
結果は Cloudflare の JSON をそのまま Hash にしたもので、"count" と "matches" を持ちます。return_metadata は :none(デフォルト)、:indexed、:all のいずれかで、return_values: true を指定するとベクトル自体も返します。
Pattern: retrieval-augmented generationパターン: RAG
def self.answer(env)
cf = env["cloudflare.env"]
question = JSON.parse(env["rack.input"].read)["question"]
query_vector = cf.AI.embed("@cf/baai/bge-base-en-v1.5", { "text" => [question] }).first
matches = cf.VECTOR_INDEX.query(query_vector, top_k: 3, return_metadata: :all)["matches"]
context = matches.map { |match| match["metadata"]["text"] }.join("\n\n")
env["cloudflare.hijack"] = cf.AI.generate("@cf/meta/llama-3.1-8b-instruct", {
"messages" => [
{ "role" => "system", "content" => "Answer only from this context:\n\n" + context },
{ "role" => "user", "content" => question },
],
"stream" => true,
})
[200, { "content-type" => "text/event-stream" }, []]
endInspect and delete確認と削除
cf.VECTOR_INDEX.get_by_ids(["doc-1"]) # => [{"id" => "doc-1", "values" => [...], ...}]
cf.VECTOR_INDEX.delete_by_ids(["doc-1"]) # => mutation response
cf.VECTOR_INDEX.describe # => dimensions, vector count, ...API
query(vector, top_k: 5, return_values: false, return_metadata: :none, namespace: nil, filter: nil)→ Hash- Nearest neighbours of
vector(an Array of numbers). vector(数値の配列)の近傍を検索します。query_by_id(id, …)→ Hash- Same options, using a stored vector as the query.
- 同じオプションで、保存済みのベクトルを検索キーにします。
insert(vectors),upsert(vectors)→ Hash- Arrays of Hashes with
"id","values", and optional"metadata"and"namespace". "id"、"values"、任意の"metadata"と"namespace"を持つ Hash の配列。get_by_ids(ids)→ Array,delete_by_ids(ids)→ Hash,describe→ Hash- Fetch or delete by ID, and describe the index.
- ID での取得・削除と、インデックス情報の取得。
Limits制約
top_kis 1–100, or at most 50 withreturn_values: trueorreturn_metadata: :all(enforced by Cloudflare).top_kは 1〜100。return_values: trueかreturn_metadata: :allの場合は最大 50(Cloudflare 側で検査)。- Buffered and JSON-only: requests that can't be serialized raise
ArgumentError; responses that aren't JSON raiseCloudflare::ProtocolError.バッファ型で JSON のみ。シリアライズできないリクエストはArgumentError、JSON でないレスポンスはCloudflare::ProtocolError。
cloudflare-vectorize.md ↗examples/rag-stream ↗Cloudflare: Vectorize ↗
MESSAGING
Queues
Move work out of the request. A producer sends UTF-8 text messages; a consumer in the same Worker receives them in batches and acknowledges or retries each one.
処理をリクエストの外へ逃がします。プロデューサが UTF-8 のテキストメッセージを送り、同じ Worker 内のコンシューマがバッチで受け取って、1 件ずつ確定(ack)または再試行(retry)します。
- Ruby
Cloudflare::Queue,Cloudflare::QueueConsumer::Base- wrangler.jsonc
queues.producers,queues.consumers- Resolve取得
env["cloudflare.env"].EVENTS_QUEUE
Configure設定
{
"queues": {
"producers": [{ "binding": "EVENTS_QUEUE", "queue": "events" }],
"consumers": [{ "queue": "events", "max_batch_size": 10 }]
}
}Produce送信する
class App
def self.call(env)
event = { "type" => "signup", "email" => "[email protected]" }
env["cloudflare.env"].EVENTS_QUEUE.send(JSON.generate(event))
[202, { "content-type" => "text/plain" }, ["queued"]]
end
endsend takes one UTF-8 String and returns nil once the queue has accepted it. Encode structured data as JSON yourself.
send は UTF-8 の String を 1 つ受け取り、キューが受け付けた時点で nil を返します。構造化データは自分で JSON にエンコードしてください。
Queue#send shadows Ruby's Object#send on queue objects. Use __send__ or public_send if you need reflection.
キューオブジェクトでは Queue#send が Ruby の Object#send を隠します。リフレクションが必要なら __send__ か public_send を使ってください。
Consume受信する
class EventConsumer < Cloudflare::QueueConsumer::Base
def call(_env)
current_batch.messages.each do |message|
begin
event = JSON.parse(message.body)
bindings.DB.query("INSERT INTO events (id, type) VALUES (?1, ?2)", message.id, event["type"]).run
message.ack
rescue Cloudflare::HostError
message.retry(delay_seconds: 30)
end
end
end
end
Rackup::Handler::CloudflareWorker.run(App) # HTTP requests
Cloudflare::Queues.run(EventConsumer) # queue batchesRegister the consumer next to the Rack app in the same program. Inside call, bindings is the Cloudflare::Environment and current_batch the current batch; both are cleared when the batch is done.
コンシューマは Rack アプリと同じプログラムに並べて登録します。call の中では bindings が Cloudflare::Environment、current_batch が現在のバッチで、どちらもバッチの処理が終わるとクリアされます。
- Returning normally acknowledges every message that was not explicitly retried.正常に return すると、明示的に retry しなかったメッセージはすべて確定されます。
- Raising an exception makes Cloudflare retry the whole batch.例外を投げると、Cloudflare がバッチ全体を再試行します。
- Per-message
ack/retrytake precedence overack_all/retry_all.メッセージ単位のack/retryはack_all/retry_allより優先されます。 message.attemptsstarts at 1 and grows with each delivery — use it to give up on messages that keep failing.message.attemptsは 1 から始まり配信のたびに増えます。失敗し続けるメッセージを諦める判断に使えます。
Logging from a consumerコンシューマからログを出す
def call(_env)
# ... settle messages ...
[:info, { "queue" => current_batch.queue, "count" => current_batch.messages.size }, "batch processed"]
endReturning [level, metadata, message] — level :debug, :info, :warn, or :error, a JSON-serializable Hash, and a String — writes a Worker log. Any other return value is ignored. The return value never settles messages.
[level, metadata, message](level は :debug / :info / :warn / :error、JSON にできる Hash、String)を返すと Worker のログに出力されます。それ以外の戻り値は無視されます。戻り値でメッセージが確定されることはありません。
Consumer middlewareコンシューマのミドルウェア
class AuditQueue
def initialize(app)
@app = app
end
def call(env)
# env["cloudflare.batch"] and env["cloudflare.env"] are available here
@app.call(env)
end
end
Cloudflare::Queues.run(EventConsumer) do
use AuditQueue
endMiddleware has Rack's callable shape and is built with Rack::Builder, but its env is the queue env (only cloudflare.env and cloudflare.batch), not an HTTP request.
ミドルウェアは Rack と同じ呼び出し形式で Rack::Builder により組み立てられますが、env は HTTP リクエストではなくキュー用の env(cloudflare.env と cloudflare.batch のみ)です。
API
Queue#send(message)→ nil- Sends one UTF-8 String.
- UTF-8 の String を 1 件送信します。
Cloudflare::Queues.run(consumer) { use Middleware }- Registers the batch handler for this Worker.
- この Worker のバッチハンドラを登録します。
QueueConsumer::Base#call(env),current_batch,bindings- Override
call; the helpers are available while it runs. callをオーバーライドします。ヘルパーは実行中に使えます。Batch#queue,messages,ack_all,retry_all(delay_seconds: nil)- Queue name, messages, and batch-wide settlement.
- キュー名、メッセージ、バッチ全体の確定・再試行。
Message#id,timestamp,body,attempts,ack,retry(delay_seconds: nil)timestampis milliseconds since the Unix epoch;bodyis a UTF-8 String.timestampは Unix エポックからのミリ秒、bodyは UTF-8 の String。
Limits制約
- Messages are UTF-8 text of at most 128 KiB, sent one at a time. JSON or byte content types, batch sends, send delays,
waitUntil, and metrics are not available yet.メッセージは最大 128 KiB の UTF-8 テキストで、1 件ずつ送信します。JSON やバイト列のコンテンツタイプ、一括送信、送信時の遅延、waitUntil、メトリクスには未対応です。 delay_secondsmust be a positive Integer (ArgumentError).delay_secondsは正の Integer(違えばArgumentError)。
STATE
Durable Objects
Named, strongly consistent storage. The current adapter treats each named instance as one JSON document: get it, change it in Ruby, and put it back.
名前付きで強い一貫性を持つストレージです。現在のアダプタは、名前ごとのインスタンスを 1 つの JSON ドキュメントとして扱います。取得して Ruby で変更し、書き戻します。
- Ruby
Cloudflare::DurableObject- wrangler.jsonc
durable_objects.bindings[].name- Resolve取得
env["cloudflare.env"].OBJECTS
Configure設定
{
"durable_objects": {
"bindings": [
{ "name": "OBJECTS", "class_name": "PicoRubyDurableObject" }
]
},
"migrations": [
{ "tag": "v1", "new_sqlite_classes": ["PicoRubyDurableObject"] }
]
}export { PicoRubyDurableObject } from "./generated/worker/runtime/index.js";The Durable Object class comes with the runtime — you don't write it in Ruby. Projects generated by picoruby-cloudflare already export it.
Durable Object のクラスはランタイムに含まれていて、Ruby で書く必要はありません。picoruby-cloudflare で生成したプロジェクトでは最初から export されています。
Read and write documentsドキュメントを読み書きする
store = Cloudflare::DurableObject.from_env(env, "OBJECTS")
store.put("user-1", { "name" => "Alice", "tags" => ["ruby"] })
profile = store.get("user-1") # => Cloudflare::DurableObject::POJO, or nil
profile["name"] # => "Alice"
profile.is_a?(Hash) # => trueEach name selects one Durable Object instance, which stores exactly one value. get returns nil if nothing was stored, a POJO (a Hash subclass) for a JSON object, or an Array for a JSON array. Symbol keys are accepted when writing but come back as Strings.
名前ごとに 1 つの Durable Object インスタンスが選ばれ、そこにちょうど 1 つの値が保存されます。get は何も保存されていなければ nil、JSON オブジェクトなら POJO(Hash のサブクラス)、JSON 配列なら Array を返します。書き込み時は Symbol キーも使えますが、読み戻すと String になります。
Custom objects with to_pojoto_pojo で独自オブジェクトを保存
class Cart
def initialize(items)
@items = items
end
def to_pojo
{ "items" => @items, "count" => @items.size }
end
end
store.put("cart-42", Cart.new(["book", "pen"]))
store.get("cart-42")["count"] # => 2Read-modify-write読んで、変えて、書き戻す
store = env["cloudflare.env"].OBJECTS
visits = store.get("page:/home") || { "count" => 0 }
visits["count"] += 1
store.put("page:/home", visits)get and put are two separate calls. Two requests can read the same value before either writes, and the last write wins. Use D1 (UPDATE … SET count = count + 1) when no update may be lost.
get と put は別々の呼び出しです。2 つのリクエストがどちらも書き込む前に同じ値を読むことがあり、後の書き込みが勝ちます。更新を失えない場合は D1(UPDATE … SET count = count + 1)を使ってください。
API
get(name)→ POJO | Array | nil- The stored document of the instance called
name. nameという名前のインスタンスに保存されたドキュメント。put(name, value)- Stores a POJO, Hash, Array, or any object responding to
to_pojo, replacing the previous value. - POJO、Hash、Array、または
to_pojoに応答するオブジェクトを保存し、前の値を置き換えます。
Limits制約
- Values may contain only
nil, booleans, Strings, Integers, Floats, Arrays, and Hashes with String or Symbol keys. Other objects and circular references raiseArgumentError.値に含められるのはnil、真偽値、String、Integer、Float、Array、String か Symbol をキーにした Hash だけです。それ以外のオブジェクトや循環参照はArgumentError。 - Names are 1–1024 bytes; payloads are at most 1 MiB.名前は 1〜1024 バイト、ペイロードは最大 1 MiB。
- Only get/put of one JSON value per instance is exposed. Custom Durable Object classes, alarms, WebSockets, and the storage API are not.公開されているのはインスタンスごとに 1 つの JSON 値の get / put だけです。独自の Durable Object クラス、アラーム、WebSocket、ストレージ API は使えません。
IDENTITY
Cloudflare Access
Rack middleware that looks up the signed-in Cloudflare Access user and puts their identity in env["cloudflare.identity"].
Cloudflare Access でサインインしているユーザーを問い合わせ、その情報を env["cloudflare.identity"] に入れる Rack ミドルウェアです。
- Ruby
Rack::Cloudflare::Access- wrangler.jsonc
vars.CF_ACCESS_TEAM- Rack env
env["cloudflare.identity"]
Configure設定
{
"vars": { "CF_ACCESS_TEAM": "my-team" }
}Put the Worker behind an Access application first. The team name is the my-team in my-team.cloudflareaccess.com, not a URL.
まず Worker を Access アプリケーションで保護してください。チーム名は my-team.cloudflareaccess.com の my-team の部分で、URL ではありません。
Protect an appアプリを保護する
app = Rack::Builder.new do
use Rack::Cloudflare::Access # reads CF_ACCESS_TEAM; or pass team: "my-team"
run lambda { |env|
identity = env["cloudflare.identity"]
[200, { "content-type" => "text/plain" }, ["Hello, #{identity.email}"]]
}
end
Rackup::Handler::CloudflareWorker.run(app)On every request the middleware reads the CF_Authorization cookie, asks Access for the identity, and calls your app only on success. Identities are never cached between requests. Otherwise it answers itself:
ミドルウェアはリクエストごとに CF_Authorization Cookie を読み、Access にユーザー情報を問い合わせ、成功した場合だけアプリを呼びます。ユーザー情報はリクエスト間でキャッシュされません。失敗時はミドルウェア自身が応答します。
| Statusステータス | When条件 |
|---|---|
503 | The team name is missing or invalid.チーム名が未設定、または不正。 |
401 | No or malformed cookie, or Access answered 401/403.Cookie がない・不正、または Access が 401/403 を返した。 |
502 | Network error, another HTTP status, or invalid identity JSON.ネットワークエラー、その他の HTTP ステータス、または不正なユーザー情報 JSON。 |
The identity objectユーザー情報オブジェクト
identity = env["cloudflare.identity"] # Cloudflare::AccessIdentity
identity.email # => "[email protected]"
identity.user_uuid # => "8c6a..."
identity.raw_data # => the full identity JSON (groups, idp, ...)Calling it directly直接呼び出す
token = Rack::Request.new(env).cookies["CF_Authorization"]
begin
identity = Cloudflare::Access.get_identity(token, team: "my-team")
rescue Cloudflare::Access::Unauthorized
# Access answered 401 or 403
endThis decodes the identity that Access returns. It does not verify the JWT signature, issuer, audience, or expiry locally, and service tokens are not supported. Keep the Access application in front of the Worker, and add token validation if your deployment requires it.
これは Access が返したユーザー情報をデコードするだけです。JWT の署名・発行者・audience・有効期限をローカルで検証することはなく、サービストークンにも対応していません。Worker の前段に Access アプリケーションを置いたままにし、必要ならトークン検証を追加してください。
API
use Rack::Cloudflare::Access, team: nil- Without
team:, readsCF_ACCESS_TEAMon each request. Alias ofCloudflare::Access, defined when Rack is loaded. team:を省略するとリクエストごとにCF_ACCESS_TEAMを読みます。Cloudflare::Accessの別名で、Rack が読み込まれているときに定義されます。Cloudflare::Access.get_identity(token, team:)→ AccessIdentity- Raises
ArgumentError,Cloudflare::Access::Unauthorized,Cloudflare::HostError, orCloudflare::ProtocolError. ArgumentError、Cloudflare::Access::Unauthorized、Cloudflare::HostError、Cloudflare::ProtocolErrorを投げます。AccessIdentity#email,user_uuid,raw_data- Convenience readers and the full JSON Hash.
- よく使う値と、JSON 全体の Hash。
HOST API
Fetch
Outbound HTTP(S) through the Worker's own fetch. Request and response bodies are buffered UTF-8 text.
Worker 自身の fetch を使った外向きの HTTP(S) 通信です。リクエストとレスポンスのボディはバッファされた UTF-8 テキストです。
- Ruby
Cloudflare.fetch- wrangler.jsonc
- —
- Returns戻り値
Cloudflare::FetchResponse
Call a JSON APIJSON API を呼ぶ
token = ENV.fetch("API_TOKEN")
response = Cloudflare.fetch(
"https://api.example.com/v1/items",
method: "POST",
headers: {
"authorization" => "Bearer #{token}",
"content-type" => "application/json",
},
body: JSON.generate({ "name" => "PicoRuby" })
)
if response.status == 201
item = JSON.parse(response.body)
else
# HTTP error statuses are returned, not raised
endThe responseレスポンス
response = Cloudflare.fetch("https://example.com/")
response.status # => 200
response.headers["content-type"] # => "text/html; charset=utf-8" — names are lowercase
response.body # => "<!doctype html>..."API
Cloudflare.fetch(url, method: "GET", headers: {}, body: nil)→ FetchResponse- Method and header values are Strings;
bodyis a String ornil. - メソッドとヘッダ値は String、
bodyは String かnil。 FetchResponse#status,headers,body- Integer status, Hash of lowercase header names, and the body String.
- Integer のステータス、小文字のヘッダ名をキーにした Hash、ボディの String。
Limits制約
http://andhttps://URLs only, without embedded credentials, at most 8192 bytes.http://とhttps://の URL のみ。認証情報の埋め込みは不可、最大 8192 バイト。- Redirects are not followed: any 3xx response raises
Cloudflare::HostError.リダイレクトは追いません。3xx のレスポンスはCloudflare::HostErrorになります。 - 10-second timeout; response bodies up to 1 MiB; encoded options up to 1 MiB.タイムアウトは 10 秒。レスポンスボディは最大 1 MiB、エンコード後のオプションも最大 1 MiB。
- UTF-8 text only — no binary or streaming bodies. Invalid UTF-8 raises
Cloudflare::ProtocolError. Error messages never contain URLs, credentials, or bodies.UTF-8 テキストのみで、バイナリやストリーミングのボディには未対応。不正な UTF-8 はCloudflare::ProtocolError。エラーメッセージに URL・認証情報・ボディは含まれません。
HOST API
Web Crypto
Cryptographically secure randomness and AES-GCM from the Workers Web Crypto API — not a PicoRuby pseudo-random generator.
Workers の Web Crypto API による暗号論的に安全な乱数と AES-GCM です。PicoRuby の疑似乱数ではありません。
- Ruby
SecureRandom,Crypto- wrangler.jsonc
- —
- Algorithmアルゴリズム
:AES_GCM
Random values乱数
SecureRandom.random_bytes # => 16 random bytes (binary String)
SecureRandom.random_bytes(32) # => 32 random bytes
SecureRandom.hex(16) # => "3f9c0a..." — 32 hex characters
SecureRandom.random_number # => Float in [0.0, 1.0)Encrypt and decrypt暗号化と復号
key = [ENV.fetch("DATA_KEY_HEX")].pack("H*") # 64 hex characters => 32-byte AES-256 key
iv, ciphertext = Crypto.encrypt(:AES_GCM, key, "private data")
plain = Crypto.decrypt(:AES_GCM, key, iv, ciphertext) # => "private data"encrypt generates a fresh 12-byte IV on every call and returns it with the ciphertext, which includes the 16-byte authentication tag. Store both. decrypt raises RuntimeError if the key, IV, or ciphertext was altered.
encrypt は呼び出しごとに新しい 12 バイトの IV を生成し、16 バイトの認証タグを含む暗号文と一緒に返します。両方を保存してください。鍵・IV・暗号文のいずれかが改変されていると、decrypt は RuntimeError を投げます。
Keys are raw bytes. Generate one once — for example openssl rand -hex 32 | npx wrangler secret put DATA_KEY_HEX — and decode it as above. A key created per request cannot decrypt anything on the next request.
鍵は生のバイト列です。一度だけ生成して(例: openssl rand -hex 32 | npx wrangler secret put DATA_KEY_HEX)、上のようにデコードして使います。リクエストごとに作った鍵では、次のリクエストで何も復号できません。
API
SecureRandom.random_bytes(n = 16)→ String,SecureRandom.hex(n = 16)→ Stringnrandom bytes, or2nhexadecimal characters.nバイトの乱数、または2n文字の 16 進文字列。SecureRandom.random_number→ Float- Uniform in [0.0, 1.0). Takes no arguments.
- [0.0, 1.0) の一様乱数。引数は取りません。
Crypto.encrypt(:AES_GCM, key, plaintext)→ [iv, ciphertext]keyis 16, 24, or 32 raw bytes.keyは 16・24・32 バイトの生の鍵。Crypto.decrypt(:AES_GCM, key, iv, ciphertext)→ String- The plaintext, or
RuntimeErrorwhen authentication fails. - 平文。認証に失敗すると
RuntimeError。