package core import ( "context" "encoding/binary" "errors" "math" "unicode/utf8" ) var ErrEditInvalid = errors.New("core: unsupported edit or coordinates") var ErrEditCollision = errors.New("core: editing client id already used") var ErrEditPending = errors.New("core: missing update dependencies") var ErrEditTooLarge = errors.New("core: edit limit exceeded") type BlockEdit struct { Index uint32 Delete uint32 Blocks []InitialBlock } // EditUpdate consumes and closes this private replay handle on every outcome. // It never recovers a failed guest mutation by replaying the pre-edit history. func (h *Handle) EditUpdate(ctx context.Context, edits []BlockEdit) ([]byte, error) { defer h.Close(ctx) if h.clientID == 0 || h.clientID > math.MaxUint32 || len(edits) == 0 || len(edits) > 32 { return nil, ErrEditInvalid } raw := binary.BigEndian.AppendUint32(nil, uint32(len(edits))) inserted, deleted, total := 0, uint64(0), 0 for i, e := range edits { if len(e.Blocks) > 200 || e.Delete > 200 || len(e.Blocks) == 0 && e.Delete == 0 || uint64(e.Index)+uint64(e.Delete) > math.MaxUint32 { return nil, ErrEditInvalid } if i > 0 && (e.Index >= edits[i-1].Index || uint64(e.Index)+uint64(e.Delete) > uint64(edits[i-1].Index)) { return nil, ErrEditInvalid } inserted += len(e.Blocks) deleted += uint64(e.Delete) if inserted > 200 || deleted > 200 { return nil, ErrEditTooLarge } raw = binary.BigEndian.AppendUint32(raw, e.Index) raw = binary.BigEndian.AppendUint32(raw, e.Delete) raw = binary.BigEndian.AppendUint32(raw, uint32(len(e.Blocks))) for _, b := range e.Blocks { total += len(b.Text) if b.Level > 6 || !utf8.ValidString(b.Text) { return nil, ErrEditInvalid } if total > 128<<10 { return nil, ErrEditTooLarge } raw = append(raw, b.Level) raw = binary.BigEndian.AppendUint32(raw, uint32(len(b.Text))) raw = append(raw, b.Text...) } } ptr, err := allocIn(ctx, h.rt.callTimeout, h.mod, uint64(len(raw))) if err != nil { return nil, err } defer freeIn(ctx, h.rt.callTimeout, h.mod, ptr, uint64(len(raw))) if !h.mod.Memory().Write(uint32(ptr), raw) { return nil, errors.New("core: edit input memory") } const cap = 1 << 20 out, err := allocIn(ctx, h.rt.callTimeout, h.mod, cap) if err != nil { return nil, err } defer freeIn(ctx, h.rt.callTimeout, h.mod, out, cap) result, err := callGuest(ctx, h.rt.callTimeout, h.mod.ExportedFunction("docs_core_edit"), h.handle, ptr, uint64(len(raw)), out, cap) if err != nil { return nil, err } if len(result) != 1 { return nil, errors.New("core: edit result") } n := int32(result[0]) switch n { case -6: return nil, ErrEditInvalid case -7: return nil, ErrEditCollision case -8: return nil, ErrEditTooLarge case -9: return nil, ErrEditPending } if n <= 0 || n > cap { return nil, errors.New("core: edit refused") } bytes, ok := h.mod.Memory().Read(uint32(out), uint32(n)) if !ok { return nil, errors.New("core: edit output memory") } return append([]byte(nil), bytes...), nil }