You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by ma...@apache.org on 2016/01/26 08:45:38 UTC

svn commit: r1726745 [1/4] - in /james/project/trunk: ./ client-guide/ home/ server-guide/ software/ spec/

Author: matthieu
Date: Tue Jan 26 07:45:37 2016
New Revision: 1726745

URL: http://svn.apache.org/viewvc?rev=1726745&view=rev
Log:
Squashed 'server/protocols/jmap/doc/specs/' content from commit 41cd59c

git-subtree-dir: server/protocols/jmap/doc/specs
git-subtree-split: 41cd59c19aa678b31e3c4262d7171b5f56d324fc

Added:
    james/project/trunk/README
    james/project/trunk/client-guide/
    james/project/trunk/client-guide/jmap-client-guide.mdwn
    james/project/trunk/home/
    james/project/trunk/home/faq.mdwn
    james/project/trunk/server-guide/
    james/project/trunk/server-guide/jmap-server-guide.mdwn
    james/project/trunk/software/
    james/project/trunk/software/software.mdwn
    james/project/trunk/spec/
    james/project/trunk/spec/account.mdwn
    james/project/trunk/spec/apimodel.mdwn
    james/project/trunk/spec/authentication.mdwn
    james/project/trunk/spec/calendar.mdwn
    james/project/trunk/spec/calendarevent.mdwn
    james/project/trunk/spec/calendareventlist.mdwn
    james/project/trunk/spec/contact.mdwn
    james/project/trunk/spec/contactgroup.mdwn
    james/project/trunk/spec/contactlist.mdwn
    james/project/trunk/spec/datamodel.mdwn
    james/project/trunk/spec/mailbox.mdwn
    james/project/trunk/spec/message.mdwn
    james/project/trunk/spec/messagelist.mdwn
    james/project/trunk/spec/push.mdwn
    james/project/trunk/spec/searchsnippet.mdwn
    james/project/trunk/spec/thread.mdwn
    james/project/trunk/spec/upload.mdwn

