session

package
v0.8.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 37 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package session shares a local file in a pedit room.

Index

Constants

View Source
const MaxFiles = 20

MaxFiles is how many files one session shares, the first included.

Variables

View Source
var (
	// ErrRoomEnded: the room has ended or never opened (HTTP 410).
	ErrRoomEnded = errors.New("the room has ended")
	// ErrRelayTooOld: the relay has no status or keep change (HTTP 404).
	ErrRelayTooOld = errors.New("the relay is too old to report or change a room's keep; it needs an update")

	// ErrKeepForbidden: the relay, or Cloudflare Access in front of it, turned
	// the request away (HTTP 403, or a redirect to Access's login page); a
	// caller may retry with an Access token.
	ErrKeepForbidden = errors.New("the relay, or Cloudflare Access in front of it, refused the request")
	ErrKeepRefused   = errors.New("the relay refused the keep: the room is live, or the host is away, or the value is not allowed")
)
View Source
var ErrAmbiguousThread = errors.New("threads of several files have that id: name the file")

ErrAmbiguousThread means threads of several files have the id asked for.

View Source
var ErrBehindAccess = errors.New("Cloudflare Access sent us to its login page")

ErrBehindAccess means Cloudflare Access sent us to its login page: we sent no credentials, or Access did not accept them.

View Source
var ErrClientOutdated = errors.New("this pedit is too old for the server; update it")

ErrClientOutdated means the server speaks a newer protocol version than this pedit, which has to be updated.

View Source
var ErrHostAway = errors.New("the host is away: a comment link cannot comment until the host is back, and no room takes comments in the minutes before it is kept")

ErrHostAway means a guest's comment cannot reach the host now: the room is kept and the guest has a comment link, or the host dropped and the room is not kept (yet).

View Source
var ErrNoComments = errors.New("no file of the room offers comments")

ErrNoComments means no file of the room offers comments.

View Source
var ErrNoFile = errors.New("no file of the room at that path offers comments")

ErrNoFile means the room shares no file at that path, or it offers no comments.

View Source
var ErrNoSavedComments = errors.New("no comments are saved for it")

ErrNoSavedComments means no comments were saved for a file: none were made, or the host never ran on it.

View Source
var ErrNoTextAnchors = errors.New("only a text or Markdown file takes a thread on a range of its text")

ErrNoTextAnchors means the room's first file takes no thread on a range of its text: a table, whose threads sit on cells, or a canvas, on nodes.

View Source
var ErrNotHost = errors.New("only the host starts a thread on a range")

ErrNotHost means a write only the host makes.

View Source
var ErrRelayMaintenance = errors.New("the relay is closed for maintenance; try again later")

ErrRelayMaintenance means the relay is closed for maintenance.

View Source
var ErrRoomClosed = errors.New("the room is closed: the host left, or the link is wrong")

ErrRoomClosed means the room could not be joined because nobody hosts it: the host left, or the link is wrong.

View Source
var ErrRoomExpired = errors.New("the room has ended: it reached its time limit on the relay; ask the host to run pedit again for a new link")

ErrRoomExpired means the room reached its relay's time limit and has ended for good.

View Source
var ErrRoomFull = errors.New("the room is full: its relay takes only so many people at once; try again when someone leaves")

ErrRoomFull means the room already has as many guests as its relay allows.

View Source
var ErrServerOutdated = errors.New("the server is older than this pedit; ask whoever runs it to update it")

ErrServerOutdated means the server speaks an older protocol version than this pedit; whoever runs it has to update it.

View Source
var ErrTooLarge = errors.New("the shared file is too large to share; pedit shares files up to " + SizeLimit + " for now")

ErrTooLarge means the room's file grew too large to share.

View Source
var SizeLimit = fmt.Sprintf("about %d MiB", protocol.MaxFrameBytes>>20)

SizeLimit is how much pedit shares, as people read it: a room gets the whole state in one frame, which the relay caps at protocol.MaxFrameBytes.

Functions

func CloseKept added in v0.3.0

