|
| 1 | +"""Documentation examples for Encryption page. |
| 2 | +
|
| 3 | +These snippets are extracted by the docs build script. |
| 4 | +
|
| 5 | +Run with: python examples/docs/encryption.py |
| 6 | +Requires: S2_ACCESS_TOKEN, S2_BASIN, S2_ENCRYPTION_KEY environment variables |
| 7 | +""" |
| 8 | + |
| 9 | +import asyncio |
| 10 | +import os |
| 11 | +import time |
| 12 | + |
| 13 | +from s2_sdk import ( |
| 14 | + S2, |
| 15 | + AppendInput, |
| 16 | + BasinConfig, |
| 17 | + Encryption, |
| 18 | + ReadLimit, |
| 19 | + Record, |
| 20 | + SeqNum, |
| 21 | +) |
| 22 | + |
| 23 | +access_token = os.environ["S2_ACCESS_TOKEN"] |
| 24 | +basin_name = os.environ["S2_BASIN"] |
| 25 | + |
| 26 | + |
| 27 | +async def main(): |
| 28 | + if "S2_ENCRYPTION_KEY" not in os.environ: |
| 29 | + raise RuntimeError("S2_ENCRYPTION_KEY is required") |
| 30 | + |
| 31 | + async with S2(access_token) as client: |
| 32 | + basin = client.basin(basin_name) |
| 33 | + stream_name = f"docs-encryption-{int(time.time())}" |
| 34 | + |
| 35 | + # ANCHOR: basin-cipher |
| 36 | + try: |
| 37 | + await client.create_basin( |
| 38 | + basin_name, |
| 39 | + config=BasinConfig(stream_cipher=Encryption.AEGIS_256), |
| 40 | + ) |
| 41 | + except Exception: |
| 42 | + pass |
| 43 | + |
| 44 | + await client.reconfigure_basin( |
| 45 | + basin_name, |
| 46 | + config=BasinConfig(stream_cipher=Encryption.AES_256_GCM), |
| 47 | + ) |
| 48 | + # ANCHOR_END: basin-cipher |
| 49 | + |
| 50 | + # Ensure stream exists |
| 51 | + try: |
| 52 | + await basin.create_stream(stream_name) |
| 53 | + except Exception: |
| 54 | + pass |
| 55 | + |
| 56 | + # ANCHOR: append-read |
| 57 | + stream = basin.stream( |
| 58 | + stream_name, |
| 59 | + encryption_key=os.environ["S2_ENCRYPTION_KEY"], |
| 60 | + ) |
| 61 | + |
| 62 | + await stream.append( |
| 63 | + AppendInput( |
| 64 | + records=[ |
| 65 | + Record(body=b"top secret"), |
| 66 | + ] |
| 67 | + ) |
| 68 | + ) |
| 69 | + |
| 70 | + batch = await stream.read( |
| 71 | + start=SeqNum(0), |
| 72 | + limit=ReadLimit(count=10), |
| 73 | + ) |
| 74 | + # ANCHOR_END: append-read |
| 75 | + print("Encryption examples ok", len(batch.records)) |
| 76 | + |
| 77 | + # Cleanup |
| 78 | + await basin.delete_stream(stream_name) |
| 79 | + |
| 80 | + print("Encryption examples completed") |
| 81 | + |
| 82 | + |
| 83 | +if __name__ == "__main__": |
| 84 | + asyncio.run(main()) |
0 commit comments