# Edit files in place

Change, insert or remove bytes inside a file by sending only those bytes.

S3 replaces a whole object on every write. To change four bytes of a 64 GB file, a plain S3 client uploads 64 GB. Orbit's edit operations send the four bytes. The drive stores new blocks for the part that changed and reuses the rest.

Each edit creates a new [version](https://docs.orbitfs.io/guides/history), so an edit can always be undone.

| Operation | Use it to | File length |
| --- | --- | --- |
| [Write](#write-at-an-offset) | Overwrite bytes at an offset, or append | Grows if you write past the end |
| [Truncate](#truncate-or-extend) | Set the length | Set exactly |
| [Patch](#patch-many-ranges) | Overwrite many ranges in one atomic step | Grows if an edit goes past the end |
| [Splice](#splice-insert-or-remove) | Insert or remove bytes, shifting what follows | Changes by inserted minus removed |

## Send an extension request

Edit operations are ordinary Signature Version 4 requests with an `x-uls-` query parameter and headers. The AWS SDK clients have no method for them, so sign the request yourself. Every `x-uls-*` header must be part of the signature.

This Python helper uses the signer that ships with boto3. The examples on this page and in the other guides call it.

```python
import os
import requests
from botocore.auth import S3SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials

ENDPOINT = "https://s3.orbitfs.io"
credentials = Credentials(
    os.environ["AWS_ACCESS_KEY_ID"],
    os.environ["AWS_SECRET_ACCESS_KEY"],
)

def orbit(method, path, headers=None, body=b""):
    """Send a signed request. `path` is /<drive>/<key>?<extension>."""
    request = AWSRequest(method, ENDPOINT + path, data=body, headers=headers or {})
    S3SigV4Auth(credentials, "s3", "auto").add_auth(request)
    signed = dict(request.headers)
    response = requests.request(method, request.url, data=body, headers=signed)
    response.raise_for_status()
    return response
```

Percent-encode the key in `path` as you would in any URL.

## Write at an offset

```http
PUT /<drive>/<key>?x-uls-write
x-uls-offset: <byte offset>
Content-Length: <length of body>

<bytes to write>
```

```python
# Overwrite 4 bytes at offset 1024.
orbit("PUT", "/my-drive/data.bin?x-uls-write", {"x-uls-offset": "1024"}, b"\xde\xad\xbe\xef")
```

- The file is created if it doesn't exist.
- Writing past the end extends the file. Any gap between the old end and the offset is filled with zeros.
- To append, use the current size as the offset. The response to any write carries the new size in `x-uls-size`.

## Truncate or extend

Add `x-uls-size` to a write to set the file's final length. With an empty body, this is a truncate:

```python
# Cut the file to exactly 1 MiB.
orbit("PUT", "/my-drive/data.bin?x-uls-write", {"x-uls-offset": "0", "x-uls-size": "1048576"})
```

A size larger than the file extends it with zeros.

## Patch many ranges

A patch applies up to 10,000 overwrites as one change. Either all of them land in a single new version, or none do.

```http
POST /<drive>/<key>?x-uls-patch
Content-Type: application/vnd.s3sdk.patch

<patch body>
```

The body is binary, with all integers big-endian:

| Bytes | Content |
| --- | --- |
| 4 | The ASCII characters `S3SP` |
| 4 | `01 00 00 00` |
| 4 | Number of edits, 1 to 10,000 |
| Then, per edit: 8 | Offset |
| 8 | Length |
| Length | The bytes to write |

```python
import struct

def patch_body(edits):
    """edits: a list of (offset, bytes)."""
    out = b"S3SP" + bytes([1, 0, 0, 0]) + struct.pack(">I", len(edits))
    for offset, data in edits:
        out += struct.pack(">QQ", offset, len(data)) + data
    return out

orbit(
    "POST", "/my-drive/table.db?x-uls-patch",
    {"Content-Type": "application/vnd.s3sdk.patch"},
    patch_body([(0, b"HDR2"), (4096, b"\x00" * 16), (1 << 30, b"tail")]),
)
```

Edits apply in order, so a later edit wins where two overlap.

Prefer one patch over many writes when a change touches several places: readers never see a half-applied state, and the drive records one version instead of many.

## Splice: insert or remove

A write overwrites. A splice changes the file's length and shifts everything after the offset.

```http
PUT /<drive>/<key>?x-uls-splice
x-uls-offset: <byte offset>
x-uls-remove: <bytes to remove, default 0>
Content-Length: <length of body>

<bytes to insert>
```

```python
# Insert a line at offset 120 without removing anything.
orbit("PUT", "/my-drive/notes.txt?x-uls-splice", {"x-uls-offset": "120"}, b"a new line\n")

# Replace 5 bytes at offset 0 with 9 bytes.
orbit("PUT", "/my-drive/notes.txt?x-uls-splice", {"x-uls-offset": "0", "x-uls-remove": "5"}, b"Chapter 1")

# Remove 64 bytes at offset 200.
orbit("PUT", "/my-drive/notes.txt?x-uls-splice", {"x-uls-offset": "200", "x-uls-remove": "64"})
```

The file must exist, and the removed range must lie inside it.

## Responses

A successful edit returns `200` with no body and these headers:

| Header | Value |
| --- | --- |
| `ETag` | The file's new ETag |
| `x-amz-version-id` | The version the edit created |
| `x-uls-size` | The file's new length in bytes |

## Concurrent edits

An edit is always applied to the version the drive held when your request arrived. If another writer changes the file while your edit is being applied, yours fails with `412 PreconditionFailed` and changes nothing. Read the file's current state and send the edit again.

To make an edit conditional on what you last read, add `If-Match: <etag>`.

## Limits

- The body of a write, patch or splice can be up to 64 MiB.
- A patch holds 1 to 10,000 edits.
- The key can't end in `/`. Folders have no bytes to edit.