func CloseKept(ctx context.Context, opts KeptTextOptions) error

CloseKept takes in the edits of a room kept by the relay, writes them to the files, and ends the room, which removes its link and its record. Source changes made outside this session are refused rather than overwritten.

func PruneKept added in v0.3.0

func PruneKept(project string, notify func(int)) error

PruneKept removes, without asking the relay, the records in project of rooms past their deadline (by more than expiredGrace) and of the older kind of kept room, which was taken in by polling and can no longer be resumed. A record with a write to finish stays. It tells notify how many it removed.

func ReadSavedComments added in v0.5.1

func ReadSavedComments(projectDir, file string) (*meta.File, error)

ReadSavedComments reads the comments the host saved last for file, in the project at projectDir, as the host reads them: through the project's real directories, with the checks of meta.Parse. It writes nothing (docs/design/comments-cli.md, listing without a session).

func SetKeptGeneration added in v0.6.0

func SetKeptGeneration(project, room, generation string) error

SetKeptGeneration gives the record of a kept room the generation of the document that is now one history with it, if it has none. A record with a generation is left as it is.

Types

type CommentChange added in v0.5.1

type CommentChange struct {
	File string
	meta.Change
}

CommentChange is a change to the comments of one of the room's files, as the room shows its path (docs/design/comments-cli.md).

type ErrFileExists

type ErrFileExists struct{ Path string }

ErrFileExists means the copy was not written because a file of that name appeared in its directory, which pedit made empty.

func (*ErrFileExists) Error

func (e *ErrFileExists) Error() string

type FileThreads added in v0.5.1

type FileThreads struct {
	File    string
	Threads []meta.Shown
}

FileThreads are the threads on one of the room's files, as the room shows its path.

type JoinOptions

type JoinOptions struct {
	// URL is the share link, with the key in its fragment.
	URL        string
	Name       string
	WriteDelay time.Duration
	// Watch streams edits made to the copy outside pedit into the room. A
	// comment link edits nothing, so its copies are not watched.
	Watch bool
	// OnComments is as in Options.
	OnComments func(CommentChange)
	// Timeout bounds how long Join waits for the room's state; 15s by default.
	Timeout  time.Duration
	Header   http.Header
	Dial     protocol.Dialer
	OnStatus func(protocol.Status)
	// OnKept is called with the time a kept room stays open until, before
	// OnStatus reports it kept.
	OnKept   func(time.Time)
	OnPeople func([]string)
	// OnNotice and OnError are as in Options.
	OnNotice func(Notice)
	OnError  func(error)
	// OnMirrored is called for each other file the room shares, with the path
	// the host shows it at and the path of its copy beside the first, and why
	// it is not copied when it is not. Called one at a time.
	OnMirrored func(hostPath, path string, err error)
	// contains filtered or unexported fields
}

JoinOptions joins a room someone else hosts, as a browser would, and keeps a local copy of each text file it shares so any editor can work on it. The copies go in a new temporary directory, removed when the session stops, leaving nothing behind, like a browser tab. They are named by the guest (copyName), never as the host names them.

type KeptRoomStatus added in v0.8.1

type KeptRoomStatus struct {
	RoomStatus
	Room string
	// Origin is the relay the record names, also on an error from it.
	Origin string
	// Edit, Comment and Read are the fragments that follow '#' in the links;
	// Comment is empty when no file of the room offers comments.
	Edit, Comment, Read string
}

KeptRoomStatus is the status of a room that is kept without its host, and the fragments of its links.

func KeptStatus added in v0.8.1

func KeptStatus(ctx context.Context, project, room string, client *http.Client, header http.Header) (KeptRoomStatus, error)

KeptStatus reads the record of room in project and asks the relay about it, sending header besides the host's token (the record holds no Access token: a caller signed in to an Access-protected relay passes its own). A relay that says the room has ended gives ErrRoomEnded; the record is left as it is.

type KeptTextOptions added in v0.2.0

