Play Strawberry Docs
Scripts

Data folder and persistence

Keep files in your private data folder and data on game objects, and check everything you read back.

Your private files

Context::get_data_folder() returns your script's data folder as seen from inside its sandbox. Ask for permissions::FS_READ_DATA to read and permissions::FS_WRITE_DATA to write (write includes read); without them the folder cannot be used. Inside it, use your language's normal file API (std::fs in Rust). Your script cannot reach server files, other scripts' folders or the host.

The folder belongs to the script's name. An update, a reload and an unload leave its files in place; a script with another name gets another, empty folder.

rust
const FILE: &str = "joins.txt";

/// Reads the saved count. A missing file is a first start; a damaged file is an error,
/// never silently replaced with 0.
fn load(folder: &PathBuf) -> Result<u64> {
    match fs::read_to_string(folder.join(FILE)) {
        Ok(text) => text.trim().parse().map_err(|_| format!("{FILE} is damaged")),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(0),
        Err(error) => Err(format!("cannot read {FILE}: {error}")),
    }
}

/// Writes a temporary file, then renames it over the old one: a crash in between
/// leaves the old file whole.
fn save(folder: &PathBuf, joins: u64) -> Result<()> {
    let temporary = folder.join("joins.tmp");
    fs::write(&temporary, joins.to_string()).map_err(|e| format!("cannot write: {e}"))?;
    fs::rename(&temporary, folder.join(FILE)).map_err(|e| format!("cannot replace: {e}"))
}
rust
impl Plugin for DataDemo {
    fn new() -> Self {
        Self
    }

    fn metadata(&self) -> PluginMetadata {
        PluginMetadata {
            name: "data-demo".into(),
            version: env!("CARGO_PKG_VERSION").into(),
            authors: vec!["Your name".into()],
            description: "Counts joins and keeps the count in its data folder.".into(),
            dependencies: Vec::new(),
            // Without these the data folder cannot be read or written.
            permissions: vec![permissions::FS_READ_DATA.into(), permissions::FS_WRITE_DATA.into()],
        }
    }

    fn on_load(&self, context: Context) -> Result<()> {
        let folder = PathBuf::from(context.get_data_folder());
        JOINS.store(load(&folder)?, Ordering::Relaxed);
        context.register_event_handler::<PlayerJoinEvent, _>(CountJoin, EventPriority::Normal, false)?;
        Ok(())
    }

    fn on_unload(&self, context: Context) -> Result<()> {
        let folder = PathBuf::from(context.get_data_folder());
        save(&folder, JOINS.load(Ordering::Relaxed))
    }
}

Safe state

  • Version the format you save and check it before use.
  • Bound file sizes, record counts and strings you decode.
  • Reject path separators and .. in names that come from players.
  • Write a temporary file and rename it over the old one. Never replace a damaged file with empty data without saying so.

Data on game objects

PersistentDataHolder stores typed values under a namespace and a key on items, entities, players, block entities, chunks and worlds (Paper's PersistentDataContainer). The values travel with the object and are saved with it: set_string, get_int, set_bool and the other typed helpers, or set_custom_data with an NbtTree.

On items, entities, players, block entities and chunks the values are saved where Paper saves its PersistentDataContainer data, each under namespace:key, so this data stays readable when a world moves between Paper and Play Strawberry.

Where file work runs

A sync task or a blocking handler holds the game up while it reads or writes. Do slow file work in an async task (see Scheduler), and remember that your other calls wait while it runs.

files::write_atomic(path, bytes) hands a save to the server instead. The server replaces the file safely without holding up your calls, and the returned job tells you when it is on disk. One write is at most 16 MiB.

Reserved file names

Do not name a file of your own .strawberry-write-*.tmp. The server uses these names for its temporary files and removes leftovers when your script loads.

On this page