| 1 | package core |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/binary" |
| 6 | "errors" |
| 7 | "math" |
| 8 | "unicode/utf8" |
| 9 | ) |
| 10 | |
| 11 | // InitialBlock is literal text. Level zero is a paragraph, 1..6 a heading. |
| 12 | type InitialBlock struct { |
| 13 | Text string |
| 14 | Level uint8 |
| 15 | } |
| 16 | |
| 17 | // InitialUpdate builds a fresh document in the real core and returns its wire |
| 18 | // update. Its handle is never exposed or reused, even after a trap or timeout. |
| 19 | func (r *Runtime) InitialUpdate(ctx context.Context, guid string, clientID uint64, blocks []InitialBlock) ([]byte, error) { |
| 20 | if clientID > math.MaxUint32 { |
| 21 | return nil, errors.New("core: initial client id limit") |
| 22 | } |
| 23 | if len(blocks) > 200 { |
| 24 | return nil, errors.New("core: initial block limit") |
| 25 | } |
| 26 | raw := make([]byte, 0) |
| 27 | total := 0 |
| 28 | for _, block := range blocks { |
| 29 | total += len(block.Text) |
| 30 | if block.Level > 6 || !utf8.ValidString(block.Text) || total > 128<<10 { |
| 31 | return nil, errors.New("core: invalid initial block") |
| 32 | } |
| 33 | raw = append(raw, block.Level) |
| 34 | raw = binary.BigEndian.AppendUint32(raw, uint32(len(block.Text))) |
| 35 | raw = append(raw, block.Text...) |
| 36 | } |
| 37 | h, err := r.NewDoc(ctx, guid, clientID) |
| 38 | if err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 | defer h.Close(ctx) |
| 42 | ptr, err := allocIn(ctx, r.callTimeout, h.mod, uint64(len(raw))) |
| 43 | if err != nil { |
| 44 | return nil, err |
| 45 | } |
| 46 | defer freeIn(ctx, r.callTimeout, h.mod, ptr, uint64(len(raw))) |
| 47 | if !h.mod.Memory().Write(uint32(ptr), raw) { |
| 48 | return nil, errors.New("core: initial memory write") |
| 49 | } |
| 50 | result, err := callGuest(ctx, r.callTimeout, h.mod.ExportedFunction("docs_core_initialize"), h.handle, ptr, uint64(len(raw))) |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | if len(result) != 1 || int32(result[0]) != 0 { |
| 55 | return nil, errors.New("core: initial content refused") |
| 56 | } |
| 57 | // No retry through Handle.read: its recovery log is intentionally empty. |
| 58 | // Read directly and discard the whole handle on any uncertain outcome. |
| 59 | out, err := readOn(ctx, r.callTimeout, h.mod, h.handle, "snapshot") |
| 60 | if err != nil { |
| 61 | return nil, err |
| 62 | } |
| 63 | if len(out) > 1<<20 { |
| 64 | return nil, errors.New("core: initial output limit") |
| 65 | } |
| 66 | return []byte(out), nil |
| 67 | } |
| 68 | |