type KeptTextOptions struct {
	File, Project, Resume string
	// Keep, when positive, replaces the keep of the record on the connection
	// that takes the room in (see Options.Resume).
	Keep      time.Duration
	OnSkipped func(int)
	// OnImageError reports an image a kept text refers to that could not be
	// saved beside its file (once per image and file).
	OnImageError func(path string, err error)
	// Dial connects to the relay, to take in a live room (kept_away_resume.go).
	Dial protocol.Dialer
	// Source and Generation are those of a room shared from a source (see
	// Options): the host then leaves file 0 to the source.
	Source     Source
	Generation string
	// Prepare is for a room of another history than the document it is closed
	// into, which also owns file 0. Given the text the room started from and
	// the text it ends with, it builds the edit between them and returns the
	// Yjs update and the generation of the document, without changing the
	// document. The host records the update, then has it applied with
	// Reapply. Source and Prepare are exclusive.
	Prepare func(base, next string) (update []byte, generation string)
	// Reapply applies an update Prepare returned to the document, if its
	// generation is still the document's and the update then integrates
	// completely; it reports whether it did. Applying what the document
	// already has changes nothing, so a retry never delivers an edit twice.
	Reapply func(update []byte, generation string) bool
	// Saved is called after Source or Prepare has the edits, before the room is
	// ended: the owner saves its file there. An error leaves the room open.
	Saved func() error
}

KeptTextOptions says which kept room CloseKept, or the resume of a session, is about.

type KeptTextRecord added in v0.3.0

type KeptTextRecord struct {
	Room  string
	Paths []string // display paths of the shared files
	Files []string // their absolute paths on disk
	Until int64    // relay deadline in Unix ms; 0 if unknown
	// Generation and Origins are those of a room shared from pedit serve; a
	// record of pedit <file> has neither. State and Text are the first file's
	// document and the text it was last known to match.
	Generation string
	Origins    []string
	State      []byte
	Text       string
	// Pending is a text the file may hold instead of Text: a write in doubt.
	Pending *string
}

KeptTextRecord summarizes a resume record of a project, without its secrets.

func ListKeptText added in v0.3.0

func ListKeptText(project string) ([]KeptTextRecord, error)

ListKeptText returns the resume records of project, soonest deadline first. Records that cannot be parsed, and those of the older polling kind of kept room, are left out.

type Link struct {
	Access protocol.Access
	URL    string
}

Link is a link to the room the host can hand out.

type Notice added in v0.1.2

type Notice struct {
	Kind NoticeKind
	// File is the path of the shared file, or of the copy when joined.
	File string
	// Reason says why in a few words, for SaveFailed, ChangeHeld and
	// ImageNotSaved. It is the same each time the same cause comes back.
	Reason string
	// Details are more lines about Reason, such as each problem in a canvas.
	Details []string
	// Kept is the temporary name, beside File, a save is kept under, for
	// SaveKept.
	Kept string
	// Err is the error behind the notice, for diagnostics.
	Err error
}

Notice tells the user about a condition of the local file they can act on. Errors nobody can act on, or that clear by themselves, go to OnError.

type NoticeKind added in v0.1.2

type NoticeKind string

NoticeKind names a condition of the local file that the user can act on.

const (
	// SaveFailed means the file could not be saved, and could not when tried
	// again either. The edits are kept, and the save is tried again until it
	// lands.
	SaveFailed NoticeKind = "save-failed"
	// SaveRecovered means a save landed after SaveFailed.
	SaveRecovered NoticeKind = "save-recovered"
	// ChangeHeld means the file changed outside pedit into something pedit
	// cannot take in, so pedit does not save over it until it is fixed.
	ChangeHeld NoticeKind = "change-held"
	// HoldReleased means that after ChangeHeld, the file was fixed or put
	// back, and saving goes on.
	HoldReleased NoticeKind = "hold-released"
	// ImageNotSaved means an image someone pasted could not be saved beside
	// the file. They are told it was not added.
	ImageNotSaved NoticeKind = "image-not-saved"
	// SaveLost means a save made outside pedit while pedit wrote the file was
	// written into the file pedit's write replaced, and is lost. Only where
	// files cannot be exchanged, such as on Windows.
	SaveLost NoticeKind = "save-lost"
	// SaveKept means pedit moved aside what was in the file while it wrote it,
	// and could not put it back: a save made outside pedit may be in Kept.
	SaveKept NoticeKind = "save-kept"
	// CommentsOff means the file offers no comments in the room, for Reason,
	// such as being outside the project or its metadata not being readable.
	CommentsOff NoticeKind = "comments-off"
	// CommentsHeld means the file that keeps the comments of a shared file
	// (File) changed outside pedit, so pedit no longer saves comments to it.
	CommentsHeld NoticeKind = "comments-held"
)

