Class: Cloudflare::DurableObjectNamespace

Inherits:
Object
  • Object
show all
Defined in:
lib/cloudflare_workers/durable_object.rb

Overview

Wraps a DurableObjectNamespace binding (env.COUNTER). The binding object itself is opaque; we only need three methods from it —idFromName, newUniqueId, get — but we also expose a high-level ‘get_by_name` helper because “get a stub by name” is the most common call site and the unwrapped form requires two steps.

Instance Method Summary collapse

Constructor Details

#initialize(js) ⇒ DurableObjectNamespace

Returns a new instance of DurableObjectNamespace.



79
80
81
# File 'lib/cloudflare_workers/durable_object.rb', line 79

def initialize(js)
  @js = js
end

Instance Method Details

#get(id) ⇒ Object

Get a stub for an id (or a DurableObjectId wrapper).



106
107
108
109
110
# File 'lib/cloudflare_workers/durable_object.rb', line 106

def get(id)
  js_ns = @js
  js_id = id.is_a?(DurableObjectId) ? id.js_id : id
  DurableObjectStub.new(`#{js_ns}.get(#{js_id})`)
end

#get_by_name(name) ⇒ Object

Convenience: derive id-from-name and return the stub in one call.

stub = env_ns.get_by_name('global-counter')
resp = stub.fetch('/inc').__await__


116
117
118
# File 'lib/cloudflare_workers/durable_object.rb', line 116

def get_by_name(name)
  get(id_from_name(name))
end

#id_from_name(name) ⇒ Object

Hash-derived DurableObjectId. Two calls with the same ‘name` in the same namespace return equal ids, so `get_by_name(“foo”)` is the idiomatic “single-writer per name” pattern.



86
87
88
89
# File 'lib/cloudflare_workers/durable_object.rb', line 86

def id_from_name(name)
  js_ns = @js
  DurableObjectId.new(`#{js_ns}.idFromName(#{name.to_s})`)
end

#id_from_string(hex) ⇒ Object

Parse a hex id string back into a DurableObjectId. Matches the Workers ‘namespace.idFromString(hex)` method.



100
101
102
103
# File 'lib/cloudflare_workers/durable_object.rb', line 100

def id_from_string(hex)
  js_ns = @js
  DurableObjectId.new(`#{js_ns}.idFromString(#{hex.to_s})`)
end

#new_unique_idObject

Random unique DurableObjectId. Used when the caller wants an ephemeral / request-scoped actor (e.g. one DO per user session).



93
94
95
96
# File 'lib/cloudflare_workers/durable_object.rb', line 93

def new_unique_id
  js_ns = @js
  DurableObjectId.new(`#{js_ns}.newUniqueId()`)
end