-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathphoenix_wasm_app.exs
More file actions
244 lines (205 loc) Β· 6.19 KB
/
Copy pathphoenix_wasm_app.exs
File metadata and controls
244 lines (205 loc) Β· 6.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# Phoenix WASM App Example
#
# Demonstrates building a complete REST API using Firebird's
# WASM-accelerated Phoenix components.
#
# Run with: mix run examples/phoenix_wasm_app.exs
IO.puts("""
π₯ Firebird Phoenix WASM - REST API Example
#{String.duplicate("β", 50)}
Building a User API with:
β’ WASM routing (compiled route table)
β’ WASM template rendering
β’ WASM form validation
β’ Elixir middleware (auth, logging, timing)
β’ Error handling
""")
# ββ Step 1: Start all WASM components ββ
IO.puts("π¦ Loading 11 WASM components...")
{:ok, components} = Firebird.Phoenix.start()
IO.puts(" β
All components loaded\n")
# ββ Step 2: Build the request handler ββ
alias Firebird.Phoenix.{RequestHandler, Middleware, Conn}
{:ok, handler} = RequestHandler.new()
# Add middleware
handler =
handler
|> RequestHandler.use_middleware(Middleware.request_id())
|> RequestHandler.use_middleware(Middleware.timer())
|> RequestHandler.use_middleware(Middleware.logger())
|> RequestHandler.use_middleware(Middleware.default_header("x-powered-by", "Firebird WASM"))
# Define routes
handler =
handler
|> RequestHandler.route("GET", "/", "PageController.index")
|> RequestHandler.route("GET", "/api/users", "UserController.index")
|> RequestHandler.route("GET", "/api/users/:id", "UserController.show")
|> RequestHandler.route("POST", "/api/users", "UserController.create")
|> RequestHandler.route("PUT", "/api/users/:id", "UserController.update")
|> RequestHandler.route("DELETE", "/api/users/:id", "UserController.delete")
|> RequestHandler.route("GET", "/api/health", "HealthController.check")
# Define templates
handler =
handler
|> RequestHandler.template(
"PageController.index",
200,
"text/html",
"<html><body><h1>Welcome to Firebird Phoenix WASM</h1><p>A REST API powered by WebAssembly</p></body></html>"
)
|> RequestHandler.template(
"UserController.index",
200,
"application/json",
~s([{"id":"1","name":"Alice"},{"id":"2","name":"Bob"},{"id":"3","name":"Charlie"}])
)
|> RequestHandler.template(
"UserController.show",
200,
"application/json",
~s({"id":"{{id}}","name":"User {{id}}","email":"user{{id}}@example.com"})
)
|> RequestHandler.template(
"UserController.create",
201,
"application/json",
~s({"status":"created","message":"User created successfully"})
)
|> RequestHandler.template(
"UserController.update",
200,
"application/json",
~s({"status":"updated","id":"{{id}}"})
)
|> RequestHandler.template(
"UserController.delete",
200,
"application/json",
~s({"status":"deleted","id":"{{id}}"})
)
|> RequestHandler.template(
"HealthController.check",
200,
"application/json",
~s({"status":"ok","uptime":"100%","wasm":"active"})
)
IO.puts("π£οΈ Routes defined:")
IO.puts(" GET /")
IO.puts(" GET /api/users")
IO.puts(" GET /api/users/:id")
IO.puts(" POST /api/users")
IO.puts(" PUT /api/users/:id")
IO.puts(" DELETE /api/users/:id")
IO.puts(" GET /api/health")
IO.puts("")
# ββ Step 3: Process requests ββ
IO.puts("π¨ Processing requests...\n")
requests = [
{"GET", "/", "Homepage"},
{"GET", "/api/health", "Health check"},
{"GET", "/api/users", "List users"},
{"GET", "/api/users/42", "Get user 42"},
{"POST", "/api/users", "Create user"},
{"PUT", "/api/users/7", "Update user 7"},
{"DELETE", "/api/users/3", "Delete user 3"},
{"GET", "/api/nonexistent", "404 test"}
]
for {method, path, description} <- requests do
{time_us, {:ok, conn}} =
:timer.tc(fn ->
RequestHandler.handle(handler, method, path)
end)
status_emoji =
cond do
conn.status in 200..299 -> "β
"
conn.status == 404 -> "π"
true -> "β"
end
body_preview =
if conn.resp_body do
String.slice(conn.resp_body, 0..60)
|> String.replace("\n", " ")
else
"(empty)"
end
IO.puts("#{status_emoji} #{method} #{path}")
IO.puts(" #{description}")
IO.puts(" Status: #{conn.status} | #{time_us}Β΅s")
IO.puts(" Body: #{body_preview}")
IO.puts("")
end
# ββ Step 4: Validator demo ββ
IO.puts("#{String.duplicate("β", 50)}")
IO.puts("π WASM Validator Demo\n")
{:ok, validator} = Firebird.Phoenix.Validator.start()
# Valid form
IO.puts(" Valid user registration:")
{:ok, result} =
Firebird.Phoenix.Validator.validate(
validator,
%{
"name" => "Alice Smith",
"email" => "alice@example.com",
"age" => "25",
"password" => "securepass123"
},
[
{:required, "name"},
{:required, "email"},
{:required, "password"},
{:type, "email", :email},
{:type, "age", :integer},
{:min_length, "password", 8}
]
)
IO.puts(" Result: #{inspect(result)}")
# Invalid form
IO.puts("\n Invalid user registration:")
{:ok, result} =
Firebird.Phoenix.Validator.validate(
validator,
%{
"name" => "A",
"email" => "not-email",
"age" => "abc"
},
[
{:required, "name"},
{:required, "email"},
{:required, "password"},
{:type, "email", :email},
{:type, "age", :integer},
{:min_length, "name", 2}
]
)
IO.puts(" Result: #{inspect(result)}")
Firebird.Phoenix.Validator.stop(validator)
# ββ Step 5: Benchmark ββ
IO.puts("\n#{String.duplicate("β", 50)}")
IO.puts("β‘ Performance Benchmark\n")
iterations = 1000
{total_us, _} =
:timer.tc(fn ->
for _ <- 1..iterations do
RequestHandler.handle(handler, "GET", "/api/users/42")
end
end)
avg = total_us / iterations
ops_per_sec = iterations / (total_us / 1_000_000)
IO.puts(" #{iterations} requests processed")
IO.puts(" Average: #{Float.round(avg / 1.0, 1)}Β΅s per request")
IO.puts(" Throughput: #{Float.round(ops_per_sec, 0)} req/sec")
# Cleanup
Firebird.Phoenix.stop(components)
IO.puts("""
#{String.duplicate("β", 50)}
π Demo complete!
This example demonstrated:
β
11 WASM modules loaded and working
β
Route matching via compiled WASM
β
Template rendering with variable substitution
β
Middleware pipeline (request_id, timer, logger)
β
Form validation via WASM
β
Error handling (404 responses)
β
Sub-millisecond request processing
""")