type Options

type Options struct {
	File string
	// Root is the directory the paths of a room's files are shown relative
	// to, such as where pedit runs. A file outside it is shown by its name.
	// Empty: the first file's directory.
	Root string
	// Project is the directory whose .pedit/meta/ keeps the comments of the
	// files inside it (#121). Empty: no file offers comments.
	Project string
	// Server is the base URL of the pedit server, e.g. https://edit.piconic.ai
	Server string
	Name   string
	// Avatar is the URL of the host's picture, shown to the others.
	Avatar     string
	WriteDelay time.Duration
	// Watch streams edits made to the file outside pedit into the room.
	Watch bool
	// Header is sent with every request to the server, such as the Cloudflare
	// Access token of whoever signed in.
	Header     http.Header
	HTTPClient *http.Client
	Dial       protocol.Dialer
	OnStatus   func(protocol.Status)
	// OnPeople is called with the names of the other people in the room,
	// sorted, whenever someone joins, leaves or renames. Callbacks run in order
	// outside session locks and must not call Stop synchronously.
	OnPeople func([]string)
	// OnPeers is OnPeople with each person's name and access apart, sorted
	// the same way, including local source pages. It must not call Stop synchronously.
	OnPeers func([]Person)
	// OnSaved is called with the path, relative to File, of each image
	// someone pasted that was saved beside the file.
	OnSaved func(path string)
	// OnNotice is called, one at a time, with conditions of the file the
	// user can act on: a save that failed, or a change pedit cannot take in,
	// and when each ends. It must not call into the Session.
	OnNotice func(Notice)
	// OnError is called with errors nobody can act on, or that clear by
	// themselves, such as a dropped connection.
	OnError func(error)
	// OnComments is called, one at a time and in order, with each change to
	// the comments of the room's files once the session holds it, its own
	// included; not with the comments there when a file was added. It must
	// not call into the Session.
	OnComments func(CommentChange)
	// OnCommentsChanged is called when a comments doc, or the text its
	// anchors point into, was updated, so that PlacedThreads may differ. It
	// runs under the doc's lock: it must be quick, and must not call into the
	// Session.
	OnCommentsChanged func()

	// Keep asks the relay to keep the room open for this long after the host
	// leaves on purpose (docs/design/rooms-away.md), and has Start write the
	// record that pedit resume takes the room up again by. More are the files to
	// share with the first, so the record lists them all.
	Keep time.Duration
	More []string
	// Resume is the ID of a room Keep left a record of in Project: Start
	// takes in what was written while the host was away, then goes on
	// sharing the record's files in that room. File, More and Server are
	// the record's. A positive Keep then replaces the room's keep.
	Resume string
	// OnKeep is called with the seconds the relay keeps the room, which may be
	// less than asked, or 0 if it cannot keep it (it speaks version 5).
	OnKeep func(seconds int64)
	// OnSkipped is called with how many entries guests wrote that were
	// refused, in all; OnImageError with an image of a replayed edit that
	// could not be saved.
	OnSkipped    func(int)
	OnImageError func(path string, err error)

	// Source, when set, is the document the room shares, which the session
	// does not own: it never reads File for content, nor writes, watches or
	// saves it. File still names the file, for the room's path, its images
	// and its comments. Keep, Resume and More are refused with it.
	Source Source
	// BeforeRecord is called before a source's kept record is written, so
	// the source can save its file: the record keeps only a state the file
	// matches. It must not call into the Session.
	BeforeRecord func()
	// Generation is the generation of the document of the `pedit serve` that
	// shares it as a Source. A kept room's record carries it.
	Generation string
	// Origins are the page origins the relay lets embed the room, sent with
	// every connection of the host as X-Pedit-Origins.
	Origins []string
	// OnRoomAwareness is called with the awareness states of the room, and
	// their removals, for a Source's pages to show, with the access each was
	// heard with: one update holding one entry. It is not called for the
	// source's own pages nor for the host. It must not block nor call into
	// the Session.
	OnRoomAwareness func(id uint64, access protocol.Access, update []byte)
}

