-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmjml.go
305 lines (236 loc) · 6.93 KB
/
mjml.go
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package mjml
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"sync"
"time"
"github.com/andybalholm/brotli"
"github.com/jackc/puddle/v2"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
)
//go:embed wasm/mjml.wasm.br
var wasm []byte
var (
runtime wazero.Runtime
compiled wazero.CompiledModule
results *sync.Map
resourcePool *puddle.Pool[api.Module]
)
func init() {
ctx := context.Background()
results = &sync.Map{}
br := brotli.NewReader(bytes.NewReader(wasm))
decompressed, err := io.ReadAll(br)
if err != nil {
panic(fmt.Sprintf("Error decompressing wasm file: %s", err))
}
runtime = wazero.NewRuntime(ctx) // TODO: this should be closed
if _, err := wasi_snapshot_preview1.Instantiate(ctx, runtime); err != nil {
panic(fmt.Sprintf("Error instantiating wasi snapshot preview 1: %s", err))
}
err = registerHostFunctions(ctx, runtime)
if err != nil {
panic(fmt.Sprintf("Error registering host functions: %s", err))
}
compiled, err = runtime.CompileModule(ctx, decompressed)
if err != nil {
panic(fmt.Sprintf("Error compiling wasm module: %s", err))
}
resourcePool, err = newResourcePool(10)
if err != nil {
panic(fmt.Sprintf("Error creating resource pool: %s", err))
}
go periodicallyRemoveIdleResources(resourcePool)
}
func SetMaxWorkers(maxSize int32) error {
oldPool := resourcePool
newPool, err := newResourcePool(maxSize)
if err != nil {
return fmt.Errorf("error creating new resource pool: %w", err)
}
resourcePool = newPool
oldPool.Close()
return nil
}
type jsonResult struct {
HTML string `json:"html"`
Error *Error `json:"error,omitempty"`
}
// ToHTML converts a string containing mjml to HTML while using any of the optionally provided options
func ToHTML(ctx context.Context, mjml string, toHTMLOptions ...ToHTMLOption) (string, error) {
data := map[string]interface{}{
"mjml": mjml,
}
o := options{
data: map[string]interface{}{},
}
for _, opt := range toHTMLOptions {
opt(o)
}
if len(o.data) > 0 {
data["options"] = o.data
}
inputBytes := bytes.NewBuffer([]byte{})
encoder := json.NewEncoder(inputBytes)
encoder.SetEscapeHTML(false)
err := encoder.Encode(data)
if err != nil {
return "", fmt.Errorf("error encoding input data: %w", err)
}
jsonInput := inputBytes.String()
jsonInputLen := uint64(len(jsonInput))
var (
module *puddle.Resource[api.Module]
tries int
)
for {
tries++
var err error
module, err = resourcePool.Acquire(ctx)
if err != nil {
if tries >= 30 {
return "", fmt.Errorf("unable to accquire wasm module after 30 tries: %w", err)
}
if err == puddle.ErrClosedPool {
time.Sleep(1 * time.Millisecond)
continue
}
return "", fmt.Errorf("error accquiring wasm module: %w", err)
}
break
}
defer module.Release()
mod, ok := module.Value().(api.Module)
if !ok {
return "", errors.New("pool resource is not an api.Module")
}
deallocate := mod.ExportedFunction("deallocate")
allocate := mod.ExportedFunction("allocate")
run := mod.ExportedFunction("run_e")
memory := mod.Memory()
allocation, err := allocate.Call(ctx, jsonInputLen)
if err != nil {
return "", fmt.Errorf("error allocating memory: %w", err)
}
if len(allocation) != 1 {
return "", errors.New("invalid input pointer allocated")
}
inputPtr := allocation[0]
defer deallocate.Call(ctx, inputPtr)
if !memory.Write(uint32(inputPtr), []byte(jsonInput)) {
return "", fmt.Errorf("error writing input to memory: %w", err)
}
ident, err := randomIdentifier()
if err != nil {
return "", fmt.Errorf("error generating identifier: %w", err)
}
resultCh := make(chan []byte, 1)
results.Store(ident, resultCh)
defer results.Delete(ident)
_, err = run.Call(ctx, inputPtr, jsonInputLen, uint64(ident))
if err != nil {
return "", fmt.Errorf("error calling run: %w", err)
}
result := <-resultCh
res := jsonResult{}
err = json.Unmarshal(result, &res)
if err != nil {
return "", fmt.Errorf("error decoding result json: %w", err)
}
if res.Error != nil {
return "", *res.Error
}
return res.HTML, nil
}
func registerHostFunctions(ctx context.Context, r wazero.Runtime) error {
_, err := r.NewHostModuleBuilder("env").
NewFunctionBuilder().
WithFunc(returnResult).
WithParameterNames("ptr", "len", "ident").
Export("return_result").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32) uint32 {
panic("get_static_file is unimplemented")
}).
Export("get_static_file").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("request_set_field is unimplemented")
}).
Export("request_set_field").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32, _ uint32) {
panic("resp_set_header is unimplemented")
}).
Export("resp_set_header").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32) uint32 {
panic("cache_get is unimplemented")
}).
Export("cache_get").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("add_ffi_var is unimplemented")
}).
Export("add_ffi_var").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32) uint32 {
panic("get_ffi_result is unimplemented")
}).
Export("get_ffi_result").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32) {
panic("return_error is unimplemented")
}).
Export("return_error").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("fetch_url is unimplemented")
}).
Export("fetch_url").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("graphql_query is unimplemented")
}).
Export("graphql_query").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("db_exec is unimplemented")
}).
Export("db_exec").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("cache_set is unimplemented")
}).
Export("cache_set").
NewFunctionBuilder().
WithFunc(func(_ uint32, _ uint32, _ uint32, _ uint32) uint32 {
panic("request_get_field is unimplemented")
}).
Export("request_get_field").
NewFunctionBuilder().
WithFunc(func(ctx context.Context, m api.Module, ptr uint32, size uint32, level uint32, ident uint32) {
panic("log_msg is unimplemented")
}).
Export("log_msg").
Instantiate(ctx)
return err
}
// returnResult is defined with a reflective signature instead of
// api.GoModuleFunc because it isn't called frequently.
func returnResult(ctx context.Context, m api.Module, ptr uint32, len uint32, ident uint32) {
if ch, ok := results.Load(int32(ident)); ok {
result, ok := m.Memory().Read(ptr, len)
resultCh, isResultCh := ch.(chan []byte)
if ok && isResultCh {
resultCh <- result
}
}
}