Added: james/project/trunk/README
URL: http://svn.apache.org/viewvc/james/project/trunk/README?rev=1726745&view=auto
==============================================================================
--- james/project/trunk/README (added)
+++ james/project/trunk/README Tue Jan 26 07:45:37 2016
@@ -0,0 +1,8 @@
+JSON Mail Access Protocol Specification (JMAP)
+----------------------------------------------
+
+This repository contains the specification for JMAP, a new JSON-based API for synchronising a mail client with a mail server. It is intended as a replacement for IMAP. The specification is based on the API currently used by the FastMail (https://www.fastmail.com) web app.  It aims to be compatible with the IMAP data model, so that it can be easily implemented on a server that currently supports IMAP, but allows for reduced data usage and more efficient synchronisation, bundling of requests for latency mitigation and is generally much easier to work with than IMAP.
+
+The pretty HTML version of the spec is hosted at http://jmap.io.
+
+Want to get involved? Join the mailing list at https://groups.google.com/forum/#!forum/jmap-discuss. Feedback is welcome: send your thoughts or comments on anything that is imprecise, incomplete, or could simply be done better in another way. Discussion is preferred prior to pull requests, except in the case of minor typos etc.!

Added: james/project/trunk/client-guide/jmap-client-guide.mdwn
URL: http://svn.apache.org/viewvc/james/project/trunk/client-guide/jmap-client-guide.mdwn?rev=1726745&view=auto
==============================================================================
--- james/project/trunk/client-guide/jmap-client-guide.mdwn (added)
+++ james/project/trunk/client-guide/jmap-client-guide.mdwn Tue Jan 26 07:45:37 2016
@@ -0,0 +1,653 @@
+Guide for client developers
+===========================
+
+This guide shows how you can use JMAP to efficiently minimise bandwidth usage and round trips whilst still giving the user a complete view of their mail. This is particularly relevant to clients on mobile devices, where there is not the space to store a complete cache of all messages, or for web clients where you often do not have a permanent cache at all and must efficiently start from scratch each time the app is loaded.
+
+A single login may have access to multiple accounts. In this guide I'm going to ignore this and just use the primary account, which I'm going to presume has full read-write mail access.
+
+## Cold boot
+
+When a user first logs in and you have no data cached for them, first call:
+
+    [
+        [ "getMailboxes", {}, "#0" ]
+    ]
+
+This will fetch the list of mailboxes (folders or labels) for the user, and the permissions and roles for each. Here's an example of the response you might receive:
+
+    [
+        [ "mailboxes", {
+            accountId: 'user@example.com',
+            state: "m123456789",
+            list: [
+                {
+                    id: "mailbox1",
+                    name: "Inbox",
+                    parentId: null,
+                    role: "inbox",
+                    mustBeOnlyMailbox: false,
+                    mayAddMessages: true,
+                    mayRemoveMessages: true,
+                    mayCreateChild: false,
+                    mayRenameMailbox: true,
+                    mayDeleteMailbox: false,
+                    totalMessages: 1424,
+                    unreadMessages: 3,
+                    totalThreads: 1213,
+                    unreadThreads: 2
+                },
+                {
+                    id: "mailbox2",
+                    name: "Sent",
+                    parentId: null,
+                    role: "sent",
+                    mustBeOnlyMailbox: false,
+                    mayAddMessages: true,
+                    mayRemoveMessages: true,
+                    mayCreateChild: false,
+                    mayRenameMailbox: true,
+                    mayDeleteMailbox: false,
+                    totalMessages: 41,
+                    unreadMessages: 0,
+                    totalThreads: 32,
+                    unreadThreads: 2
+                },
+                {
+                    id: "mailbox3",
+                    name: "Trash",
+                    parentId: null,
+                    role: "trash",
+                    mustBeOnlyMailbox: true,
+                    mayAddMessages: true,
+                    mayRemoveMessages: true,
+                    mayCreateChild: false,
+                    mayRenameMailbox: true,
+                    mayDeleteMailbox: false,
+                    totalMessages: 3,
+                    unreadMessages: 0,
+                    totalThreads: 2,
+                    unreadThreads: 0
+                },
+                {
+                    id: "mailbox4",
+                    name: "Awaiting Reply",
+                    parentId: "mailbox2",
+                    role: null,
+                    mustBeOnlyMailbox: false,
+                    mayAddMessages: true,
+                    mayRemoveMessages: true,
+                    mayCreateChild: true,
+                    mayRenameMailbox: true,
+                    mayDeleteMailbox: true,
+                    totalMessages: 0,
+                    unreadMessages: 0,
+                    totalThreads: 0,
+                    unreadThreads: 0
+                }
+            ],
+            notFound: null
+        }, "#0"]
+    ]
+
+In this (simple) example, the user has four mailboxes. Three at the top level (Inbox, Sent and Trash) and one submailbox of Sent called "Awaiting Reply". The first 3 have `role` attributes, so they are to be used for the designated system roles (these are much as you would expect, but see the spec for full details). Note, you should always use the `role` attribute, as names may be localised (or even different between different servers with the same language)!
+
+The Inbox, Sent and Awaiting Reply mailboxes all have `mustBeOnlyMailbox:false`. The Trash mailbox on the other hand has `mustBeOnlyMailbox:true`. This means that a message in the trash may not be in any other mailbox, and vice versa. However, a message belonging to the Sent mailbox could also be in, for example, the Awaiting Reply mailbox.
+
+The Sent mailbox has no unread messages, but 2 unread threads. This is not an error! A thread is considered unread if any of the messages in it are unread, even if those messages are actually in a different mailbox. In this case, the 3 unread messages in the Inbox must all be replies to messages in the Sent mailbox. Email clients will probably want to hide unread thread counts for mailboxes with a role of "sent" or "archive".
+
+Presuming the client defaults to showing the `role=inbox` mailbox, we now get the list of messages at the top of the mailbox, and the data for each one that we need to show it in the interface.
+
+    [
+        [ "getMessageList", {
+            filter: {
+                inMailboxes: [ "mailbox1" ]
+            },
+            sort: [ "date desc", "id desc" ]
+            collapseThreads: true,
+            position: 0,
+            limit: 10,
+            fetchThreads: true,
+            fetchMessages: true,
+            fetchMessageProperties: [
+                "threadId",
+                "mailboxId",
+                "isUnread",
+                "isFlagged",
+                "isAnswered",
+                "isDraft",
+                "hasAttachment",
+                "from",
+                "to",
+                "subject",
+                "date",
+                "preview"
+            ],
+            fetchSearchSnippets: false
+        }, "call1"]
+    ]
+
+This might return the following:
+
+    [
+        [ "messageList", {
+            accountId: 'user@example.com',
+            filter: {
+                inMailboxes: [ "mailbox1" ]
+            },
+            sort: [ "date desc", "id desc" ]
+            collapseThreads: true,
+            state: "m8231u341",
+            canCalculateUpdates: true,
+            position: 0,
+            total: 1213,
+            messageIds: [
+                "fm1u314",
+                "fm1u312",
+                "fm1u298",
+                "fm1u286",
+                "fm1u265",
+                "fm1u254",
+                "fm1u241",
+                "fm1u211",
+                "fm1u109",
+                "fm1u3"
+            ],
+            threadIds: [
+                "4f512aafed75e7fb",
+                "fed75e7fb4f512aa",
+                "75e7fb4f512aafed",
+                "512aafed75e7fb4f",
+                "fb4f512aafed75e7",
+                "2aafed75e7fb4f51",
+                "afed75fb4f512ae7",
+                "e7fb4f512aafed75",
+                "ed75e74f51fb2aaf",
+                "b4f5ed75e712aaff"
+            ]
+        }, "call1" ],
+        [ "threads", {
+            accountId: 'user@example.com',
+            state: "mc1264092",
+            list: [{
+                id: "4f512aafed75e7fb",
+                messageIds: [ "fm1u314" ]
+            }, {
+                id: "fed75e7fb4f512aa",
+                messageIds: [ "fm1u312", "fm2u12", "fm1u304" ]
+            },
+                … 8 more thread objects, omitted for brevity …
+            ],
+            notFound: null
+        }],
+        [ "messages", {
+            accountId: 'user@example.com',
+            state: "m815034",
+            list: [{
+                "id": "fm1u314",
+                "threadId": "4f512aafed75e7fb",
+                "mailboxIds": [ "mailbox1" ],
+                "isUnread": true,
+                "isFlagged": false,
+                "isAnswered": false,
+                "isDraft": false,
+                "hasAttachment": false,
+                "from": [
+                    { name: "Joe Bloggs", email: "joebloggs@fastmail.fm" }
+                ],
+                "to": [
+                    { name: "Jane Doe", email: "janedoe@fastmail.fm" }
+                ],
+                "subject": "Camping trip",
+                "date": "2014-07-24T15:04:51Z",
+                "preview": "Hey Joe. Fancy a trip out west next week? I hea…"
+            },
+            {
+                "id": "fm1u312",
+                "threadId": "fed75e7fb4f512aa",
+                "mailboxIds": [ "mailbox1" ],
+                "isUnread": false,
+                "isFlagged": true,
+                "isAnswered": false,
+                "isDraft": false,
+                "hasAttachment": true,
+                "from": [
+                    { name: "James Connor", email: "jamesconnorwork@fastmail.fm" }
+                ],
+                "to": [
+                    { name: "Jane Doe", email: "janedoe@fastmail.fm" },
+                    { name: "Joe Bloggs", email: "joebloggs@fastmail.fm" }
+                ],
+                "subject": "Re: I need the swallow velocity report ASAP",
+                "date": "2014-07-24T12:01:43Z",
+                "preview": "Come on you guys. How long can it take to do a simple scientif…"
+            },
+            {
+                "id": "fm2u12",
+                "threadId": "fed75e7fb4f512aa",
+                "mailboxIds": [ "mailbox2" ],
+                "isUnread": false,
+                "isFlagged": false,
+                "isAnswered": false,
+                "isDraft": false,
+                "hasAttachment": false,
+                "from": [
+                    { name: "Jane Doe", email: "janedoe@fastmail.fm" }
+                ],
+                "to": [
+                    { name: "James Connor", email: "jamesconnorwork@fastmail.fm" },
+                    { name: "Joe Bloggs", email: "joebloggs@fastmail.fm" }
+                ],
+                "subject": "Re: I need the swallow velocity report ASAP",
+                "date": "2014-07-24T11:32:15Z",
+                "preview": "It's on its way. Jane."
+            },
+                … more message objects, omitted for brevity …
+            ],
+            notFound: null
+        }, "call1" ]
+    ]
+
+We now have the header information for all the messages in the top 10 threads in the Inbox, plus a full list of mailboxes and their unread counts. Providing the screen cannot fit more than 10 messages without scrolling, this is sufficient to display a standard mail interface as though **all data was loaded**, even though we have only made 2 round trips to the server, and transferred minimal data. (Obviously, you can request more than 10 in the request if you need more to show the initial screen).
+
+## Paging in data as the interface is navigated
+
+In our example Inbox, there are 1213 threads, but so far we have only loaded in data for the first 10. As the user scrolls down, we need to page in the data for the section of the mailbox that becomes visible (and indeed, to avoid the user having to wait, it's advisable to preload a little way ahead too). This is just another call to `getMessageList`, as in the cold boot example, but with the `position` property changed to the index for the section required.
+
+Similarly, if we switch mailboxes, or want to do a search, we can use the same call as well. However, remember in JMAP the same message may appear in multiple mailboxes, so to avoid downloading the same data multiple times, it's advisable to just fetch the message list without also getting the message or thread objects (except in certain situations, such as the very first request; the exact heuristics for deciding between the two can be made arbitrarily clever and complex).
+
+    [
+        [ "getMessageList", {
+            filter: {
+                inMailboxes: [ "mailbox2" ]
+            },
+            sort: [ "date desc", "id desc" ]
+            collapseThreads: true,
+            position: 11,
+            limit: 10,
+            fetchThreads: false,
+            fetchMessages: false,
+            fetchMessageProperties: null,
+            fetchSearchSnippets: false
+        }, "call1"]
+    ]
+
+After the list has been returned, a second request can be made directly to `getThreads` with the thread ids (or to `getMessages` with the message ids) to fetch the ones you are missing.
+
+## Opening a thread
+
+So far we have only fetched the minimal amount of information we need to display a mailbox entry for a message or thread. When opening a thread from the mailbox, we now need to fetch the rest of the message details. Exactly what you wish to fetch depends on what information your client displays. Suppose we open the 2nd thread in the example Inbox above. I'm presuming we already know the list of message ids in the thread from the data received when we fetched the mailbox.
+
+    [
+        [ "getMessages", {
+            ids: [ "fm1u312", "fm2u12", "fm1u304" ],
+            properties: [
+                "threadId",
+                "mailboxIds",
+                "isUnread",
+                "isFlagged",
+                "isAnswered",
+                "isDraft",
+                "hasAttachment",
+                "from",
+                "to",
+                "cc",
+                "bcc",
+                "replyTo",
+                "subject",
+                "date",
+                "size",
+                "body",
+                "attachments",
+                "attachedMessages"
+            ]
+        }]
+    ]
+
+Alternatively, a client may want to just request the "rawUrl" property, then download the original RFC2822 message from the URL returned and parse it in the client.
+
+## Staying in sync
+
+Suppose a new message arrives, or the user performs some actions on their messages using a different client. A push notification comes in to indicate the state has changed on the server, or you get a response back to a method call with a different state string to the previous call. We now need efficiently work out exactly what has changed so that we can update the model in the client and keep it in sync, without throwing away all of our data and starting again.
+
+To efficiently stay in sync, we can call:
+
+    [
+        [ "getMailboxUpdates", {
+            sinceState: "m123456789",
+            fetchRecords: true,
+            fetchRecordProperties: null
+        }, "call1" ],
+        [ "getMessageListUpdates", {
+            filter: {
+                inMailboxes: [ "mailbox1" ]
+            },
+            sort: [ "date desc", "id desc" ]
+            collapseThreads: true,
+            sinceState: "m8231u341",
+            uptoMessageId: "fm1u3",
+            maxChanges: 100
+        }, "call2" ],
+        [ "getMessageUpdates", {
+            sinceState: "m815034"
+            maxChanges: 30,
+            fetchRecords: true,
+            fetchRecordProperties: [
+                "threadId",
+                "mailboxIds",
+                "isUnread",
+                "isFlagged",
+                "isAnswered",
+                "isDraft",
+                "hasAttachment",
+                "labels",
+                "from",
+                "to",
+                "subject",
+                "date",
+                "preview"
+            ]
+        }, "call3" ],
+        [ "getThreadUpdates", {
+            sinceState: "mc1264092"
+            maxChanges: 20,
+            fetchRecords: true
+        }, "call4" ]
+    ]
+
+This is a good example of multiple method calls combined into a single request. Let's have a look at what they are doing.
+
+1. `getMailboxUpdates`: This will return the ids of any mailboxes that have been created or modified (e.g. renamed, or have changed counts). It will also return the ids of any mailboxes that have been deleted. Because we set `fetchMailboxes == true`, any new or changed mailboxes will be fetched. If the server supports the `onlyCountsChanged` property of the mailboxes response, then we will only receive the counts properties for the changed mailboxes if that is the only change (the common case).
+2. `getMessageListUpdates`: All our message lists may have changed, so we must mark all of them as needing a refresh, and immediately refresh the one that is currently selected in the client (here, presuming the Inbox). We'll look at the response to this and how it is used to update the client cache below.
+3. `getMessageUpdates`: Gets the list of ids for all messages which have been added or modified, plus the list of messages which have been deleted. We have also specified `fetchMessages` and `fetchMessageProperties` arguments here to request the standard header information we need to display a message in a mailbox for any new/changed messages. This includes all mutable properties of a message, so is sufficient to bring any changed messages up to date.
+4. `getThreadUpdates`: Gets the list of threads which have had messages added or removed from the thread. We also fetch the `Thread` object for those threads that have changed.
+
+In each case, the `sinceState` argument comes from the response to our previous calls to get the records of that type.
+
+### Handling a standard response
+
+In the common case, not many changes will have occurred since we last synced with the server, and the data returned from this request will be sufficient to fully bring the client into sync with the server.
+
+The `maxChanges` argument prevents methods from returning huge volumes of data in the case where a large number of changes have been made. If we get a `tooManyChanges` error in response to one of our method calls then we will then have to do more work to get back in sync, as detailed below.
+
+Let's look at a common case example, where two new messages have been delivered to the Inbox and one other existing message has been marked as read. We might get back a response something like:
+
+    [
+        [ "mailboxUpdates", {
+            accountId: 'user@example.com',
+            oldState: "m123456789",
+            newState: "m123471231",
+            changed: [ "mailbox1" ],
+            removed: [],
+            onlyCountsChanged: true
+        }, "call1" ],
+        [ "mailboxes", {
+            accountId: 'user@example.com',
+            state: "m123471231"
+            list: [{
+                totalMessages: 1426,
+                unreadMessages: 4,
+                totalThreads: 1214,
+                unreadThreads: 3
+            }],
+            notFound: null
+        }, "call1" ],
+        [ "messageListUpdates", {
+            accountId: 'user@example.com',
+            filter: {
+                inMailboxes: [ "mailbox1" ]
+            },
+            sort: [ "date desc", "id desc" ]
+            collapseThreads: true,
+            oldState: "m8231u341",
+            newState: "m8239u342",
+            uptoMessageId: "fm1u3",
+            removed: [{
+                messageId: "fm1u241",
+                threadId:
+            }],
+            added: [{
+                messageId: "fm1u316",
+                threadId: "afed75fb4f512ae7",
+                index: 0
+            }, {
+                messageId: "fm1u315",
+                threadId: "b4aae3925af0a0a2",
+                index: 1
+            }],
+            total: 1214
+        }, "call2" ],
+        [ "messageUpdates", {
+            accountId: 'user@example.com',
+            oldState: "m815034",
+            newState: "m815039",
+            changed: [ "fm1u316", "fm1u315", "fm1u314" ]
+            removed: []
+        }, "call3" ],
+        [ "messages", {
+            accountId: 'user@example.com',
+            state: "m815039",
+            list: [{
+                "id": "fm1u316",
+                "threadId": "afed75fb4f512ae7",
+                "mailboxId": "mailbox1",
+                "isUnread": true,
+                "isFlagged": false,
+                "isAnswered": false,
+                "isDraft": false,
+                "hasAttachment": false,
+                "from": [
+                    { name: "Joe Bloggs", email: "joebloggs@fastmail.fm" }
+                ],
+                "to": [
+                    { name: "Jane Doe", email: "janedoe@fastmail.fm" }
+                ],
+                "subject": "Camping trip",
+                "date": "2014-07-24T15:04:51Z",
+                "preview": "Hey Joe. Fancy a trip out west next week? I hea…"
+            }, {
+                "id": "fm1u315",
+                "threadId": "b4aae3925af0a0a2",
+                "mailboxId": "mailbox1",
+                "isUnread": true,
+                "isFlagged": false,
+                "isAnswered": false,
+                "isDraft": false,
+                "hasAttachment": false,
+                "from": [
+                    { name: "Joe Bloggs", email: "joebloggs@fastmail.fm" }
+                ],
+                "to": [
+                    { name: "Jane Doe", email: "janedoe@fastmail.fm" }
+                ],
+                "subject": "Camping trip",
+                "date": "2014-07-24T15:04:51Z",
+                "preview": "Hey Joe. Fancy a trip out west next week? I hea…"
+            }, {
+                "id": "fm1u314",
+                "threadId": "4f512aafed75e7fb",
+                "mailboxId": "mailbox1",
+                "isUnread": false,
+                "isFlagged": false,
+                "isAnswered": false,
+                "isDraft": false,
+                "hasAttachment": false,
+                "from": [
+                    { name: "Joe Bloggs", email: "joebloggs@fastmail.fm" }
+                ],
+                "to": [
+                    { name: "Jane Doe", email: "janedoe@fastmail.fm" }
+                ],
+                "subject": "Camping trip",
+                "date": "2014-07-24T15:04:51Z",
+                "preview": "Hey Joe. Fancy a trip out west next week? I hea…"
+            }],
+            notFound: null
+        }, "call3" ],
+        [ "threadUpdates", {
+            accountId: 'user@example.com',
+            oldState: "mc1264092",
+            newState: "mc1264097",
+            changed: [ "afed75fb4f512ae7", "b4aae3925af0a0a2" ],
+            removed: []
+        }, "call4" ]
+        [ "threads", {
+            accountId: 'user@example.com',
+            state: "mc1264097",
+            list: [{
+                id: "afed75fb4f512ae7",
+                messageIds: [ "fm1u241", "fm1u316" ]
+            }, {
+                id: "b4aae3925af0a0a2",
+                messageIds: [ "fm1u315" ]
+            }],
+            notFound: null
+        }, "call4" ]
+    ]
+
+Here's how we apply this information to our current state to stay in sync:
+
+1. `mailboxUpdates`/`mailboxes`: The inbox is the only mailbox to have changed, and only the counts have changed. The new counts are returned in the `mailboxes` response, so we just need to update our cache with the new properties to bring us fully in sync.
+2. `messageListUpdates`: This is more interesting.
+
+    Suppose the client has a sparse list of messageIds (for example, the user opened the folder, loading the first section, then jumped to the middle):
+
+        [ 'm1u1', 'm1u2', 'm1u3', 'm1u4', -, -, -, 'm1u8', -, ...]
+
+    To update this to match the new server state:
+
+    1. Check the oldState property matches the current state of the list. Also check the sort and search are the same. If any of these don't match, abort and re-request an update from the actual current state.
+    2. If the newState property is the same as the current state of the list, nothing to do, so return.
+    3. If there's an `uptoMessageId`, search for this id. If found, remove anything after it in the list. If not found, abort, reset the list and start again with `getMailboxMessageList`.
+    4. Search for each of the messageIds in the `removed` list and remove them from the client's list (without leaving a gap – this is a splice operation). If any can't be found, keep processing but after finishing, null out anything after the first gap in the list. e.g. referring to the example sparse list above, 'm1u8' would be removed as it's after the first gap.
+    5. Iterate through the `added` list **in order**, inserting the messageIds at the positions indicated (again this is a splice operation and will shift everything else further along).
+    6. Set the list length to that given in the `total` property.
+
+    Note, adding or removing an item to/from the list shifts the position of
+    everything around it.
+
+    e.g. adding 'm2' in position 2: `[ 'm1', 'm3' ] -> [ 'm1', 'm2', 'm3' ]`
+
+    e.g. removing 'm2': `[ 'm1', 'm2', 'm3' ] -> [ 'm1', 'm3' ]`
+
+3. `messageUpdates`: The `removed` array has 0 length (so, although a message was removed from the Inbox message list, it has not been deleted: it is simply no longer the first message in the thread in the given sort order). The `changed` array has three message ids: the first two we don't have in memory, so we can ignore, but the last one we have in our cache so we should mark is as needing an update (i.e. the flags might be out of date).
+4. `messages`: Because we specified a `fetchMessages` argument to `getMessageUpdates`, this response contains the requested data for the messages that have been modified or added. The first two are new messages, and we can add this data to our header cache information so we have the info we need to display the mailbox. The final message is one we already have in cache, but a property of it has now changed (in this case, it is no longer unread). We can update this data and clear the flag we set in step 3 indicating it needs refreshing (the reason we set the flag is so the `messageUpdates` response is correctly handled regardless of whether we specified `fetchMessages` or not.
+5. `threadUpdates`: There are two changed threads here. One existing thread has a new message in it, the other is a brand new thread to create in our cache.
+
+After applying these changes, or cache is completely in sync with the server, even though we only have a partial data set cached, and we only made a single HTTP request.
+
+Now let's look at the more difficult cases, when errors occur.
+
+### Handling errors
+
+The most common error will be a `tooManyChanges` error, when the number of changes exceeds the number we were prepared to accept. In this case, it would be more efficient to throw away much of our cache, or mark it as potentially dirty, and then just fetch the information we need right now (similar to the cold boot situation), rather than fetching a potentially large set of updates. Let's look at the errors for each method.
+
+`getMessageListUpdates`: If there are more changes than the `maxChanges` argument, or the server is unable to calculate updates from the state requested, you will receive an appropriate error back. In these cases, you simply have to throw away the current message list cache and request the section you are interested in with a standard `getMessageList` call.
+
+`getMessageUpdates`: If there are too many changes, you will get an error back. In this case, there are two strategies you could adopt. The first is simple: mark each message you have in cache as needing an update, and fetch these when the message is next required by the user (note, since only the flags and mailboxes it belongs to are mutable, the data you need to fetch can be reduced). As an extra possible optimisation, you could try another `getMessageUpdates` call first, with a higher `maxChanges`, but with `fetchMessages` set to `null`. If it succeeds, this will give you back an exact list of the message ids for messages with changes, so you can mark just those as needing a refresh rather than every message in your cache. If there are still too many changes, you will have to fall back to refetching all the flags and labels.
+
+`getThreadUpdates`: Just like with `getMessageUpdates`, if there are too many changes you can either flush your cache of threads, or try with a higher `maxChanges` but `fetchThreads: false`.
+
+In each of the error cases, a single further HTTP request should be sufficient to get the necessary data to update the client to the correct state.
+
+### Handling message list without delta updates
+
+The response to `getMessageList` includes a property called `canCalculateUpdates`, which lets you know whether the server supports a call to `getMessageListUpdates` for the given message list (servers may not support it at all, or may only support it when there is no search involved etc.). In this case, we have to fetch the bit of the message list currently on display, and just throw away all of our cached data for the message list. Note, however, we don't have to throw away all the message data, we just have to fetch the message ids, so it's still not too inefficient.
+
+## Performing actions
+
+Modifying the state is the most complex operation to get right, as changes to messages may change counts in mailboxes, or thread membership, and the client may not have sufficient information to work out all the effects; it must apply the change then get the rest of the updates from the server.
+
+### Selecting all
+
+If you select all, you need to fetch the complete message list for the mailbox currently displayed.
+
+When applying actions to threads, you will often wish to apply the same action to every message in the thread in the same mailbox as the one explicitly selected, or even to all the messages in the thread, regardless of mailbox. The most efficient way to do the former is to fetch the same message list, but with `collapseConversations == false`. You can then easily build a map of threadId to messages ids for messages in the list. If you need to find all messages in the thread, regardless of message list, you will need to fetch the Thread object for every thread in the message list (but you don't need to fetch any message details). You can do this in a single `getMessageList` call, with `fetchThreads: true`, but `fetchMessages: null`, although if it's a long message list you may wish to break this up into a few calls to avoid a single large request blocking the UI for too long.
+
+### Moving a message
+
+Moving a message from the Inbox to the Trash is simple:
+
+    [ "setMessages", {
+        update: {
+            "fm1u254": {
+                mailboxes: [ "mailbox3" ]
+            }
+        }
+    }, "call1" ]
+
+We can then do a resync as in section 4 to update the client cache. This is easy, but means there's a noticeable delay performing every action, and we cannot operate in an offline mode and resync later. We can improve on this, although it makes it considerably more complicated. We can apply the effects we think the changes will have instantly then compare this with the results we get back from the server.
+
+1. **Mailbox counts**.
+
+   For each message moved:
+   - Decrement the `totalMessages` count for the source mailbox.
+   - Increment the `totalMessages` count for the destination mailbox.
+   - If unread, decrement the `unreadMessages` count for the source mailbox.
+   - If unread, increment the `unreadMessages` count for the destination mailbox.
+
+   If there are no other messages in the thread in the source mailbox:
+   - Decrement the `totalThreads` count for the source mailbox.
+   - If any of the messages in the thread are unread, decrement the
+     `unreadThreads` count for the source mailbox.
+
+   If there are no other messages in the thread already in the destination mailbox:
+   - Increment the `totalThreads` count for the destination mailbox.
+   - If any of the messages in the thread are unread, increment the
+     `unreadThreads` count for the destination mailbox.
+
+   There are slight added complexities if moving a message into or out of the Trash; refer to the spec for full details.
+
+2. **Message list**. Splice each selected message being moved from the current message list (from which it was selected by the user). You may also try to insert them at the correct position in the message list of the destination mailbox:
+
+   From the thread object, you know if there are any other messages in the thread already in the mailbox. As the message list in the thread object is sorted by date, as long as the mailbox list is also sorted by date, you can now work out if the message is a new exemplar in the message list or not. If it is, binary search the list by date to find where to insert it. If you don't have message headers for all the message list loaded, you may not be able to determine the correct spot. In this case, it should be inserted anyway so the user can access it; the mistake will be corrected when the next sync with the server occurs.
+
+3. **Thread**. No changes to make.
+
+4. **Message**. Update the `mailboxIds` property on the message object.
+
+When you next do resync, whether that's a second or several days later, apply the changes and fetch the delta update (as per section 4) in a single request, and when the response is received, undo the preemptive changes made above and apply the real changes. Hopefully the end result will be the same, and there will be no noticeable difference to the user.
+
+## Keeping a full copy of mail in sync
+
+JMAP can also be used to efficiently download and keep in sync the entire set of a user's mail. To do this, you would firstly get the full set of mailboxes, then page in the full list of message ids and download the actual messages. From this point on, you would only need to get the delta updates. Presuming you also want to optimise for fetching new mail first, you could do something like when you want to get the latest updates:
+
+    [
+        [ "getMailboxUpdates", {
+            sinceState: "m123456789",
+            fetchRecords: true,
+            fetchRecordProperties: null
+        }, "call1" ],
+        [ "getMessageUpdates", {
+            sinceState: "m815034"
+            maxChanges: 50,
+            fetchRecords: true,
+            fetchRecordProperties: [
+                "threadId",
+                "mailboxIds",
+                "isUnread",
+                "isFlagged",
+                "isAnswered",
+                "isDraft",
+                "hasAttachment",
+                "labels",
+                "from",
+                "to",
+                "subject",
+                "date",
+                "preview"
+            ]
+        }, "call3" ],
+        [ "getMessageList", {
+            filter: {
+                inMailboxes: [ "${inboxId}" ]
+            },
+            sort: [ "date desc", "id desc" ]
+            collapseThreads: false,
+            position: 0,
+            limit: 100
+        }, "call2" ]
+    ]
+
+The first two calls get the delta updates to mailboxes and messages (if the client has a copy of all messages locally, it has no need to use the server to get threads as it already has all the information). In the common case where there are fewer than 50 message changes since last time, this will bring the client fully up to date (barring downloading new message bodies, attachments and other details, which it can easily schedule at its leisure).
+
+However, if there have been a large number of changes since last time, the client is not yet fully up to date. It can continue to call getMessageUpdates to fetch more changes until it reaches the current state. Simultaneously, it can use the response to the getMessageList call in the first request to see if there are any new message ids at the top of the Inbox. These can be downloaded first so the user has immediate access to new messages (by the end of the second round trip) while the other changes then continue to sync across afterwards.

Added: james/project/trunk/home/faq.mdwn
URL: http://svn.apache.org/viewvc/james/project/trunk/home/faq.mdwn?rev=1726745&view=auto
==============================================================================
--- james/project/trunk/home/faq.mdwn (added)
+++ james/project/trunk/home/faq.mdwn Tue Jan 26 07:45:37 2016
@@ -0,0 +1,49 @@
+# JMAP
+
+<p style="margin-left:-40px;"><iframe width="780" height="469" src="http://www.youtube.com/embed/8qCSK-aGSBA?version=3&amp;rel=0&amp;fs=1&amp;showsearch=0&amp;showinfo=1&amp;iv_load_policy=1&amp;wmode=transparent" frameborder="0" allowfullscreen="true"></iframe></p>
+
+## What is JMAP?
+
+JMAP is a transport-agnostic, stateless JSON-based API for synchronising a mail client with a mail server. It is intended as a replacement for IMAP. The specification is based on the API currently used by [FastMail](https://www.fastmail.com)'s web app.  It aims to be compatible with the IMAP data model, so that it can be easily implemented on a server that currently supports IMAP, but also allows for reduced data usage and more efficient synchronisation, bundling of requests for latency mitigation and is generally much easier to work with than IMAP.
+
+## Why is it not REST based?
+
+JMAP is actually more REST-like than most "RESTful" APIs. It is stateless, highly cacheable, supports transparent intermediaries and provides a uniform interface for manipulating different resources. However, it doesn't use HTTP verbs to implement this.
+
+When you have a high latency connection (such as on a mobile phone, or even wired connections from the other side of the world), the extra round trips required for an HTTP REST-based protocol can make a huge impact on  performance. This is especially an issue when you have an order-dependency in your API calls and you need to make sure one has finished before the other can be run (for example when you mutate the state of a message then want to fetch the changes to a mailbox containing the message). In the JMAP protocol, this can be done in a single round trip. An HTTP REST-based version would require two full round trips for the same operation.
+
+The JMAP protocol is transport agnostic and can be easily transported over a WebSocket, for example, as well as HTTP.
+
+## Why is it not a binary protocol?
+
+A binary protocol would be arguably more compact and faster to encode/parse. However, history has shown text-based protocols are much easier to debug, and by using an existing widely-used encoding format (JSON) we make it much easier for developers to use this protocol. No need to write new custom, error-prone parsers. The difference in speed is likely to be minimal, especially if you GZIP the exchange and use WebSockets instead of HTTP.
+
+## Why do labels apply to messages not threads?
+
+Mutable state has to be stored per-message, for example the `isUnread` status must apply on a per message basis, and it's very useful to be able to flag a particular useful message rather than just the whole thread. To be able to delete a particular message to the Trash out of a thread, you need to be able to change the mailbox of that message. Sent messages should belong to the sent mailbox, but not messages you receive.
+
+Meanwhile, it is simple to aggregate the information of the messages in the thread. So, for example, if any message in the thread is unread, then the thread can be considered unread. There is no need to store mutable state as a property of a thread therefore, and the less mutable state, the easier it is to manage. Finally, all known existing IMAP implementations, plus Gmail, store this state per-message, not per-thread, so it makes it easier for implementors to migrate to JMAP.
+
+## Why are there flags (e.g. isUnread) separate to mailboxes?
+
+In IMAP, you can only have one mailbox but you can have multiple flags on a single message. In other systems (where you have labels), these are really the same thing and you can have a single message in multiple mailboxes. JMAP aims to support both, so it has to be able to specify whether a mailbox can be used in combination with other mailboxes on a message, or must be the only one with the message (but does allow different flags). The clearest way of specifying what is allowed by the server is to keep the mailboxes separate to flags in JMAP as well.
+
+## Why isUnread instead of isRead?
+
+Although this may seem inconsistent at first, it actually makes more sense. The "special" status is when a message is unread (this is what clients are interested in), so like isDraft, isFlagged and isAnswered, we make the special status equal to `true`. It is also consistent with the need for unread counts in mailbox objects, not read counts, and makes the definition of sorting a message list the same for isFlagged and isUnread when conversations are collapsed.
+
+## I want to get involved with JMAP. What do I need to know?
+
+First of all, you should join the [JMAP mailing list](https://groups.google.com/forum/#!forum/jmap-discuss). Feedback is welcome: send your thoughts or comments on anything that is imprecise, incomplete, or could simply be done better in another way. Or if you're working on something JMAP related, this list is a good place to let other people know and to raise any issues you come across.
+
+The specification itself is [hosted on GitHub](https://github.com/jmapio/jmap). If you've found a typo or other minor change, feel free to just submit a pull request. Otherwise, discussion on the mailing list first is preferred.
+
+## I want to implement it. What do I need to know?
+
+That's great! There are lots of resources on this website to help you. Counter-intuitive though it may seem, I recommend starting with the [guide for client authors](client.html) to get a good feel for how the JMAP spec works. After that though, [the spec](spec.html) is your bible and the [advice for implementors](server.html) is your friend.
+
+If you're implementing the spec and suddenly find there's an externally visible behaviour that's not specified, please email the [mailing list](https://groups.google.com/forum/#!forum/jmap-discuss) so we can update the spec to nail down this corner.
+
+## I want to use it to build a client. What do I need to know?
+
+Have a read through the [client guide](client.html) to get an idea of how it works. Then you'll want to find a JMAP server to test against.

Added: james/project/trunk/server-guide/jmap-server-guide.mdwn
URL: http://svn.apache.org/viewvc/james/project/trunk/server-guide/jmap-server-guide.mdwn?rev=1726745&view=auto
==============================================================================
--- james/project/trunk/server-guide/jmap-server-guide.mdwn (added)
+++ james/project/trunk/server-guide/jmap-server-guide.mdwn Tue Jan 26 07:45:37 2016
@@ -0,0 +1,312 @@
+# Advice for JMAP implementors
+
+This document describes a recommended set of data structures and algorithms for efficiently implementing JMAP. It is intended to serve as suggestions only; there may well be better ways to do it. The spec is the authoritative guide on what constitutes a conformant JMAP implementation.
+
+## Assigning Message Ids
+ 
+A good way of assigning a message id is to sha1 the RFC2822 message and take the first 80 bits (this is sufficient for avoiding collisions in any reasonable sized instance, but the server may choose any length it likes). If this is already in use (i.e. another copy of the message already exists), sha1 the GUID. Repeat until there is no collision. The bytes can be represented in any reasonable encoding for transmission as a `String` within the API.
+
+## Modification sequences
+
+A modification sequence, or **modseq**, is a 63-bit monotonically incrementing counter. Each user has their own modseq counter (in IMAP it's originally per-mailbox, but per user is backwards compatible with this). Every time a change occurs to data within the user, the modseq is incremented by one and the new value is associated with the changes. This is used in a number of data structures and algorithms below to efficiently calculate changes.
+
+## Data structures
+
+As ever in programming, get your data structures right and the server will practically write itself.
+
+There are three types of data structures suggested in this guide (excluding the email indexing for search, which is more complicated than this guide is prepared to go into):
+
+1. A **Map** (associative array) of id to variable-length data blob:
+   - Insert should be O(1).
+   - Lookup should be O(1).
+   - Delete should be O(1).
+   - Not ordered, but we need to be able to iterate over all the values.
+2. An **append-only log** of variable length blobs:
+   - Insert is only at tail.
+   - Lookup needs to be able to binary search (based on modseq) to find start location, then read sequentially.
+   - Delete is only at head.
+3. An **Ordered list** of fixed-sized objects:
+   - Insert is mainly at or near the head, but can be in a random location.
+   - Want to be able to read sequentially from head (common case), or read whole structure into memory and sort.
+   - Delete is mainly near head, but can be in a random location.
+
+### 1. User
+
+This is a simple collection of important top-level values for the user (kept in a **Map**):
+
+- Highest ModSeq for the user (`63 bits` for IMAP compatibility)
+- Highest ModSeq of any Mailbox.
+- Low watermark ModSeq for Thread Log `63 bits` – whenever the thread log (see below) is truncated, the modseq of the new first item in the log is stored here. Any attempt to call *getThreadUpdates* with a modseq lower than this must be rejected with a `cannotCalculateUpdates` error.
+- Low watermark ModSeq for Message Log `63 bits` – the same, but for the message log.
+- Quota available in bytes (63 bits. -1 => Don't care)
+- Quota used in bytes `63 bits`
+- List of other users with mailboxes made available to this user (shared mailboxes) (var length).
+ 
+### 2. Mailboxes
+
+A map of Mailbox Id to all of the mailbox object values (as defined in the spec, including the counts). For the purposes of calculating `getMailboxUpdates`, also include the following for each mailbox:
+
+- **Mailbox ModSeq** `63 bits` Updated when any of the mailbox properties (as defined in the spec) change – not updated when the mailbox message list changes.
+- **Mailbox Non-Counts ModSeq** `63 bits` Updated when any of the mailbox properties that are not counts change. When calculating `getMailboxUpdates`, if this is lower than the previous mod seq, but the Mailbox ModSeq is higher, then only counts have changed.
+- **Message list UID Next** `32 bits` The next UID (incrementing 32-bit counter) to assign to messages added to the mailbox message list.
+- **Message list highest ModSeq** `63 bits` The highest ModSeq of a message in the mailbox message list.
+- **Low watermark message list ModSeq** `63 bits` Whenever a message is undeleted via IMAP (that is the \Deleted flag is removed) or a deleted message is fully expunged from the mailbox message list (see message list data structure below), set this to the ModSeq of that message if higher than the previous value. Any attempt to call *getMessageListUpdates* with a modseq lower than this must be rejected with a `cannotCalculateUpdates` error.
+
+The suggested way to assign a Mailbox id is to use an incrementing counter. 16 bits should be sufficient, giving support for a maximum of 65536 mailboxes per user. Old ids are reusable without penalty while keeping with the JMAP semantics. Over the wire this would be represented as a prefix plus an encoding of the number, e.g. "m1", "m2" etc.
+
+### 3. Mailbox message list
+
+One of these should exist for each mailbox. It is an ordered list of fixed size objects. Each object is:
+
+- **UID** `32 bits` As per IMAP semantics, this increments each time you append a message to the mailbox. The next UID to use is stored in the Mailbox object.
+- **ModSeq** `63 bits` As per IMAP semantics, this is updated whenever any property of the message changes.
+- **Message Id** `80 bits` This is the ID always used within JMAP to refer to the message, and does not change as it moves between mailboxes.
+- **Thread Id** `64 bits`
+- **Deleted** `64 bits` Time stamp from epoch of when the message was removed the mailbox. `0` means not deleted. See below
+- **Message Date** `64 bits`
+ 
+Given that most message list fetches are of the first section of a single mailbox in date descending order, if we keep it stored in this order on disk we can just read the first few bytes to return the desired information; no sorting required (we don't even have to look up anything in the message cache). The date is included in each record so we can insert a new one in the correct position without having to reference any other data.
+
+When a message is removed from the mailbox we don't remove it immediately from the message list. Instead we just set the Deleted field to the time stamp of when it was deleted. This allows the delta update algorithm to work to efficiently update the client to the new list state. At certain intervals (either based on how many deleted nodes there are or how long since they were deleted) this needs to be cleaned up and the deleted objects fully expunged from the message list. At this point the low watermark ModSeq needs to be updated on the Mailbox data structure.
+ 
+### 4. Message cache
+
+A map of Message Id to flags, mailboxes and common header information for that message (variable length). This lets the server optimise calls to `getMessages` that only fetch this information (common when fetching the required information for a mailbox listing). It also allows optimisation of `getMessageList` as most, even quite complex filters will only require checking this cache (which should be relatively fast) rather than looking up and parsing the whole message (which could be quite slow).
+
+For each message, store:
+
+- **isUnread** `1 bit` (mutable)
+- **isFlagged** `1 bit` (mutable)
+- **isAnswered** `1 bit` (mutable)
+- **isDraft** `1 bit` (mutable by IMAP)
+- Other flags + labels + annotations as needed for IMAP compatibility only. (mutable)
+- **Mailboxes** (list of mailbox ids this message belongs to) (mutable)
+- **From** header (either in the JSON used by JMAP, or whatever IMAP needs)
+- **To** header (either in the JSON used by JMAP, or whatever IMAP needs)
+- **Subject** header
+- **Date**
+- **Preview** (see spec)
+- **Attachments** (list of file names only; also used for hasAttachments)
+- **GUID** (sha1 of raw email)
+ 
+### 5. Message index
+
+For searching messages at any reasonable speed, an index is required from textual content within the message to the message id. Describing how this should work is beyond the scope of this guide.
+
+### 6. Messages
+
+A map of GUID (sha1 of the message contents) to the raw RFC2822 message itself. This is the bulk of the data to be stored for each user. As this data is immutable and referenced by its sha1, there are many possibilities for how to store it. Each message could be stored as a separate file using its GUID as the name. Or on a separate networked object store etc. etc.
+ 
+### 7. Message log
+
+An append only log of changes made to the message cache. Each entry consists of:
+
+- **ModSeq** of change `63 bits`
+- List of **Message ids** which were affected by the change (to save extra lookups when the client is fetching these changes, should probably include a bit to say whether the message was destroyed by the change or created/modified).
+ 
+Periodically, truncate the log by chopping records off the beginning. At this point you need to update the low watermark ModSeq for the log in the User object (data structure 1).
+ 
+### 8. Threads
+
+A map of thread id to an object containing information about the thread (variable length). The information stored for each thread is:
+
+- The **list of messages** belonging to the thread, sorted in date order. For each - message we need to store:
+  - **Message Id** `80 bits`
+  - **Mailboxes** The list of mailboxes the message belongs to. For sorting a message list by thread unread/thread flagged purposes only.
+  - **isUnread** `1 bit` For sorting a message list by thread unread/thread flagged purposes only.
+  - **isFlagged** `1 bit` For sorting a message list by thread unread/thread flagged purposes only.
+- **ModSeq of last change** to isRead/isFlagged for any message in the thread (for sorting a message list by thread unread/thread flagged purposes only).
+- **Sha1 of subject** after stripping Fwd/Re etc. (for checking whether we need to split a new conversation out later; see threading algorithm in data structure 10).
+ 
+### 9. Thread log
+
+An append only log of changes made to the **membership** of threads (in data structure 7; changes to only the isRead/isFlagged/Mailboxes of a message in a thread do not need to go in the log). Each entry consists of:
+
+- **ModSeq** of change
+- **List of thread ids** which were affected by the change (to save extra lookups when the client is fetching these changes, should probably include a bit to say whether the thread was destroyed by the change or created/modified).
+ 
+As with the message log, periodically truncate the log by chopping records off the beginning; at this point you need to update the low watermark ModSeq for the log in the user object.
+ 
+### 10. Refs to ThreadId
+
+This is solely used to look up the conversation to assign to a message on creation/import/delivery. Maps the RFC2822 Message Id (eughh, so many different types of id!) to the thread id.
+
+The suggested rule for connecting messages into threads is this:
+
+If two messages share a common RFC2822 Message Id in the set of such ids within the `Message-Id`, `References` and `In-Reply-To` headers of each message, and the messages have the same `Subject` header (after stripping any preceding Re:/Fwd: and trimming white space from either end), then they should belong in the same thread. Otherwise they should belong in different threads.
+
+## Message List Algorithms
+
+The `state` property to return with getter calls to each type is:
+
+- Mailbox: Highest ModSeq of any Mailbox (stored in the User object)
+- MessageList: Message list UID Next + Message list highest ModSeq (as stored on the Mailbox object). For message lists that aren't just a mailbox, the state string should be the highest message ModSeq (as found at the tail of the Message Log).
+- Thread: The highest modseq found at the end of the Thread Log.
+- Message: The highest modseq found at the end of the Message Log.
+
+### getMailboxUpdates
+
+Simply iterate through the set of Mailboxes comparing their current mod seqs to the client mod seq. If higher, the mailbox has changed. If the non-counts is not higher, only counts have changed.
+
+### getMessageList
+
+First you need to get the complete list. In the common case of…
+
+    filter == { inMailboxes: [ 'inboxId' ], notInMailboxes: [ 'trashId' ] }
+
+…you are simply fetching the list of messages in a mailbox. This list is already pre-calculated for each mailbox and kept on disk (data structure 3). You can simply slurp this into memory and sort if needed (again, in the common case of sorting date-descending, it will be pre-sorted).
+
+If the filter is more complex, you will need to do more work to get the set of matching messages and sort it. If there is a `String` component to the filter, first use the message index (data structure 5) to get a set of matches. Then iterate through and lookup each match in the message cache (data structure 4) to apply any other components of the filter. Finally sort as specified.
+
+Once you have the complete message list, you can calculate the results to return to the client. Since a client is likely to fetch a different portion of the same message list soon after, it is beneficial if the server can keep the last list requested by the user in a cache for a short time.
+
+    let collapseThreads = args.collapseThreads
+    let position = args.position
+    let anchor = args.anchor
+    let anchorOffset = args.anchorOffset
+    let limit = args.limit
+    let total = 0
+    let messageIds = [] # NB Max size of array is limit
+    let threadIds = []  # NB Max size of array is limit
+
+    # If not collapsing threads, we can just jump to the required section
+    if !collapseThreads {
+      total = messageList.length
+      for i = position; i < total; i = i + 1 {
+        messageIds.push( msg.id )
+        threadIds.push( msg.threadId )
+      }
+    } else {
+      # Optimisation for the common case
+      let totalIsKnown = filter is just mailbox
+      let SeenThread = new Set()
+      let numFound = 0
+      foreach msg in sortedFilteredList {
+        if !SeenThread{ msg.threadId } {
+          SeenThread.add( msg.threadId )
+          total += 1
+          if position >= total && numFound < limit {
+            messageIds.push( msg.id )
+            threadIds.push( msg.threadId )
+            numFound += 1
+            if numFound == limit && totalIsKnown {
+              break;
+            }
+          }
+        }
+      }
+      if totalIsKnown {
+        total = getTotal( mailbox, collapseThreads )
+      }
+    }
+
+### getMessageListUpdates
+
+With the suggested data structures, we can do delta updates for any standard mailbox message list (the common case), but not for a search. The following algorithm correctly calculates the delta update. We're presuming we already have a `messageList` (directly read in from data structure 3 and sorted if required):
+
+    let index = -1
+    let added = []
+    let removed = []
+    let collapseThreads = args.collapseThreads
+    let uptoHasBeenFound = false
+
+    # A mutable sort is one which sorts by a mutable property, e.g.
+    # sort flagged messages/threads first.
+    let isMutable = sort.isMutable()
+
+    # An exemplar is the first message in each thread in the list, given the
+    # sort order that
+    # The old exemplar is the exemplar in the client's old state.
+    let SeenExemplar = collapseThreads ? new Set() : null
+    let SeenOldExemplar = collapseThreads ? new Set() : null
+
+    foreach msg in messageList {
+
+      let isNewExemplar = false
+      let isOldExemplar = false
+
+      let isNew = ( msg.uid >= mailbox.uidNext )
+      let isChanged = ( msg.modSeq > args.state )
+      let isDeleted = ( msg.deletedTimeStamp != 0 )
+      let wasDeleted = ( isDeleted && !isChanged )
+
+      # Is this message the current exemplar?
+      if !isDeleted && ( !collapseThreads || !SeenExemplar{ msg.threadId } ) {
+        isNewExemplar = true
+        index += 1
+        if collapseThreads {
+          SeenExemplar.set( msg.threadId )
+        }
+      }
+
+      # Was this message an old exemplar?
+      # 1. Must not have arrived after the client's state
+      # 2. Must have been deleted before the client's state
+      # 3. Must not have already found the old exemplar
+      if !isNew && !wasDeleted &&
+          ( !collapseThreads || !SeenOldExemplar{ msg.threadId } ) {
+        isOldExemplar = true
+        if collapseThreads {
+          SeenOldExemplar.set( msg.threadId )
+        }
+      }
+
+      if isOldExemplar && !isNewExemplar {
+        removed.push({
+          messageId: msg.messageId,
+          threadId: msg.threadId
+        })
+      }
+      else if !isOldExemplar && isNewExemplar {
+        added.push({
+          index: index,
+          messageId: msg.messageId,
+          threadId: msg.threadId
+        })
+      }
+      # Special case for mutable sorts (based on isFlagged/isUnread). If
+      # collapseThread == true, the sort is based on the *conversation*
+      # isFlagged/isUnread status.
+      if isMutable && isOldExemplar && isNewExemplar {
+        # Has the isUnread/isFlagged status of the message/thread
+        # (as appropriate) possibly changed since the client's state?
+        let modSeq = collapseThreads ?
+              msg.modSeq :
+              getThread( msg.threadId ).modSeq
+        # If so, we need to remove the exemplar from the client view and add 
+        # it back in at the correct position.
+        if modSeq > args.modSeq {
+          removed.push({
+            messageId: msg.messageId,
+            threadId: msg.threadId
+          })
+          added.push({
+            index: index,
+            messageId: msg.messageId,
+            threadId: msg.threadId
+          })
+        }
+      }
+      # If this is the last message the client cares about, we can stop here
+      # and just return what we've calculated so far. We already know the total
+      # count for this message list as we keep it pre calculated and cached in
+      # the Mailbox object.
+      #
+      # However, if the sort is mutable we can't break early, as messages may 
+      # have moved from the region we care about to lower down the list.
+      if !isMutable && msg.uid == args.upto {
+        break
+      }
+    } # End loop
+
+    total = getTotal( mailbox, collapseThreads )
+
+To implement this algorithm, the server must keep the metadata at least of deleted (expunged) messages for a little while (say 1-2 weeks). This is also very useful for restoring accidentally deleted messages as well. At cleanup time (when actually removing the messages), the server must keep track of the highest modseq of a message it has removed in that mailbox (the modseq would have been set at the original delete time); any requests for updates from a state before this must be rejected, as the results may be incorrect.
+
+## getThreadUpdates
+
+If the client id is lower than the low watermark ModSeq for the Thread Log (as found in the User object), reject with a `cannotCalculateUpdates` error. Otherwise, binary search the Thread log looking for the client modseq, then read sequentially from there to get the changes.
+
+## getMessageUpdates
+
+If the client id is lower than the low watermark ModSeq for the Message Log (as found in the User object), reject with a `cannotCalculateUpdates` error. Otherwise, binary search the Message log looking for the client modseq, then read sequentially from there to get the changes.

Added: james/project/trunk/software/software.mdwn
URL: http://svn.apache.org/viewvc/james/project/trunk/software/software.mdwn?rev=1726745&view=auto
==============================================================================
--- james/project/trunk/software/software.mdwn (added)
+++ james/project/trunk/software/software.mdwn Tue Jan 26 07:45:37 2016
@@ -0,0 +1,19 @@
+# JMAP software
+
+JMAP is still young but several implementations already exist, and more are on the way. If you're working on a project that uses JMAP, please email the [mailing list](https://groups.google.com/forum/#!forum/jmap-discuss) and we'll add it here.
+
+## Clients
+
+* **[JMAP Demo Webmail](https://github.com/jmapio/jmap-demo-webmail)** (JavaScript, MIT): a sophisticated demo webmail client to be used as a base for new projects. Default client for the [proxy](https://proxy.jmap.io).
+
+## Servers
+
+* **[JMAP Proxy](https://github.com/jmapio/jmap-perl)** (Perl, MIT): a complete JMAP server implementation that uses any IMAP, CalDAV and CardDAV store as a backend. Also available as a hosted service at [proxy.jmap.io](https://proxy.jmap.io).
+* **[Cyrus IMAP](https://docs.cyrus.foundation/imap/release-notes/3.0/x/3.0.0-beta1.html)** (C, BSD-style): A scalable enterprise-grade IMAP, CalDAV and CardDAV server. The 3.0 series is adding JMAP support.
+* **[salada](https://github.com/robn/salada)** (Rust, MIT): A small standalone JMAP server, suitable for development and experimentation.
+
+## Libraries
+
+* **[JMAP-JS](https://github.com/jmapio/jmap-js)** (JavaScript, MIT): a full implementation of the JMAP mail, calendar and contacts model in JavaScript. It supports asynchronous local changes and is tolerant of network failure – actions will update the UI instantly, then synchronise changes back to the server when it can. It also has multi-level undo/redo support. Used by the [demo webmail](https://github.com/jmapio/jmap-demo-webmail).
+* **[jmap-client](https://github.com/linagora/jmap-client)** (JavaScript ES6, MIT): a simple promise-based API to send requests to a JMAP server.
+* **[jmap-rs](https://github.com/robn/jmap-rs)** (Rust, MIT): JMAP parser, generator and data model library for Rust. Used by [salada](https://github.com/robn/salada).

Added: james/project/trunk/spec/account.mdwn
URL: http://svn.apache.org/viewvc/james/project/trunk/spec/account.mdwn?rev=1726745&view=auto
==============================================================================
--- james/project/trunk/spec/account.mdwn (added)
+++ james/project/trunk/spec/account.mdwn Tue Jan 26 07:45:37 2016
@@ -0,0 +1,116 @@
+## Accounts
+
+A single login may provide access to multiple accounts, for example if another user is sharing their mail with the logged in user.
+
+All data belongs to an account. With the exception of a few explicit operations to copy data between accounts, all methods take an *accountId* argument that specifies on which account the operations are to take place. This argument is always optional; if not specified, the primary account is used. All ids (other than Account ids of course) are only unique within their account.
+
+An **Account** object has the following properties:
+
+- **id**: `String`
+  The id of the account. This property is immutable.
+- **name**: `String`
+  A user-friendly string to show when presenting content from this account. e.g. the email address of the account.
+- **isPrimary**: `Boolean`
+  This MUST be true for exactly one of the accounts returned.
+- **capabilities**: `AccountCapabilities`
+  An object describing general capabilities of this server.
+- **mail**: `MailCapabilities|null`
+  If `null`, this account does not support mail, and any use of the mail-related methods with this account will result in an `accountNoMail` error. Otherwise, it will be an object describing certain capabilities of the mail system.
+- **contacts**: `ContactsCapabilities|null`
+  If `null`, this account does not support contacts, and any use of the contacts-related methods with this account will result in an `accountNoContacts` error. Otherwise, it will be an object describing certain capabilities of the contacts system.
+- **calendars**: `CalendarsCapabilities|null`
+  If `null`, this account does not support calendars, and any use of the calendar-related methods with this account will result in an `accountNoCalendars` error. Otherwise, it will be an object describing certain capabilities of the calendars system.
+
+An **AccountCapabilities** object has the following properties:
+
+- **maxSizeUpload**: `Number`
+  The maximum file size, in bytes, that the server will accept for a single file upload (for any purpose).
+
+A **MailCapabilities** object has the following properties:
+
+- **isReadOnly**: `Boolean`
+  True if the user has read-only access to the mail in this account. The user may not use the `set`-type mail methods with this account.
+- **maxSizeMessageAttachments**: `Number`
+  The maximum total size of attachments, in bytes, allowed for messages. A server MAY still reject messages with a lower attachment size total (for example, if the body includes several megabytes of text, causing the size of the encoded MIME structure to be over some server-defined limit).
+- **canDelaySend**: `Boolean`
+  Does the server support inserting a message into the outbox to be sent later at a user-specified time?
+- **messageListSortOptions**: `String[]`
+  A list of all the message properties the server supports for sorting by. This MAY include properties the client does not recognise (for example custom properties specified in the vendor extension). Clients MUST just ignore any unknown properties in the list.
+
+A **ContactsCapabilities** object has the following properties:
+
+- **isReadOnly**: `Boolean`
+  True if the user has read-only access to the contacts in this account. The user may not use the `set`-type contacts methods with this account.
+
+A **CalendarsCapabilities** object has the following properties:
+
+- **isReadOnly**: `Boolean`
+  True if the user has read-only access to the calendars in this account. The user may not use the `set`-type calendar methods with this account.
+
+The AccountCapabilities, MailCapabilities, ContactsCapabilities and CalendarsCapabilities objects MAY also contain one or more properties prefixed with "vnd-" + a name that uniquely identifies the vendor. For example `"vnd-com.fastmail"`. The value type for these properties is undefined. These properties allow vendors to be able to inform their own clients of custom capabilities. Unknown properties of this form MUST be ignored by clients.
+
+### getAccounts
+
+To fetch the complete list of accounts to which the user has access, make a call to `getAccounts`. It takes a sole, optional argument:
+
+- **sinceState**: `String|null`
+  This is the `state` string from a previous call to *getAccounts*.
+
+The response to *getAccounts* is called *accounts*. It has the following arguments:
+
+- **state**: `String`
+   A string representing the state on the server for **all** the data contained within the Account objects. If the data changes, this string will change.
+- **list**: `Account[]|null`
+  An array of all Account objects. If *sinceState* was supplied and it is identical to the current state, this property is `null`.
+
+The following errors may be returned instead of the `accounts` response:
+
+`invalidArguments`: Returned if the `sinceState` argument is included and has the wrong type.
+
+Example of a successful request:
+
+    ["getAccounts", {}, "#0"]
+
+and response:
+
+    [ "accounts", {
+      "state": "f6a7e214",
+      "list": [
+        {
+          "id": "6asf5",
+          "name": "user@example.com",
+          "isPrimary": true,
+          "capabilities": {
+            maxSizeUpload: 1000000000
+          },
+          "mail": {
+            "isReadOnly": false,
+            "maxSizeMessageAttachments": 50000000,
+            "canDelaySend": true,
+            "messageListSortOptions": [
+              "id", "date", "subject", "from", "to",
+              "isUnread", "isPinned", "threadUnread", "threadPinned"
+            ],
+          },
+          "contacts": {
+            "isReadOnly": false
+          },
+          "calendars": {
+            "isReadOnly": false
+          }
+        },
+        {
+          "id": "e12e1a",
+          "name": "shared.user@example.com",
+          "isPrimary": false,
+          "capabilities": {
+            maxSizeUpload: 0
+          },
+          "mail": null,
+          "contacts": null,
+          "calendars": {
+            "isReadOnly": true
+          }
+        }
+      ]
+    }, "#0" ]



---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org