type Person added in v0.6.0

type Person struct {
	Name   string
	Access protocol.Access
	Local  bool
}

A Person is someone else in the room, with the access of their link.

type PlacedThread added in v0.8.2

type PlacedThread struct {
	meta.Shown
	// From and To are the place in the text, in UTF-16 code units, when
	// Placed: not for a thread on cells or a node, nor one whose text is gone.
	From, To int
	Placed   bool
}

PlacedThread is a thread of the first file, with where its anchor is now.

func PlaceSavedComments added in v0.8.6

func PlaceSavedComments(saved *meta.File, text string) []PlacedThread

PlaceSavedComments places saved threads in the current normalized text, using the same cleaning, ordering and anchors as a live session.

type RoomStatus added in v0.8.1

type RoomStatus struct {
	Keep    int64  `json:"keep"`
	Host    string `json:"host"`
	Ends    int64  `json:"ends"`
	LifeEnd int64  `json:"lifeEnd"`
}

RoomStatus is what the relay says of a room it keeps (GET /api/rooms/:id/keep, docs/design/rooms-away.md "Lifecycle"). Host is "here" or "away"; Ends and LifeEnd are Unix ms.

type Session

type Session struct {
	// URL is the share URL. Its fragment holds the key and must never be sent to the server.
	URL string
	Doc *crdt.Doc
	// Text is the shared text, or nil when the file is a canvas, shared as
	// nodes and edges.
	Text   *crdt.YText
	Client *protocol.Client
	// contains filtered or unexported fields
}

func Join

func Join(ctx context.Context, opts JoinOptions) (*Session, error)

Join enters the room at opts.URL, waits for its content and writes it to a copy (copyName). The returned Session mirrors the copy and the room both ways until Stop; Session.URL is the link joined.

func Start

func Start(ctx context.Context, opts Options) (*Session, error)

func (*Session) AddFile added in v0.1.12

func (s *Session) AddFile(file string) (protocol.FileEntry, error)

AddFile shares another file in the room, in a Y.Doc of its own, and tells the room its new list of files. The host names every file: nothing in the room can add one. It fails, changing nothing, when the file cannot be shared, or is already.

func (*Session) Comments added in v0.5.1

func (s *Session) Comments() []FileThreads

Comments lists the threads of every file that offers comments, as the browser lists them.

func (*Session) File

func (s *Session) File() string

File is the path of the shared file, or of the copy when the session joined a room.

func (*Session) Files added in v0.1.12

func (s *Session) Files() []protocol.FileEntry

Files lists the files the session shares, the first one first.

func (*Session) Fragments added in v0.6.0

func (s *Session) Fragments() (room, edit, comment, read string)

Fragments are the room's id and the fragments of its links, as they follow '#' in the links of `pedit <file>`: the edit secret, then the "c." and "r." parts. comment is empty when no file offers comments.

func (*Session) FromSource added in v0.6.0

func (s *Session) FromSource(update []byte) error

FromSource applies an update the source made to the room's doc. It reaches the room and is not handed back to the source. It returns with the update in the doc, so the last snapshot of a kept room (Stop) holds every update whose FromSource has returned: the caller stops feeding the session first, then calls Stop.

func (*Session) FromSourceAwareness added in v0.6.0

func (s *Session) FromSourceAwareness(id uint64, reader bool, update []byte) error

FromSourceAwareness sends the state of one of the source's pages, whose awareness client ID is id, to the room. update holds that one entry; a removal is one whose state is null. reader tells that the page may only read: its state is sent at read access.

func (*Session) KeepCopy added in v0.1.3

func (s *Session) KeepCopy()

KeepCopy makes Stop keep the temporary directory of the copies. Call it before Stop.

func (*Session) KeepStatus added in v0.8.1

func (s *Session) KeepStatus(ctx context.Context) (RoomStatus, error)

KeepStatus asks the relay about the room this session hosts.

func (*Session) KeptUntil added in v0.3.0

func (s *Session) KeptUntil() time.Time

KeptUntil is when the relay ends the room, if it keeps it now that the host has left, or the zero time if it does not.

func (s *Session) Links() []Link

Links are the links to the room with less access than the host's (#122): comment only, while some file offers comments, then read only. They come from the fragments the host's keys derive, and like URL hold secrets that must never be sent to the server.

func (*Session) PlacedThreads added in v0.8.2

func (s *Session) PlacedThreads() []PlacedThread

PlacedThreads lists the threads of the first file as the browser lists them, each with where its anchor is in the text now.

func (*Session) Relay added in v0.8.6

func (s *Session) Relay() string

Relay is the effective relay URL, including a resumed room's saved origin.

func (*Session) Reply added in v0.5.1

func (s *Session) Reply(file, thread, id, body string) (WriteResult, error)

Reply adds a comment to a thread, under id, signed with the session's name. file names the thread's file, or is empty to look in every file. A reply the thread holds already is not written again.

func (*Session) Resolve added in v0.5.1

func (s *Session) Resolve(file, thread string, resolved bool) (WriteResult, error)

Resolve resolves a thread, or reopens it.

func (*Session) SetKeep added in v0.8.1

func (s *Session) SetKeep(ctx context.Context, keep time.Duration) (RoomStatus, error)

SetKeep changes how long the relay keeps the room after the host leaves, while the host is here. The new keep (as the relay grants it) is what a later reconnect sends and what the record holds.

func (*Session) StartThread added in v0.8.2

func (s *Session) StartThread(thread, message string, from, to int, body string) (WriteResult, error)

StartThread starts a thread, under id thread, on [from, to) of the first file's text, in UTF-16 code units, with its first comment under id message, signed with the session's name (docs/design/embedding.md, "Comments from the app"). The host has it at once.

func (*Session) Stop

func (s *Session) Stop() error

Stop leaves the room and writes the final state to the files. It reports an error when the final state could not be saved.

func (*Session) Temporary

func (s *Session) Temporary() bool

Temporary reports whether the copy is removed when the session stops.

type Source added in v0.6.0

type Source interface {
	// State is the document's whole state as one v1 update.
	State() []byte
	// Apply hands the source a Yjs update made in the room. It is called
	// under the room client's lock, in order: it must not call into the
	// Session.
	Apply(update []byte) error
}

A Source is a document the session shares without owning it, such as the one `pedit serve` holds. The source stays the only owner of the doc and the only writer of the file: the session keeps a doc of its own, started from the source's state so both have one history, and the two exchange Yjs updates, each going to the other side once and never back.

type TooLargeError added in v0.1.3

type TooLargeError struct {
	File string
	// Size is the file's size in bytes.
	Size int
	// Shared is the size of the frame that would carry a canvas, whose
	// shared form is larger than its file; 0 for text.
	Shared int
}

TooLargeError means a file is too large to share: a room gets its whole state in one frame, which the relay caps at protocol.MaxFrameBytes.

func (*TooLargeError) Error added in v0.1.3

func (e *TooLargeError) Error() string

type WriteResult added in v0.5.1

type WriteResult struct {
	Delivered bool
}

WriteResult says how far a write from the command line got. Delivered is set once the host has it: at once for the host itself.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL